"use client";

import { useEffect, useRef, useState } from "react";
import {
  LIGHTHOUSE_LABELS,
  type LighthouseScores,
  type PageSpeedData,
} from "@/lib/realisations";
import { ScoreGauge } from "./score-gauge";

type Strategy = "mobile" | "desktop";

export function RealisationPageSpeed({ data }: { data: PageSpeedData }) {
  const ref = useRef<HTMLDivElement | null>(null);
  const [active, setActive] = useState(false);

  const has = { mobile: !!data.mobile, desktop: !!data.desktop };
  const initial: Strategy = data.mobile ? "mobile" : "desktop";
  const [strategy, setStrategy] = useState<Strategy>(initial);

  useEffect(() => {
    const node = ref.current;
    if (!node) return;
    if (typeof IntersectionObserver === "undefined") {
      setActive(true);
      return;
    }
    const obs = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          if (e.isIntersecting) {
            setActive(true);
            obs.disconnect();
            break;
          }
        }
      },
      { threshold: 0.3 },
    );
    obs.observe(node);
    return () => obs.disconnect();
  }, []);

  const scores: LighthouseScores | undefined =
    strategy === "mobile" ? data.mobile : data.desktop;
  if (!scores) return null;

  return (
    <div ref={ref} className="panel p-6 md:p-8">
      <div className="flex items-center justify-between gap-4 flex-wrap">
        <div>
          <div className="text-micro uppercase tracking-wider text-text-faint">
            PageSpeed Insights · Lighthouse
          </div>
          <h3 className="font-editorial mt-1 text-xl md:text-2xl font-medium text-text">
            Mesuré, pas raconté.
          </h3>
        </div>
        {has.mobile && has.desktop && (
          <div
            role="tablist"
            aria-label="Stratégie de mesure"
            className="inline-flex items-center rounded-full border border-border bg-stone-900/[0.03] p-0.5"
          >
            <StrategyTab active={strategy === "mobile"} onClick={() => setStrategy("mobile")}>
              Mobile
            </StrategyTab>
            <StrategyTab
              active={strategy === "desktop"}
              onClick={() => setStrategy("desktop")}
            >
              Desktop
            </StrategyTab>
          </div>
        )}
      </div>

      <div
        className="mt-8 grid grid-cols-2 md:grid-cols-4 gap-4"
        // re-déclenche l'animation quand on switch de stratégie
        key={strategy}
      >
        {LIGHTHOUSE_LABELS.map(({ key, label }, i) => (
          <ScoreGauge
            key={`${strategy}-${key}`}
            target={scores[key]}
            label={label}
            active={active}
            delay={i * 120}
          />
        ))}
      </div>

      {data.fetchedAt && (
        <p className="mt-6 text-micro text-text-faint text-center italic">
          Mesure du{" "}
          {new Date(data.fetchedAt).toLocaleDateString("fr-FR", {
            day: "numeric",
            month: "long",
            year: "numeric",
          })}
          , source : Google PageSpeed Insights.
        </p>
      )}
    </div>
  );
}

function StrategyTab({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      role="tab"
      aria-selected={active}
      onClick={onClick}
      className={`px-3 py-1 text-xs rounded-full transition-colors cursor-pointer ${
        active
          ? "bg-accent text-accent-fg font-semibold"
          : "text-text-muted hover:text-text"
      }`}
    >
      {children}
    </button>
  );
}
