"use client";

import { useEffect, useState } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { loadSubscriptions } from "@/lib/finance/subscriptions-store";

type TabKey = "detected" | "tracked";

/**
 * Thin client shell that picks the default tab based on which side has data.
 *
 * Both panels are kept mounted (`forceMount`) so the detector's transaction
 * fetch runs even while the user is looking at the tracked tab — switching
 * tabs is then instant and no work is lost.
 *
 * The `<Tabs>` primitive captures `defaultValue` on first render, so we
 * delay rendering it until we've read the manual store. That avoids a
 * one-frame flicker from "detected" to "tracked" on users who use the
 * manager regularly.
 */
export function SubscriptionsTabs({
  detector,
  manager,
}: {
  detector: React.ReactNode;
  manager: React.ReactNode;
}) {
  const [defaultTab, setDefaultTab] = useState<TabKey | null>(null);

  useEffect(() => {
    // One-time hydration from localStorage. Same pattern as `useLocalStorage`
    // in `src/lib/hooks/use-local-storage.ts` — we can't read window during
    // SSR / first render, so we sync once on mount and then never again.
    let next: TabKey = "detected";
    try {
      const tracked = loadSubscriptions();
      next = tracked.length > 0 ? "tracked" : "detected";
    } catch {
      next = "detected";
    }
    // eslint-disable-next-line react-hooks/set-state-in-effect -- one-time hydration from localStorage
    setDefaultTab(next);
  }, []);

  if (defaultTab === null) {
    // First paint: render the detector eagerly so SSR / initial paint isn't
    // empty, but no tab chrome yet. The hydration effect above flips this in
    // the next tick.
    return <div className="space-y-6">{detector}</div>;
  }

  return (
    <Tabs defaultValue={defaultTab}>
      <TabsList>
        <TabsTrigger value="detected">Detected</TabsTrigger>
        <TabsTrigger value="tracked">Tracked</TabsTrigger>
      </TabsList>
      <TabsContent value="detected" forceMount>
        {detector}
      </TabsContent>
      <TabsContent value="tracked" forceMount>
        {manager}
      </TabsContent>
    </Tabs>
  );
}
