const { useState, useCallback } = React;

function App() {
  const [dossierId, setDossierId] = useState(null);
  const [view, setView] = useState('landing');
  const [email, setEmail] = useState('');
  const [emailError, setEmailError] = useState('');
  const [isCreating, setIsCreating] = useState(false);

  const handleEmailSubmit = useCallback(async (e) => {
    e.preventDefault();
    const trimmed = email.trim();

    if (!trimmed || !trimmed.includes('@') || !trimmed.includes('.')) {
      setEmailError('Entrez une adresse email valide');
      return;
    }

    setEmailError('');
    setIsCreating(true);

    try {
      const res = await fetch('/api/session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: trimmed })
      });
      const data = await res.json();

      if (data.dossierId) {
        setDossierId(data.dossierId);
        setView('chat');
      } else {
        setEmailError(data.error || 'Impossible de creer le dossier');
      }
    } catch (err) {
      setEmailError('Erreur de connexion au serveur');
    } finally {
      setIsCreating(false);
    }
  }, [email]);

  // ─── LANDING ─────────────────────────────────────────────
  if (view === 'landing') {
    return (
      <div className="min-h-screen flex flex-col gradient-bg">
        {/* Nav */}
        <nav className="px-5 md:px-8 py-4 md:py-5 flex items-center justify-between max-w-6xl mx-auto w-full">
          <div className="flex items-center gap-2.5">
            <div className="w-9 h-9 rounded-xl bg-brand-500 flex items-center justify-center shadow-md">
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5">
                <path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/>
              </svg>
            </div>
            <span className="font-display font-bold text-lg text-ink-900">SinistrAI</span>
          </div>
          <span className="text-xs font-semibold px-3.5 py-1.5 rounded-full bg-brand-100 text-brand-700 tracking-wide">
            Expert Sinistre
          </span>
        </nav>

        {/* Hero */}
        <main className="flex-1 flex items-center">
          <div className="max-w-6xl mx-auto px-5 md:px-8 w-full grid lg:grid-cols-2 gap-10 lg:gap-16 items-center py-8 md:py-12">

            {/* Left — Copy */}
            <div className="anim-fade-up">
              <div className="inline-flex items-center gap-2 text-xs font-semibold px-3.5 py-1.5 rounded-full bg-emerald-50 text-emerald-600 mb-6">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
                IA + Expertise juridique
              </div>

              <h1 className="font-display font-bold tracking-tight leading-[1.05] mb-6 text-ink-900" style={{ fontSize: 'clamp(2rem, 5vw, 3.5rem)' }}>
                Votre assureur<br/>
                minimise votre<br/>
                <span className="gradient-text">indemnisation ?</span>
              </h1>

              <p className="text-base md:text-lg leading-relaxed max-w-md mb-8 md:mb-10 text-ink-500">
                Notre IA analyse votre dossier sinistre, identifie les failles
                du rapport d'expertise adverse et produit un rapport de defense
                avec arguments juridiques en 15 minutes.
              </p>

              <button
                onClick={() => setView('email')}
                className="btn-primary group inline-flex items-center gap-3 font-semibold text-base md:text-lg px-7 md:px-8 py-3.5 md:py-4 rounded-xl text-white w-full sm:w-auto justify-center"
              >
                Analyser mon dossier
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="group-hover:translate-x-1 transition-transform">
                  <path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>
                </svg>
              </button>

              <div className="flex flex-wrap items-center gap-4 md:gap-6 mt-6 md:mt-8">
                <div className="flex items-center gap-2 text-sm text-ink-400">
                  <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/>
                  </svg>
                  A partir de 79 EUR
                </div>
                <div className="flex items-center gap-2 text-sm text-ink-400">
                  <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
                  </svg>
                  Rapport en 15 min
                </div>
                <div className="flex items-center gap-2 text-sm text-ink-400">
                  <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10"/>
                  </svg>
                  Paiement securise
                </div>
              </div>
            </div>

            {/* Right — Visual */}
            <div className="hidden lg:block anim-fade-up-d2">
              <div className="relative">
                {/* Card stack effect */}
                <div className="absolute -top-3 -left-3 w-full h-full rounded-2xl border border-ink-200 rotate-[-2deg]"></div>
                <div className="absolute -top-1.5 -left-1.5 w-full h-full rounded-2xl border border-ink-200 rotate-[-1deg] bg-white"></div>

                <div className="relative bg-white rounded-2xl border border-ink-200 p-8 shadow-xl shadow-brand-500/5">
                  {/* Fake report preview */}
                  <div className="flex items-center gap-3 mb-6">
                    <div className="w-10 h-10 rounded-xl bg-brand-100 flex items-center justify-center">
                      <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#d97706" strokeWidth="2">
                        <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/>
                      </svg>
                    </div>
                    <div>
                      <p className="font-semibold text-sm text-ink-900">Rapport de defense</p>
                      <p className="text-xs text-ink-400">PDF — 12 pages</p>
                    </div>
                    <span className="ml-auto text-xs font-semibold px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-600">
                      Livre
                    </span>
                  </div>

                  <div className="space-y-3">
                    <div className="h-3 rounded-full w-full bg-ink-100"></div>
                    <div className="h-3 rounded-full w-4/5 bg-ink-100"></div>
                    <div className="h-3 rounded-full w-3/4 bg-ink-100"></div>
                  </div>

                  <div className="mt-6 p-4 rounded-xl bg-brand-50">
                    <p className="text-xs font-bold mb-2.5 text-brand-700">Failles identifiees</p>
                    <div className="space-y-2">
                      <div className="flex items-center gap-2">
                        <span className="w-1.5 h-1.5 rounded-full bg-brand-500"></span>
                        <span className="text-xs text-ink-600">Sous-evaluation des degats constates</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="w-1.5 h-1.5 rounded-full bg-brand-500"></span>
                        <span className="text-xs text-ink-600">Non-respect art. L113-5 Code assurances</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="w-1.5 h-1.5 rounded-full bg-brand-500"></span>
                        <span className="text-xs text-ink-600">Methodologie d'evaluation contestable</span>
                      </div>
                    </div>
                  </div>

                  <div className="mt-6 grid grid-cols-3 gap-3">
                    <div className="text-center p-3 rounded-xl bg-ink-50">
                      <p className="text-xl font-bold text-brand-500">5</p>
                      <p className="text-xs mt-0.5 text-ink-400">Failles</p>
                    </div>
                    <div className="text-center p-3 rounded-xl bg-ink-50">
                      <p className="text-xl font-bold text-brand-500">7</p>
                      <p className="text-xs mt-0.5 text-ink-400">Ref. juridiques</p>
                    </div>
                    <div className="text-center p-3 rounded-xl bg-ink-50">
                      <p className="text-xl font-bold text-emerald-600">1</p>
                      <p className="text-xs mt-0.5 text-ink-400">Courrier type</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </main>

        {/* Social proof / trust strip */}
        <div className="border-t border-brand-200/50 py-6 md:py-8">
          <div className="max-w-6xl mx-auto px-5 md:px-8">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-8">
              <div className="text-center">
                <p className="text-2xl font-bold font-display text-brand-600">97%</p>
                <p className="text-xs text-ink-400 mt-1">Taux de satisfaction</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold font-display text-brand-600">15 min</p>
                <p className="text-xs text-ink-400 mt-1">Delai moyen</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold font-display text-brand-600">+40%</p>
                <p className="text-xs text-ink-400 mt-1">Indemnisation moyenne</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold font-display text-brand-600">RGPD</p>
                <p className="text-xs text-ink-400 mt-1">Donnees protegees</p>
              </div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <footer className="px-5 md:px-8 py-5 text-center border-t border-ink-200/50">
          <p className="text-xs text-ink-400">
            SinistrAI Expert est un assistant IA. Les rapports produits ne constituent pas un avis juridique.
          </p>
        </footer>
      </div>
    );
  }

  // ─── EMAIL CAPTURE ─────────────────────────────────────────
  if (view === 'email') {
    return (
      <div className="min-h-screen flex items-center justify-center px-5 md:px-8 bg-ink-50">
        <div className="w-full max-w-md anim-fade-up">
          <button
            onClick={() => setView('landing')}
            className="flex items-center gap-2 text-sm mb-8 text-ink-400 hover:text-ink-700 transition-colors"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>
            </svg>
            Retour
          </button>

          <div className="bg-white rounded-2xl border border-ink-200 p-6 md:p-8 shadow-lg shadow-ink-900/5">
            <div className="flex items-center gap-3 mb-6">
              <div className="w-11 h-11 rounded-xl bg-brand-500 flex items-center justify-center shadow-md shadow-brand-500/30">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5">
                  <path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/>
                </svg>
              </div>
              <div>
                <h2 className="font-display font-bold text-xl text-ink-900">Commencer l'analyse</h2>
                <p className="text-sm text-ink-400">Votre rapport sera envoye a cette adresse</p>
              </div>
            </div>

            <form onSubmit={handleEmailSubmit}>
              <label className="block text-sm font-semibold mb-2 text-ink-700">
                Adresse email
              </label>
              <input
                type="email"
                value={email}
                onChange={e => { setEmail(e.target.value); setEmailError(''); }}
                placeholder="vous@exemple.fr"
                autoFocus
                className={`w-full px-4 py-3.5 rounded-xl border-2 text-base text-ink-900 bg-ink-50 transition-all duration-200 focus:outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-500/10 placeholder:text-ink-300 ${
                  emailError ? 'border-red-400' : 'border-ink-200'
                }`}
              />
              {emailError && (
                <p className="text-sm mt-2 text-red-500 font-medium">{emailError}</p>
              )}

              <button
                type="submit"
                disabled={isCreating}
                className="btn-primary w-full mt-5 font-semibold text-base px-6 py-3.5 rounded-xl text-white disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {isCreating ? (
                  <>
                    <svg className="anim-spin-slow" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                      <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
                    </svg>
                    Creation du dossier...
                  </>
                ) : (
                  'Continuer'
                )}
              </button>
            </form>

            <p className="text-xs mt-5 leading-relaxed text-ink-400 text-center">
              En continuant, vous acceptez que vos donnees soient traitees pour l'analyse de votre dossier.
              Donnees supprimees sous 90 jours (RGPD).
            </p>
          </div>
        </div>
      </div>
    );
  }

  // ─── CHAT ────────────────────────────────────────────────
  if (view === 'chat') {
    return (
      <div className="h-screen flex flex-col bg-ink-50">
        {/* Header */}
        <header className="glass px-4 md:px-6 py-3 flex items-center justify-between border-b border-ink-200/70 z-10">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-xl bg-brand-500 flex items-center justify-center shadow-sm">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5">
                <path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/>
              </svg>
            </div>
            <div>
              <p className="font-display font-bold text-sm text-ink-900">SinistrAI Expert</p>
              <p className="text-xs text-ink-400">Dossier {dossierId?.slice(0, 8).toUpperCase()}</p>
            </div>
          </div>
          <Upload dossierId={dossierId} />
        </header>

        <Chat dossierId={dossierId} onPaymentComplete={() => setView('status')} />
      </div>
    );
  }

  // ─── STATUS ──────────────────────────────────────────────
  if (view === 'status') {
    return (
      <div className="min-h-screen bg-ink-50">
        <header className="glass px-4 md:px-6 py-4 border-b border-ink-200/70">
          <div className="flex items-center gap-3 max-w-3xl mx-auto">
            <div className="w-9 h-9 rounded-xl bg-brand-500 flex items-center justify-center shadow-sm">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5">
                <path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/>
              </svg>
            </div>
            <span className="font-display font-bold text-ink-900">SinistrAI Expert</span>
          </div>
        </header>
        <Status dossierId={dossierId} />
      </div>
    );
  }

  return null;
}
