const { useState, useCallback } = React;

function App() {
  const [dossierId, setDossierId] = useState(null);
  const [view, setView] = useState('landing'); // landing | email | chat | status
  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">
        {/* Nav */}
        <nav className="px-6 py-5 flex items-center justify-between max-w-6xl mx-auto w-full">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: 'var(--brand)' }}>
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <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" style={{ color: 'var(--text)' }}>SinistrAI</span>
          </div>
          <span className="text-xs font-medium px-3 py-1 rounded-full" style={{ background: '#fef3c7', color: 'var(--brand-dark)' }}>
            Expert Sinistre
          </span>
        </nav>

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

            {/* Left — Copy */}
            <div className="animate-slide-up">
              <div className="inline-flex items-center gap-2 text-xs font-medium px-3 py-1.5 rounded-full mb-6" style={{ background: '#ecfdf5', color: 'var(--accent-green)' }}>
                <span className="w-1.5 h-1.5 rounded-full" style={{ background: 'var(--accent-green)' }}></span>
                IA + Expertise juridique
              </div>

              <h1 className="font-display font-bold tracking-tight leading-none mb-6" style={{ fontSize: 'clamp(2.2rem, 5vw, 3.5rem)', color: 'var(--text)' }}>
                Votre assureur<br/>
                minimise votre<br/>
                <span style={{ color: 'var(--brand)' }}>indemnisation ?</span>
              </h1>

              <p className="text-lg leading-relaxed max-w-md mb-10" style={{ color: 'var(--text-secondary)' }}>
                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="group inline-flex items-center gap-3 font-semibold text-lg px-8 py-4 rounded-xl text-white transition-all duration-200 hover:scale-105 hover:shadow-lg"
                style={{ background: 'var(--brand)' }}
              >
                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 items-center gap-6 mt-8">
                <div className="flex items-center gap-2 text-sm" style={{ color: 'var(--text-muted)' }}>
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 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" style={{ color: 'var(--text-muted)' }}>
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 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" style={{ color: 'var(--text-muted)' }}>
                  <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 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 animate-fade-in">
              <div className="relative">
                {/* Card stack effect */}
                <div className="absolute -top-3 -left-3 w-full h-full rounded-2xl border-2" style={{ borderColor: 'var(--border)', transform: 'rotate(-2deg)' }}></div>
                <div className="absolute -top-1.5 -left-1.5 w-full h-full rounded-2xl border-2" style={{ borderColor: 'var(--border)', transform: 'rotate(-1deg)', background: 'white' }}></div>

                <div className="relative bg-white rounded-2xl border-2 p-8" style={{ borderColor: 'var(--border)' }}>
                  {/* Fake report preview */}
                  <div className="flex items-center gap-3 mb-6">
                    <div className="w-10 h-10 rounded-lg flex items-center justify-center" style={{ background: '#fef3c7' }}>
                      <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" style={{ color: 'var(--text)' }}>Rapport de defense</p>
                      <p className="text-xs" style={{ color: 'var(--text-muted)' }}>PDF - 12 pages</p>
                    </div>
                    <span className="ml-auto text-xs font-medium px-2.5 py-1 rounded-full" style={{ background: '#ecfdf5', color: 'var(--accent-green)' }}>
                      Livre
                    </span>
                  </div>

                  <div className="space-y-3">
                    <div className="h-3 rounded-full w-full" style={{ background: '#f5f5f4' }}></div>
                    <div className="h-3 rounded-full w-4/5" style={{ background: '#f5f5f4' }}></div>
                    <div className="h-3 rounded-full w-3/4" style={{ background: '#f5f5f4' }}></div>
                  </div>

                  <div className="mt-6 p-4 rounded-xl" style={{ background: '#fffbeb' }}>
                    <p className="text-xs font-semibold mb-2" style={{ color: 'var(--brand-dark)' }}>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" style={{ background: 'var(--brand)' }}></span>
                        <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>Sous-evaluation des degats constates</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="w-1.5 h-1.5 rounded-full" style={{ background: 'var(--brand)' }}></span>
                        <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>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" style={{ background: 'var(--brand)' }}></span>
                        <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>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-lg" style={{ background: '#f5f5f4' }}>
                      <p className="text-xl font-bold" style={{ color: 'var(--brand)' }}>5</p>
                      <p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>Failles</p>
                    </div>
                    <div className="text-center p-3 rounded-lg" style={{ background: '#f5f5f4' }}>
                      <p className="text-xl font-bold" style={{ color: 'var(--brand)' }}>7</p>
                      <p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>Ref. juridiques</p>
                    </div>
                    <div className="text-center p-3 rounded-lg" style={{ background: '#f5f5f4' }}>
                      <p className="text-xl font-bold" style={{ color: 'var(--accent-green)' }}>1</p>
                      <p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>Courrier type</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </main>

        {/* Footer */}
        <footer className="px-6 py-6 text-center">
          <p className="text-xs" style={{ color: 'var(--text-muted)' }}>
            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-6" style={{ background: 'var(--bg)' }}>
        <div className="w-full max-w-md animate-fade-in">
          <button
            onClick={() => setView('landing')}
            className="flex items-center gap-2 text-sm mb-8 hover:opacity-70 transition-opacity"
            style={{ color: 'var(--text-secondary)' }}
          >
            <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="flex items-center gap-3 mb-8">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: 'var(--brand)' }}>
              <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" style={{ color: 'var(--text)' }}>Commencer l'analyse</h2>
              <p className="text-sm" style={{ color: 'var(--text-muted)' }}>Votre rapport sera envoye a cette adresse</p>
            </div>
          </div>

          <form onSubmit={handleEmailSubmit}>
            <label className="block text-sm font-medium mb-2" style={{ color: 'var(--text)' }}>
              Adresse email
            </label>
            <input
              type="email"
              value={email}
              onChange={e => { setEmail(e.target.value); setEmailError(''); }}
              placeholder="vous@exemple.fr"
              autoFocus
              className="email-input w-full px-4 py-3.5 rounded-xl border-2 text-base transition-colors"
              style={{
                borderColor: emailError ? 'var(--accent-red)' : 'var(--border)',
                color: 'var(--text)',
                background: 'var(--surface)'
              }}
            />
            {emailError && (
              <p className="text-sm mt-2" style={{ color: 'var(--accent-red)' }}>{emailError}</p>
            )}

            <button
              type="submit"
              disabled={isCreating}
              className="w-full mt-4 font-semibold text-base px-6 py-3.5 rounded-xl text-white transition-all duration-200 hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              style={{ background: 'var(--brand)' }}
            >
              {isCreating ? (
                <>
                  <svg className="animate-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-6 leading-relaxed" style={{ color: 'var(--text-muted)' }}>
            En continuant, vous acceptez que vos donnees soient traitees pour l'analyse de votre dossier.
            Donnees supprimees sous 90 jours (RGPD).
          </p>
        </div>
      </div>
    );
  }

  // ─── CHAT ────────────────────────────────────────────────
  if (view === 'chat') {
    return (
      <div className="h-screen flex flex-col" style={{ background: 'var(--bg)' }}>
        {/* Header */}
        <header className="px-6 py-3 flex items-center justify-between border-b" style={{ background: 'var(--surface)', borderColor: 'var(--border)' }}>
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: 'var(--brand)' }}>
              <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" style={{ color: 'var(--text)' }}>SinistrAI Expert</p>
              <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Assistant IA — 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" style={{ background: 'var(--bg)' }}>
        <header className="px-6 py-4 border-b" style={{ background: 'var(--surface)', borderColor: 'var(--border)' }}>
          <div className="flex items-center gap-3 max-w-3xl mx-auto">
            <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: 'var(--brand)' }}>
              <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" style={{ color: 'var(--text)' }}>SinistrAI Expert</span>
          </div>
        </header>
        <Status dossierId={dossierId} />
      </div>
    );
  }

  return null;
}
