// src/components/keywords/overview/overview-container.tsx
"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { Skeleton } from "@/components/ui/skeleton";
import { getKeywordOverviewAction } from "@/lib/keywords/actions";
import type { KeywordOverview } from "@/lib/keywords/overview";
import { useActiveSite } from "@/lib/keywords/site-context";
import { BacklinksCard } from "./backlinks-card";
import { BreakdownCard } from "./breakdown-card";
import { GscPerformanceHero } from "./gsc-performance-hero";
import { KdHistogram } from "./kd-histogram";
import { OpportunitiesCard } from "./opportunities-card";
import { OverviewKpis } from "./overview-kpis";
import { StagesFunnel } from "./stages-funnel";
import { TopVolumeCard } from "./top-volume-card";

export function OverviewContainer({
  initialOverview,
  initialSiteId,
}: {
  initialOverview: KeywordOverview | null;
  initialSiteId: string;
}) {
  const { activeSiteId } = useActiveSite();
  const [ov, setOv] = useState<KeywordOverview | null>(initialOverview);
  const [loading, setLoading] = useState(false);
  // The server already provided the overview for this site. Track the loaded
  // site so we never refetch on mount — firing a read server action on mount
  // triggers an implicit route revalidation that races and deadlocks the next
  // client navigation.
  const loadedSite = useRef(initialSiteId);

  const load = useCallback(async () => {
    setLoading(true);
    const data = await getKeywordOverviewAction(activeSiteId);
    setOv(data);
    setLoading(false);
  }, [activeSiteId]);

  useEffect(() => {
    // Only refetch when the active site actually changes — never on mount.
    if (activeSiteId === loadedSite.current) return;
    loadedSite.current = activeSiteId;
    void load().catch(() => setLoading(false));
  }, [activeSiteId, load]);

  if (loading || !ov) {
    return (
      <div className="space-y-3 p-4">
        <Skeleton className="h-28 w-full" />
        <Skeleton className="h-20 w-full" />
        <Skeleton className="h-64 w-full" />
      </div>
    );
  }

  if (ov.totalKeywords === 0) {
    return (
      <div className="flex h-64 flex-col items-center justify-center gap-2 text-muted-foreground">
        <p>Aucun mot-clé pour ce site.</p>
        <p className="text-sm">
          Importe un CSV ou « Importer depuis GSC » depuis le Reservoir.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4 p-4">
      <GscPerformanceHero ov={ov} />
      <OverviewKpis ov={ov} />
      <div className="grid gap-4 lg:grid-cols-3">
        <div className="lg:col-span-2">
          <OpportunitiesCard ov={ov} />
        </div>
        <BreakdownCard ov={ov} />
      </div>
      <div className="grid gap-4 lg:grid-cols-2">
        <KdHistogram ov={ov} />
        <TopVolumeCard ov={ov} />
      </div>
      <div className="grid gap-4 lg:grid-cols-2">
        <StagesFunnel ov={ov} />
        <BacklinksCard ov={ov} />
      </div>
    </div>
  );
}
