import { useEffect, useRef, useState } from 'react';

import { cn } from '@/lib/utils';

interface HeroDashboardMockupProps {
  className?: string;
}

function useReducedMotion(): boolean {
  const [reduced, setReduced] = useState(() => {
    if (typeof window === 'undefined') return false;
    return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  });
  useEffect(() => {
    const mql = window.matchMedia('(prefers-reduced-motion: reduce)');
    const handler = (e: MediaQueryListEvent) => setReduced(e.matches);
    mql.addEventListener('change', handler);
    return () => mql.removeEventListener('change', handler);
  }, []);
  return reduced;
}

function AnimatedPercentage({ target, reducedMotion }: { target: number; reducedMotion: boolean }) {
  const [value, setValue] = useState(reducedMotion ? target : 0);
  const ref = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    if (reducedMotion) {
      setValue(target);
      return;
    }

    let start: number | null = null;
    const duration = 1200;
    let rafId: number;

    const animate = (timestamp: number) => {
      if (start === null) start = timestamp;
      const progress = Math.min((timestamp - start) / duration, 1);
      // ease-out cubic
      const eased = 1 - Math.pow(1 - progress, 3);
      setValue(Math.round(eased * target));
      if (progress < 1) {
        rafId = requestAnimationFrame(animate);
      }
    };

    // Start animation when element is visible
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          rafId = requestAnimationFrame(animate);
          observer.disconnect();
        }
      },
      { threshold: 0.5 },
    );

    if (ref.current) observer.observe(ref.current);

    return () => {
      observer.disconnect();
      cancelAnimationFrame(rafId);
    };
  }, [target, reducedMotion]);

  return <span ref={ref}>+{value}% ↑</span>;
}

export function HeroDashboardMockup({ className }: HeroDashboardMockupProps) {
  const reducedMotion = useReducedMotion();

  const weeklyData = [
    { week: 'W1', before: 420, after: null },
    { week: 'W2', before: 445, after: null },
    { week: 'W3', before: 410, after: null },
    { week: 'W4', before: 460, after: 410 },
    { week: 'W5', before: null, after: 495 },
    { week: 'W6', before: null, after: 540 },
    { week: 'W7', before: null, after: 612 },
    { week: 'W8', before: null, after: 680 },
  ];

  const maxVal = 720;
  const barW = 14;
  const gap = 6;
  const groupW = barW * 2 + gap + 10;
  const chartH = 80;
  const chartW = groupW * 8 + 4;
  const cutoffX = 3.5 * groupW + barW / 2;

  const recommendations = [
    { action: 'Content Rewrite', page: '/blog/seo-tips-2024', impact: 87, badge: 'High' as const },
    {
      action: 'Meta Tag Update',
      page: '/services/wordpress-seo',
      impact: 64,
      badge: 'Medium' as const,
    },
  ];

  // Flatten bars into a sequential index for stagger delay
  let barIndex = 0;

  return (
    <div
      className={cn(
        'rounded-xl overflow-hidden border border-border/50 bg-card shadow-2xl',
        className,
      )}
      role="img"
      aria-label="RankWiz dashboard preview showing traffic recovery after applying SEO recommendations"
    >
      <style>{`
        @keyframes barGrow {
          from { transform: scaleY(0); }
          to { transform: scaleY(1); }
        }
        @keyframes impactFill {
          from { width: 0%; }
        }
        @media (prefers-reduced-motion: reduce) {
          .mockup-bar, .mockup-impact-bar {
            animation: none !important;
          }
        }
      `}</style>

      {/* Browser chrome */}
      <div className="flex items-center gap-2 px-4 py-2.5 bg-muted/60 border-b border-border/40">
        <div className="flex gap-1.5">
          <span className="w-2.5 h-2.5 rounded-full bg-rose-400/70" />
          <span className="w-2.5 h-2.5 rounded-full bg-warning/70" />
          <span className="w-2.5 h-2.5 rounded-full bg-success/70" />
        </div>
        <div className="flex-1 mx-3 bg-background/70 rounded px-3 py-0.5 text-xs text-muted-foreground font-mono truncate">
          rankwiz.app — myblog.com
        </div>
      </div>

      {/* Dashboard content */}
      <div className="p-4 grid grid-cols-2 gap-4">
        {/* Chart panel */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-xs font-semibold text-foreground">Weekly Clicks</span>
            <span className="text-xs font-medium text-success">
              <AnimatedPercentage target={62} reducedMotion={reducedMotion} />
            </span>
          </div>
          <svg width={chartW} height={chartH + 16} className="overflow-visible" aria-hidden="true">
            {weeklyData.map((d, i) => {
              const x = i * groupW;
              const beforeBar =
                d.before !== null
                  ? (() => {
                      const idx = barIndex++;
                      return (
                        <rect
                          key={`before-${d.week}`}
                          x={0}
                          y={chartH - (d.before / maxVal) * chartH}
                          width={barW}
                          height={(d.before / maxVal) * chartH}
                          rx={2}
                          className="mockup-bar fill-muted-foreground/25"
                          style={
                            reducedMotion
                              ? undefined
                              : {
                                  transformOrigin: `${barW / 2}px ${chartH}px`,
                                  animation: `barGrow 0.5s ease-out ${idx * 100}ms both`,
                                }
                          }
                        />
                      );
                    })()
                  : null;

              const afterBar =
                d.after !== null
                  ? (() => {
                      const idx = barIndex++;
                      return (
                        <rect
                          key={`after-${d.week}`}
                          x={barW + gap}
                          y={chartH - (d.after / maxVal) * chartH}
                          width={barW}
                          height={(d.after / maxVal) * chartH}
                          rx={2}
                          className="mockup-bar fill-success/75"
                          style={
                            reducedMotion
                              ? undefined
                              : {
                                  transformOrigin: `${barW + gap + barW / 2}px ${chartH}px`,
                                  animation: `barGrow 0.5s ease-out ${idx * 100}ms both`,
                                }
                          }
                        />
                      );
                    })()
                  : null;

              return (
                <g key={d.week} transform={`translate(${x}, 2)`}>
                  {beforeBar}
                  {afterBar}
                </g>
              );
            })}

            {/* Analysis cutoff line */}
            <line
              x1={cutoffX}
              y1={2}
              x2={cutoffX}
              y2={chartH + 2}
              strokeDasharray="3 3"
              strokeWidth={1}
              className="stroke-primary/40"
            />

            {/* "Fix applied" annotation */}
            <text
              x={cutoffX}
              y={chartH + 14}
              textAnchor="middle"
              className="fill-primary/60 animate-pulse-soft"
              style={{ fontSize: '7px' }}
            >
              Fix applied
            </text>

            {/* X-axis "Weeks" label */}
            <text
              x={chartW / 2}
              y={chartH + 14}
              textAnchor="middle"
              className="fill-muted-foreground/50"
              style={{ fontSize: '7px' }}
            >
              Weeks
            </text>
          </svg>
          <div className="flex items-center gap-3">
            <span className="flex items-center gap-1 text-xs text-muted-foreground">
              <span className="inline-block w-3 h-2 rounded-sm bg-muted-foreground/25" />
              Before
            </span>
            <span className="flex items-center gap-1 text-xs text-muted-foreground">
              <span className="inline-block w-3 h-2 rounded-sm bg-success/75" />
              After fix
            </span>
          </div>
        </div>

        {/* Recommendations panel */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-xs font-semibold text-foreground">AI Recommendations</span>
            <span className="text-xs text-muted-foreground">3 ready</span>
          </div>
          <div className="space-y-2">
            {recommendations.map((rec, recIdx) => (
              <div
                key={rec.page}
                className="rounded-lg border border-border/50 p-2.5 bg-background/60"
              >
                <div className="flex items-center justify-between mb-0.5">
                  <span className="text-xs font-medium text-foreground">{rec.action}</span>
                  <span
                    className={cn(
                      'text-xs px-1.5 py-px rounded-full font-medium',
                      rec.badge === 'High'
                        ? 'bg-success/15 text-success'
                        : 'bg-warning/15 text-warning',
                    )}
                  >
                    {rec.badge}
                  </span>
                </div>
                <p className="text-xs text-muted-foreground truncate mb-1.5">{rec.page}</p>
                <div className="h-1.5 rounded-full bg-muted/60 overflow-hidden">
                  <div
                    className="mockup-impact-bar h-full rounded-full bg-success/70"
                    style={
                      reducedMotion
                        ? { width: `${rec.impact}%` }
                        : {
                            width: `${rec.impact}%`,
                            animation: `impactFill 0.8s ease-out ${800 + recIdx * 200}ms both`,
                          }
                    }
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
