"use client";

import { useEffect, useState } from "react";

interface DemoSeedTriggerProps {
  hasTraces: boolean;
  children: React.ReactNode;
}

export function DemoSeedTrigger({ hasTraces, children }: DemoSeedTriggerProps) {
  const [seeding, setSeeding] = useState(false);

  useEffect(() => {
    if (hasTraces || seeding) return;

    async function seedIfNeeded() {
      setSeeding(true);
      try {
        const res = await fetch("/api/demo/seed", { method: "POST" });
        if (res.ok) {
          window.location.reload();
        }
      } catch {
        // Seed failed, continue showing empty state
      } finally {
        setSeeding(false);
      }
    }

    seedIfNeeded();
  }, [hasTraces, seeding]);

  if (!hasTraces && seeding) {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-center">
        <div className="w-10 h-10 rounded-xl border-2 border-emerald-500/30 border-t-emerald-500 animate-spin mb-4" />
        <p className="text-sm text-neutral-400">Setting up your workspace with sample data...</p>
      </div>
    );
  }

  return <>{children}</>;
}
