'use client';

import { useEffect, useState } from 'react';
import { Sparkles, Wand2, Image as ImageIcon, Code2, Shield, CheckCircle2 } from 'lucide-react';
import { cn } from '@/lib/utils';

/**
 * Multi-Step-Loader während die Pipeline läuft.
 * Echte Phasen sind nicht real-time observable — wir simulieren die Timeline:
 *  0-30s : Strategie (Sonnet)
 *  30-38s: Hero-Bild (fal.ai)
 *  38-39s: MJML-Render (mjml@5)
 *  39-40s: Spam-Check
 */

interface Step {
  key: string;
  label: string;
  hint: string;
  icon: typeof Sparkles;
  expectedSec: number;
}

const STEPS: Step[] = [
  { key: 'strategy', label: 'Strategie & Body', hint: 'Sonnet schreibt Subjects, Hero-Headline, Vorteile, CTA …', icon: Wand2, expectedSec: 30 },
  { key: 'hero',     label: 'Hero-Bild',         hint: 'fal.ai gpt-image rendert das Lifestyle-Bild …',          icon: ImageIcon, expectedSec: 8 },
  { key: 'mjml',     label: 'MJML → HTML',       hint: 'Outlook-safe Tabellen-Layout, Inline-CSS …',             icon: Code2, expectedSec: 1 },
  { key: 'spam',     label: 'Spam-Check',        hint: 'Pre-Flight Validierung gegen 13 Regeln …',              icon: Shield, expectedSec: 1 },
];

export function GenerateLoader({ heroEnabled = true }: { heroEnabled?: boolean }) {
  const visibleSteps = STEPS.filter(s => s.key !== 'hero' || heroEnabled);
  const [elapsedSec, setElapsedSec] = useState(0);

  useEffect(() => {
    const start = Date.now();
    const tick = setInterval(() => {
      setElapsedSec((Date.now() - start) / 1000);
    }, 250);
    return () => clearInterval(tick);
  }, []);

  // Berechne aktuellen Schritt basierend auf elapsed
  let cursor = 0;
  let currentStep = 0;
  for (let i = 0; i < visibleSteps.length; i++) {
    cursor += visibleSteps[i].expectedSec;
    if (elapsedSec < cursor) { currentStep = i; break; }
    currentStep = i + 1;
  }

  return (
    <div className="flex h-full flex-col items-center justify-center gap-8 p-8">
      {/* Hauptanimation */}
      <div className="relative">
        <div className="absolute inset-0 animate-ping rounded-full bg-[#ff006a]/30" />
        <div className="relative flex h-20 w-20 items-center justify-center rounded-full bg-gradient-to-br from-[#ff006a] to-[#c70054] shadow-lg shadow-[#ff006a]/30">
          <Sparkles className="h-10 w-10 animate-pulse text-white" />
        </div>
      </div>

      <div className="text-center">
        <h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100">
          Marketing-Email wird generiert
        </h2>
        <p className="mt-1 text-sm text-zinc-500">
          Das dauert ca. {visibleSteps.reduce((a, s) => a + s.expectedSec, 0)} Sekunden — ein Kaffee-Moment.
        </p>
        <p className="mt-1 font-mono text-xs text-zinc-400">{elapsedSec.toFixed(1)}s</p>
      </div>

      {/* Schritt-Liste */}
      <ol className="flex w-full max-w-md flex-col gap-3">
        {visibleSteps.map((step, i) => {
          const Icon = step.icon;
          const isPast = i < currentStep;
          const isCurrent = i === currentStep;
          const isFuture = i > currentStep;
          return (
            <li
              key={step.key}
              className={cn(
                'flex items-start gap-3 rounded-lg border p-3 transition',
                isCurrent && 'border-pink-200 bg-pink-50 shadow-sm dark:border-pink-900/50 dark:bg-pink-950/30',
                isPast && 'border-emerald-200 bg-emerald-50/50 dark:border-emerald-900/50 dark:bg-emerald-950/20',
                isFuture && 'border-zinc-200 bg-zinc-50/50 opacity-50 dark:border-zinc-800 dark:bg-zinc-900/30',
              )}
            >
              <div
                className={cn(
                  'flex h-8 w-8 shrink-0 items-center justify-center rounded-full',
                  isPast && 'bg-emerald-500 text-white',
                  isCurrent && 'bg-[#ff006a] text-white',
                  isFuture && 'bg-zinc-200 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-500',
                )}
              >
                {isPast ? (
                  <CheckCircle2 className="h-4 w-4" />
                ) : isCurrent ? (
                  <Icon className="h-4 w-4 animate-pulse" />
                ) : (
                  <Icon className="h-4 w-4" />
                )}
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex items-baseline justify-between gap-2">
                  <span className={cn(
                    'text-sm font-medium',
                    isCurrent ? 'text-pink-900 dark:text-pink-200' : isPast ? 'text-emerald-800 dark:text-emerald-300' : 'text-zinc-500',
                  )}>
                    {step.label}
                  </span>
                  <span className="text-[10px] text-zinc-400">~{step.expectedSec}s</span>
                </div>
                <p className={cn(
                  'mt-0.5 text-xs',
                  isCurrent ? 'text-pink-700 dark:text-pink-300' : 'text-zinc-500',
                )}>
                  {step.hint}
                </p>
              </div>
            </li>
          );
        })}
      </ol>
    </div>
  );
}
