// marketing.jsx — Homepage, Login, Signup, Forgot, 404

// ─────── Top marketing nav ───────

function MarketNav({ navigate, currentRoute }) {
  return (
    <nav className="market-nav">
      <div className="row gap-3" style={{ alignItems: "center" }}>
        <div onClick={() => navigate("market.home")} style={{ cursor: "pointer" }}>
          <Logo />
        </div>
        <span className="tag" style={{ fontSize: 10.5 }}>
          by <a href="https://fmatique.com" target="_blank" rel="noopener noreferrer" style={{ color: "var(--fg-muted)", fontWeight: 600, marginLeft: 3 }}>FMAtique</a>
        </span>
      </div>
      <div className="row gap-5" style={{ fontSize: 13, color: "var(--fg-muted)" }}>
        <a style={{ cursor: "pointer" }} onClick={() => navigate("market.home")}>Produit</a>
        <a style={{ cursor: "pointer" }}>Tarifs</a>
        <a style={{ cursor: "pointer" }}>Docs</a>
        <a href="https://fmblueprint.app" target="_blank" rel="noopener noreferrer" className="row gap-1" style={{ textDecoration: "none" }}>
          FMBluePrint
          <Icon name="externalLink" size={10} style={{ color: "var(--fg-faint)" }} />
        </a>
      </div>
      <div className="row gap-2">
        <Button variant="ghost" size="sm" onClick={() => navigate("market.login")}>Se connecter</Button>
        <Button variant="primary" size="sm" iconRight="arrowRight" onClick={() => navigate("market.signup")}>
          Démarrer
        </Button>
      </div>
    </nav>
  );
}

function MarketFooter({ navigate }) {
  return (
    <footer style={{ borderTop: "1px solid var(--border)", padding: "48px 0 32px", marginTop: 80 }}>
      <div className="container row" style={{ alignItems: "flex-start", gap: 64 }}>
        <div className="col gap-3" style={{ maxWidth: 280 }}>
          <Logo />
          <p style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.5 }}>
            Le pont entre votre IA préférée et FileMaker Pro. Collez le script généré par ChatGPT, Claude ou Gemini — on s'occupe du tapotage.
          </p>
          <div className="row gap-2" style={{ marginTop: 8 }}>
            <span className="tag">macOS</span>
            <span className="tag">FileMaker 19+</span>
          </div>
        </div>
        <div className="grow row" style={{ gap: 48, justifyContent: "flex-end", fontSize: 13 }}>
          <div className="col gap-2">
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--fg-faint)", marginBottom: 4 }}>Produit</div>
            <a style={{ cursor: "pointer" }}>Companion</a>
            <a style={{ cursor: "pointer" }}>Extension</a>
            <a style={{ cursor: "pointer" }}>Changelog</a>
          </div>
          <div className="col gap-2">
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--fg-faint)", marginBottom: 4 }}>Suite FMAtique</div>
            <a href="https://fmblueprint.app" target="_blank" rel="noopener noreferrer" className="row gap-1" style={{ textDecoration: "none" }}>
              FMBluePrint
              <Icon name="externalLink" size={10} style={{ color: "var(--fg-faint)" }} />
            </a>
            <a href="https://fmatique.com" target="_blank" rel="noopener noreferrer" className="row gap-1" style={{ textDecoration: "none" }}>
              fmatique.com
              <Icon name="externalLink" size={10} style={{ color: "var(--fg-faint)" }} />
            </a>
          </div>
          <div className="col gap-2">
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--fg-faint)", marginBottom: 4 }}>Ressources</div>
            <a style={{ cursor: "pointer" }}>Documentation</a>
            <a style={{ cursor: "pointer" }}>Référence des steps</a>
            <a style={{ cursor: "pointer" }}>Exemples</a>
          </div>
          <div className="col gap-2">
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--fg-faint)", marginBottom: 4 }}>Compte</div>
            <a style={{ cursor: "pointer" }} onClick={() => navigate("market.login")}>Connexion</a>
            <a style={{ cursor: "pointer" }} onClick={() => navigate("market.signup")}>Inscription</a>
          </div>
        </div>
      </div>
      <div className="container row" style={{ justifyContent: "space-between", marginTop: 48, color: "var(--fg-faint)", fontSize: 12 }}>
        <div>
          © 2026 <a href="https://fmatique.com" target="_blank" rel="noopener noreferrer" style={{ color: "var(--fg-muted)", fontWeight: 500 }}>FMAtique</a> — un produit de la suite FMAtique. Non affilié à Claris.
        </div>
        <div className="row gap-4">
          <a style={{ cursor: "pointer" }}>Vie privée</a>
          <a style={{ cursor: "pointer" }}>CGU</a>
        </div>
      </div>
    </footer>
  );
}

// ─────── Homepage ───────

function HomePage({ navigate }) {
  return (
    <div className="market-shell">
      <MarketNav navigate={navigate} />
      <main className="market-content">

        {/* HERO */}
        <section style={{ padding: "80px 0 40px" }}>
          <div className="container col gap-5" style={{ alignItems: "flex-start" }}>
            <span className="eyebrow">
              <Icon name="sparkles" size={12} />
              Le pont entre l'IA et FileMaker
            </span>
            <h1 className="hero-title" style={{ maxWidth: 980 }}>
              Vos scripts FileMaker, écrits par l'IA.<br />
              <span style={{ color: "var(--fg-muted)" }}>Générés dans FileMaker en un clic.</span>
            </h1>
            <p className="hero-sub">
              ChatGPT, Claude, Gemini, Copilot — l'IA de votre choix génère le script. FMAutoScript le tape dans FileMaker Pro, étape par étape. Parce que FileMaker n'accepte pas le copier-coller dans Script Workspace.
            </p>
            <div className="row gap-3" style={{ marginTop: 8 }}>
              <Button variant="primary" size="lg" iconRight="arrowRight" onClick={() => navigate("market.signup")}>
                Essayer gratuitement
              </Button>
              <Button variant="secondary" size="lg" icon="play">
                Voir la démo (90 sec)
              </Button>
            </div>
            <div className="row gap-4" style={{ marginTop: 12, fontSize: 12.5, color: "var(--fg-faint)" }}>
              <span className="row gap-1"><Icon name="check" size={13} style={{ color: "var(--success)" }} /> Compatible toutes IA</span>
              <span className="row gap-1"><Icon name="check" size={13} style={{ color: "var(--success)" }} /> FileMaker 19, 20, 21, 22</span>
              <span className="row gap-1"><Icon name="check" size={13} style={{ color: "var(--success)" }} /> Aucune donnée envoyée</span>
            </div>

            {/* Bridge illustration: AI → FMAutoScript → FileMaker */}
            <BridgeIllustration />
          </div>
        </section>

        {/* BRING YOUR OWN AI */}
        <section style={{ padding: "56px 0", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)", background: "var(--surface)" }}>
          <div className="container col gap-5" style={{ alignItems: "center", textAlign: "center" }}>
            <span style={{ fontSize: 12, color: "var(--fg-faint)", textTransform: "uppercase", letterSpacing: "0.1em", fontWeight: 500 }}>Bring your own AI</span>
            <h2 style={{ fontSize: "clamp(22px, 2.4vw, 30px)", letterSpacing: "-0.02em", maxWidth: 720, lineHeight: 1.2 }}>
              On ne vous impose pas de modèle. Utilisez celui que vous payez déjà.
            </h2>
            <div className="row" style={{ gap: 12, flexWrap: "wrap", justifyContent: "center", marginTop: 16 }}>
              {[
                { name: "ChatGPT", glyph: "chatgpt", by: "OpenAI" },
                { name: "Claude", glyph: "claude", by: "Anthropic" },
                { name: "Gemini", glyph: "gemini", by: "Google" },
                { name: "Copilot", glyph: "copilot", by: "Microsoft" },
                { name: "Mistral", glyph: "mistral", by: "Mistral AI" },
                { name: "DeepSeek", glyph: "deepseek", by: "DeepSeek" },
              ].map((p) => (
                <div key={p.name} className="card row gap-2" style={{ padding: "10px 16px", alignItems: "center" }}>
                  <AIGlyph name={p.glyph} size={22} />
                  <div className="col" style={{ alignItems: "flex-start", lineHeight: 1.1 }}>
                    <span style={{ fontSize: 13, fontWeight: 600 }}>{p.name}</span>
                    <span style={{ fontSize: 10.5, color: "var(--fg-faint)" }}>{p.by}</span>
                  </div>
                </div>
              ))}
            </div>
            <p style={{ fontSize: 13, color: "var(--fg-muted)", maxWidth: 600, marginTop: 8 }}>
              FMAutoScript ne stocke pas votre clé API et n'appelle aucune IA. Vous discutez avec l'IA de votre côté, vous nous donnez le résultat.
            </p>
          </div>
        </section>

        {/* FEATURES */}
        <section style={{ padding: "80px 0" }}>
          <div className="container">
            <Section
              eyebrow="Ce que ça remplace"
              title="Le seul pont entre l'IA et votre base."
              sub="L'IA sait écrire des scripts FileMaker corrects depuis longtemps. Le vrai problème, c'est de les y mettre. FileMaker Script Workspace refuse le paste — il faut tout retaper à la main. FMAutoScript automatise ce tapotage."
            />

            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16, marginTop: 48 }}>
              {[
                { icon: "scripts", title: "240+ steps FileMaker", body: "De Set Field aux Perform Script On Server, en passant par tous les contrôles If/Loop. Si l'IA l'écrit, on sait le taper." },
                { icon: "alertTri", title: "Reprise sur erreur", body: "Avec notre plugin de détection d'erreurs, FileMaker s'arrête à la ligne 42 (champ inexistant, syntaxe invalide), corrigez et on reprend là où ça a planté." },
                { icon: "puzzle", title: "Extension navigateur", body: "L'extension Chrome/Firefox/Safari fait passer le script directement de votre onglet ChatGPT à FileMaker. Sans détour par notre site." },
                { icon: "cpu", title: "100 % local", body: "Le companion tourne sur votre machine. Vos scripts ne transitent jamais par nos serveurs — aucun risque de fuite IP client." },
                { icon: "globe", title: "Multi-versions FM", body: "FileMaker 19, 20, 21, Pro Advanced. On s'adapte au layout de Manage Scripts de la version installée." },
                { icon: "history", title: "Historique illimité", body: "Tous vos scripts générés sont conservés (plan Pro). Re-jouez, dupliquez, exportez en un clic." },
              ].map((f) => (
                <div key={f.title} className="feature">
                  <div className="feature-icon"><Icon name={f.icon} size={18} /></div>
                  <h3 style={{ fontSize: 16, marginBottom: 6 }}>{f.title}</h3>
                  <p style={{ fontSize: 13.5, color: "var(--fg-muted)", lineHeight: 1.55 }}>{f.body}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* HOW IT WORKS */}
        <section style={{ padding: "40px 0 80px", background: "var(--surface)", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)" }}>
          <div className="container">
            <Section
              eyebrow="Comment ça marche"
              title="4 étapes. 2 minutes."
              sub="Le scénario que tout dev FileMaker connaît : l'IA écrit un script, mais FileMaker refuse le copier-coller. Voilà comment on règle ça."
            />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 16, marginTop: 48 }}>
              {[
                { n: "01", icon: "sparkles", title: "Demandez à votre IA", body: "\"Donne-moi un script FileMaker qui crée un patient et envoie un mail.\" — ChatGPT, Claude, Gemini, peu importe." },
                { n: "02", icon: "copy", title: "Copiez le résultat", body: "Copie standard de la réponse de l'IA. Plain text, format FileMaker classique (Set Field, If, Loop, etc.)." },
                { n: "03", icon: "code", title: "Collez dans FMAutoScript", body: "Cmd+V dans l'éditeur. Coloration syntaxique automatique. Vérifiez, ajustez si besoin." },
                { n: "04", icon: "zap", title: "On tape dans FileMaker", body: "Un clic. Le companion ouvre Manage Scripts et tape chaque step à votre place. Vous regardez (ou pas)." },
              ].map((s) => (
                <div key={s.n} className="card" style={{ padding: 20 }}>
                  <div className="row gap-2" style={{ marginBottom: 10 }}>
                    <div className="step-num">{s.n}</div>
                    <Icon name={s.icon} size={14} style={{ color: "var(--fg-faint)", marginLeft: "auto" }} />
                  </div>
                  <h3 style={{ fontSize: 15, marginBottom: 6 }}>{s.title}</h3>
                  <p style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.5 }}>{s.body}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* EXTENSION CALL-OUT */}
        <section style={{ padding: "80px 0" }}>
          <div className="container">
            <div className="banner-ext">
              <div className="col gap-2" style={{ maxWidth: 540 }}>
                <span className="eyebrow"><Icon name="puzzle" size={12} />Extension navigateur</span>
                <h3 style={{ fontSize: 24, letterSpacing: "-0.02em" }}>Générez des scripts en un clic.</h3>
                <p style={{ fontSize: 14, color: "var(--fg-muted)", lineHeight: 1.55 }}>
                  Pas besoin de notre site. L'extension Chrome / Firefox / Safari fait tourner FMAutoScript dans votre navigateur.
                </p>
              </div>
              <div className="col gap-2" style={{ alignItems: "flex-end" }}>
                <Button variant="primary" iconRight="externalLink">
                  Télécharger l'extension
                </Button>
                <span style={{ fontSize: 11, color: "var(--fg-faint)", fontFamily: "var(--font-mono)" }}>
                  Chrome 100+ · Firefox 102+ · Safari 16+
                </span>
              </div>
            </div>
          </div>
        </section>

        {/* SUITE FMATIQUE — sister product */}
        <section style={{ padding: "60px 0", borderTop: "1px solid var(--border)" }}>
          <div className="container">
            <div className="card" style={{ padding: 32, display: "grid", gridTemplateColumns: "1fr 1.1fr", gap: 32, alignItems: "center" }}>
              <div className="col gap-3">
                <span className="eyebrow" style={{ background: "var(--surface)", color: "var(--fg-muted)" }}>
                  <Icon name="sparkles" size={11} />
                  Suite FMAtique
                </span>
                <h2 style={{ fontSize: "clamp(24px, 2.6vw, 32px)", letterSpacing: "-0.025em", lineHeight: 1.15 }}>
                  Vous documentez aussi vos bases&nbsp;?<br />
                  <span style={{ color: "var(--fg-muted)" }}>Découvrez FMBluePrint.</span>
                </h2>
                <p style={{ fontSize: 14, color: "var(--fg-muted)", lineHeight: 1.55, maxWidth: 420 }}>
                  L'autre outil de FMAtique : générez la documentation complète d'une base FileMaker — tables, relations, scripts, calculs — en quelques secondes. Compatible avec FMAutoScript.
                </p>
                <div className="row gap-3" style={{ marginTop: 6 }}>
                  <a href="https://fmblueprint.app" target="_blank" rel="noopener noreferrer" className="btn btn-secondary" style={{ textDecoration: "none" }}>
                    <Icon name="externalLink" size={13} />
                    Visiter FMBluePrint
                  </a>
                  <a href="https://fmatique.com" target="_blank" rel="noopener noreferrer" style={{ fontSize: 13, color: "var(--fg-muted)", textDecoration: "none", alignSelf: "center" }} className="row gap-1">
                    Tous les outils FMAtique <Icon name="arrowRight" size={12} />
                  </a>
                </div>
              </div>

              {/* Mini blueprint preview */}
              <BlueprintPreview />
            </div>
          </div>
        </section>

        {/* CTA */}
        <section style={{ padding: "40px 0 80px" }}>
          <div className="container-narrow col gap-4" style={{ alignItems: "center", textAlign: "center" }}>
            <h2 style={{ fontSize: "clamp(32px, 4vw, 48px)", letterSpacing: "-0.025em", lineHeight: 1.1 }}>
              Votre IA a déjà écrit le script.<br />
              <span style={{ color: "var(--fg-muted)" }}>Arrêtez de le retaper.</span>
            </h2>
            <p style={{ color: "var(--fg-muted)", fontSize: 16, maxWidth: 520 }}>
              Premier script collé et créé en moins de 2 minutes. Aucune carte bancaire. Compte gratuit limité à 30 scripts/mois.
            </p>
            <div className="row gap-3" style={{ marginTop: 8 }}>
              <Button variant="primary" size="lg" iconRight="arrowRight" onClick={() => navigate("market.signup")}>
                Créer un compte
              </Button>
              <Button variant="ghost" size="lg" onClick={() => navigate("market.login")}>
                J'ai déjà un compte
              </Button>
            </div>
          </div>
        </section>

      </main>
      <MarketFooter navigate={navigate} />
    </div>
  );
}

// Code viewer for marketing screenshots
function CodeViewer({ code, small = false }) {
  return (
    <div style={{
      background: "var(--code-bg)", color: "var(--code-fg)",
      borderRadius: "var(--radius-sm)",
      padding: "14px 16px",
      fontFamily: "var(--font-mono)",
      fontSize: small ? 12 : 13,
      lineHeight: 1.65,
      overflow: "auto",
      maxHeight: 360,
      border: "1px solid oklch(0.25 0.01 270)"
    }}>
      <pre style={{ margin: 0, whiteSpace: "pre-wrap" }} dangerouslySetInnerHTML={{ __html: window.highlightFm(code) }} />
    </div>
  );
}

// Rendered FM Script Workspace mock
function FmScriptPreview() {
  const steps = [
    { idx: 1, t: "step", n: "Set Error Capture", args: "[ On ]" },
    { idx: 2, t: "step", n: "New Record/Request" },
    { idx: 3, t: "step", n: "Set Field", args: "[ Patients::Nom; \"Dupont\" ]" },
    { idx: 4, t: "step", n: "Set Field", args: "[ Patients::Prenom; \"Marie\" ]" },
    { idx: 5, t: "step", n: "Set Field", args: "[ Patients::DateNaissance; Get(CurrentDate) ]" },
    { idx: 6, t: "step", n: "Commit Records/Requests" },
    { idx: 7, t: "ctrl", n: "If", args: "[ Get(LastError) = 0 ]" },
    { idx: 8, t: "step", n: "  Show Custom Dialog", args: "[ \"Patient créé.\" ]" },
    { idx: 9, t: "ctrl", n: "End If" },
  ];

  return (
    <div style={{
      background: "var(--bg-elevated)",
      borderRadius: "var(--radius-sm)",
      border: "1px solid var(--border)",
      overflow: "hidden",
      fontFamily: "var(--font-sans)",
      fontSize: 12.5
    }}>
      {steps.map((s, i) => (
        <div key={i} className="row gap-3" style={{
          padding: "6px 14px",
          borderBottom: i < steps.length - 1 ? "1px solid var(--border)" : "none",
          background: i % 2 === 0 ? "transparent" : "color-mix(in oklch, var(--surface) 50%, transparent)"
        }}>
          <span style={{ width: 18, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-faint)", textAlign: "right" }}>{s.idx}</span>
          <span style={{ color: s.t === "ctrl" ? "var(--accent)" : "var(--fg)", fontWeight: 500 }}>{s.n}</span>
          {s.args && <span className="mono" style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>{s.args}</span>}
        </div>
      ))}
    </div>
  );
}

// ─────── Auth pages ───────

function AuthChrome({ children, navigate }) {
  return (
    <div className="auth-shell">
      <div style={{ position: "absolute", top: 24, left: 24, cursor: "pointer" }} onClick={() => navigate("market.home")}>
        <Logo />
      </div>
      {children}
    </div>
  );
}

function LoginPage({ navigate, onLogin }) {
  const [showPw, setShowPw] = React.useState(false);
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");

  const handleGoogle = async () => {
    if (!window.sb) { setError("Auth non configurée — clé Supabase manquante"); return; }
    const { error } = await window.sb.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: 'https://www.fmautoscript.app' }
    });
    if (error) setError(error.message);
  };

  const handleLogin = async () => {
    if (!window.sb) { setError("Auth non configurée — clé Supabase manquante"); return; }
    if (!email.trim()) { setError("Entrez votre email"); return; }
    if (!pw) { setError("Entrez votre mot de passe"); return; }
    setLoading(true);
    setError("");
    try {
      const { error } = await window.sb.auth.signInWithPassword({
        email: email.trim(),
        password: pw
      });
      setLoading(false);
      if (error) {
        setError(error.message === "Invalid login credentials" ? "Email ou mot de passe incorrect" : error.message);
      }
    } catch (e) {
      setLoading(false);
      setError(e.message || "Erreur de connexion au serveur");
    }
  };

  return (
    <AuthChrome navigate={navigate}>
      <div className="auth-card">
        <h1 style={{ fontSize: 24, marginBottom: 6 }}>Bon retour</h1>
        <p style={{ fontSize: 14, color: "var(--fg-muted)", marginBottom: 28 }}>
          Connectez-vous à votre compte FMAutoScript.
        </p>

        <div className="col gap-3">
          <Button variant="secondary" size="lg" icon="globe" style={{ width: "100%" }} onClick={handleGoogle}>
            Continuer avec Google
          </Button>
        </div>

        <div className="row" style={{ margin: "24px 0", alignItems: "center", gap: 12 }}>
          <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
          <span style={{ fontSize: 11, color: "var(--fg-faint)", textTransform: "uppercase", letterSpacing: "0.1em" }}>OU</span>
          <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
        </div>

        <div className="col gap-3">
          <Field label="Email" icon="mail" type="email" placeholder="vous@boite.fr" value={email} onChange={(e) => setEmail(e.target.value)} />
          <div>
            <div className="row" style={{ justifyContent: "space-between", marginBottom: 6 }}>
              <label className="label" style={{ margin: 0 }}>Mot de passe</label>
              <a style={{ fontSize: 12, color: "var(--accent)", cursor: "pointer" }} onClick={() => navigate("market.forgot")}>
                Oublié ?
              </a>
            </div>
            <div className="field">
              <Icon name="lock" size={15} style={{ color: "var(--fg-faint)", marginRight: 8 }} />
              <input type={showPw ? "text" : "password"} value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••••" />
              <button onClick={() => setShowPw(!showPw)} style={{ background: "none", border: "none", color: "var(--fg-faint)", cursor: "pointer", padding: 0 }}>
                <Icon name={showPw ? "eyeOff" : "eye"} size={15} />
              </button>
            </div>
          </div>

          {error && (
            <div style={{ fontSize: 12, color: "var(--danger)", padding: "8px 12px", background: "color-mix(in oklch, var(--danger) 10%, var(--bg-elevated))", borderRadius: "var(--radius-sm)" }}>
              {error}
            </div>
          )}

          <Button variant="primary" size="lg" onClick={handleLogin} iconRight="arrowRight" disabled={loading}>
            {loading ? "Connexion…" : "Se connecter"}
          </Button>
        </div>

        <p style={{ fontSize: 13, color: "var(--fg-muted)", textAlign: "center", marginTop: 24 }}>
          Pas encore de compte ?{" "}
          <a style={{ color: "var(--accent)", cursor: "pointer", fontWeight: 500 }} onClick={() => navigate("market.signup")}>
            Créer un compte
          </a>
        </p>
      </div>
    </AuthChrome>
  );
}

function SignupPage({ navigate, onLogin }) {
  const [showPw, setShowPw] = React.useState(false);
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");
  const [confirmSent, setConfirmSent] = React.useState(false);

  const handleGoogle = async () => {
    if (!window.sb) { setError("Auth non configurée — clé Supabase manquante"); return; }
    const { error } = await window.sb.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: 'https://www.fmautoscript.app' }
    });
    if (error) setError(error.message);
  };

  const pwStrength = pw.length === 0 ? 0 : pw.length < 6 ? 1 : pw.length < 10 ? 2 : pw.length < 14 ? 3 : 4;
  const pwLabels = ["", "Faible", "Moyen", "Bon", "Fort"];

  const handleSignup = async () => {
    if (!window.sb) { setError("Auth non configurée — clé Supabase manquante"); return; }
    if (!email.trim()) { setError("Entrez votre email"); return; }
    if (pw.length < 6) { setError("Le mot de passe doit contenir au moins 6 caractères"); return; }
    setLoading(true);
    setError("");
    try {
      const { data, error } = await window.sb.auth.signUp({
        email: email.trim(),
        password: pw
      });
      setLoading(false);
      if (error) {
        setError(error.message);
      } else if (data.session) {
        // Auto-logged in — onAuthStateChange in app.jsx will redirect
      } else {
        setConfirmSent(true);
      }
    } catch (e) {
      setLoading(false);
      setError(e.message || "Erreur de connexion au serveur");
    }
  };

  return (
    <AuthChrome navigate={navigate}>
      <div className="auth-card">
        {confirmSent ? (
          <div className="col gap-4" style={{ alignItems: "flex-start" }}>
            <div style={{ width: 44, height: 44, borderRadius: 999, background: "var(--accent-soft)", display: "grid", placeItems: "center", color: "var(--accent-soft-fg)" }}>
              <Icon name="mail" size={20} />
            </div>
            <h1 style={{ fontSize: 22 }}>Vérifiez votre boîte mail</h1>
            <p style={{ fontSize: 14, color: "var(--fg-muted)", lineHeight: 1.55 }}>
              Un email de confirmation a été envoyé à <strong>{email}</strong>. Cliquez sur le lien pour activer votre compte.
            </p>
            <Button variant="secondary" onClick={() => navigate("market.login")}>
              Aller à la connexion
            </Button>
          </div>
        ) : (
        <>
        <h1 style={{ fontSize: 24, marginBottom: 6 }}>Créer un compte</h1>
        <p style={{ fontSize: 14, color: "var(--fg-muted)", marginBottom: 28 }}>
          30 scripts gratuits par mois. Aucune carte bancaire.
        </p>

        <div className="row gap-2" style={{ marginBottom: 20 }}>
          <Button variant="secondary" icon="globe" style={{ flex: 1 }} onClick={handleGoogle}>Google</Button>
        </div>

        <div className="row" style={{ margin: "0 0 20px", alignItems: "center", gap: 12 }}>
          <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
          <span style={{ fontSize: 11, color: "var(--fg-faint)", textTransform: "uppercase", letterSpacing: "0.1em" }}>OU PAR EMAIL</span>
          <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
        </div>

        <div className="col gap-3">
          <Field label="Email" icon="mail" type="email" placeholder="vous@boite.fr" value={email} onChange={(e) => setEmail(e.target.value)} />
          <div>
            <label className="label">Mot de passe</label>
            <div className="field">
              <Icon name="lock" size={15} style={{ color: "var(--fg-faint)", marginRight: 8 }} />
              <input type={showPw ? "text" : "password"} value={pw} onChange={(e) => setPw(e.target.value)} placeholder="Min. 6 caractères" />
              <button onClick={() => setShowPw(!showPw)} style={{ background: "none", border: "none", color: "var(--fg-faint)", cursor: "pointer", padding: 0 }}>
                <Icon name={showPw ? "eyeOff" : "eye"} size={15} />
              </button>
            </div>
            {pw.length > 0 && (
              <>
                <div className="row gap-1" style={{ marginTop: 8 }}>
                  {[0, 1, 2, 3].map((i) => (
                    <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i < pwStrength ? "var(--accent)" : "var(--border)" }} />
                  ))}
                </div>
                <p style={{ fontSize: 11, color: "var(--fg-faint)", marginTop: 6 }}>Force : {pwLabels[pwStrength]}</p>
              </>
            )}
          </div>

          {error && (
            <div style={{ fontSize: 12, color: "var(--danger)", padding: "8px 12px", background: "color-mix(in oklch, var(--danger) 10%, var(--bg-elevated))", borderRadius: "var(--radius-sm)" }}>
              {error}
            </div>
          )}

          <label className="row gap-2" style={{ fontSize: 12.5, color: "var(--fg-muted)", cursor: "pointer", alignItems: "flex-start", marginTop: 4 }}>
            <input type="checkbox" style={{ marginTop: 2 }} />
            <span>J'accepte les <a style={{ color: "var(--accent)" }}>CGU</a> et la <a style={{ color: "var(--accent)" }}>politique de vie privée</a>.</span>
          </label>

          <Button variant="primary" size="lg" onClick={handleSignup} iconRight="arrowRight" disabled={loading}>
            {loading ? "Création…" : "Créer mon compte"}
          </Button>
        </div>

        <p style={{ fontSize: 13, color: "var(--fg-muted)", textAlign: "center", marginTop: 24 }}>
          Déjà inscrit ?{" "}
          <a style={{ color: "var(--accent)", cursor: "pointer", fontWeight: 500 }} onClick={() => navigate("market.login")}>
            Se connecter
          </a>
        </p>
        </>
        )}
      </div>
    </AuthChrome>
  );
}

function ForgotPage({ navigate }) {
  const [sent, setSent] = React.useState(false);
  const [email, setEmail] = React.useState("");
  const [loading, setLoading] = React.useState(false);

  const handleReset = async () => {
    if (!email.trim() || !window.sb) return;
    setLoading(true);
    await window.sb.auth.resetPasswordForEmail(email.trim(), {
      redirectTo: 'https://www.fmautoscript.app'
    });
    setLoading(false);
    setSent(true);
  };

  return (
    <AuthChrome navigate={navigate}>
      <div className="auth-card">
        {!sent ? (
          <>
            <h1 style={{ fontSize: 24, marginBottom: 6 }}>Mot de passe oublié ?</h1>
            <p style={{ fontSize: 14, color: "var(--fg-muted)", marginBottom: 28 }}>
              Entrez l'email de votre compte, on vous envoie un lien de réinitialisation.
            </p>
            <div className="col gap-4">
              <Field label="Email" icon="mail" type="email" placeholder="vous@boite.fr" value={email} onChange={(e) => setEmail(e.target.value)} />
              <Button variant="primary" size="lg" iconRight="arrowRight" onClick={handleReset} disabled={loading}>
                {loading ? "Envoi…" : "Envoyer le lien"}
              </Button>
            </div>
          </>
        ) : (
          <div className="col gap-4" style={{ alignItems: "flex-start" }}>
            <div style={{ width: 44, height: 44, borderRadius: 999, background: "var(--accent-soft)", display: "grid", placeItems: "center", color: "var(--accent-soft-fg)" }}>
              <Icon name="mail" size={20} />
            </div>
            <h1 style={{ fontSize: 22 }}>Vérifiez votre boîte mail</h1>
            <p style={{ fontSize: 14, color: "var(--fg-muted)", lineHeight: 1.55 }}>
              Si un compte existe pour cette adresse, vous recevrez un lien de réinitialisation dans les 2 minutes.
            </p>
            <div className="row gap-2" style={{ marginTop: 8 }}>
              <Button variant="secondary" onClick={() => setSent(false)}>Essayer un autre email</Button>
            </div>
          </div>
        )}

        <div className="row gap-2" style={{ marginTop: 24, justifyContent: "center" }}>
          <a className="row gap-1" style={{ fontSize: 13, color: "var(--fg-muted)", cursor: "pointer" }} onClick={() => navigate("market.login")}>
            <Icon name="arrowLeft" size={13} /> Retour à la connexion
          </a>
        </div>
      </div>
    </AuthChrome>
  );
}

function FourOhFour({ navigate }) {
  return (
    <div className="auth-shell" style={{ background: "var(--bg)" }}>
      <div className="col gap-5" style={{ alignItems: "center", textAlign: "center", maxWidth: 480 }}>
        <span className="tag mono">ERROR_CODE: 404</span>
        <div className="fourofour-num">404</div>
        <h1 style={{ fontSize: 28 }}>Cette page n'existe pas.</h1>
        <p style={{ color: "var(--fg-muted)", fontSize: 15 }}>
          Comme un <span className="mono" style={{ background: "var(--surface)", padding: "1px 6px", borderRadius: 4 }}>Go to Layout</span> vers un layout supprimé. Vérifiez l'URL ou revenez à l'accueil.
        </p>
        <div className="row gap-2" style={{ marginTop: 8 }}>
          <Button variant="primary" icon="arrowLeft" onClick={() => navigate("market.home")}>
            Retour à l'accueil
          </Button>
          <Button variant="secondary" icon="bookOpen">Consulter la doc</Button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HomePage, LoginPage, SignupPage, ForgotPage, FourOhFour });

// ─────── AI glyph (abstract, brand-evoking but not brand-copying) ───────
function AIGlyph({ name, size = 24 }) {
  const s = size, c = s / 2;
  const wrap = { width: s, height: s, borderRadius: s * 0.28, display: "grid", placeItems: "center", flexShrink: 0 };
  if (name === "chatgpt") return <div style={{ ...wrap, background: "oklch(0.55 0.13 165)", color: "white" }}><svg width={s * 0.6} height={s * 0.6} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2 4 7v10l8 5 8-5V7l-8-5z" /><path d="m4 7 8 5 8-5M12 12v10" /></svg></div>;
  if (name === "claude") return <div style={{ ...wrap, background: "oklch(0.62 0.16 40)", color: "white", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: s * 0.5, letterSpacing: "-0.05em" }}>A*</div>;
  if (name === "gemini") return <div style={{ ...wrap, background: "oklch(0.55 0.18 260)", color: "white" }}><svg width={s * 0.65} height={s * 0.65} viewBox="0 0 24 24" fill="currentColor"><path d="M12 2c.5 4 2 6 6 6-4 0-5.5 2-6 6-.5-4-2-6-6-6 4 0 5.5-2 6-6z" /></svg></div>;
  if (name === "copilot") return <div style={{ ...wrap, background: "oklch(0.55 0.14 220)", color: "white", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: s * 0.46 }}>{"//"}</div>;
  if (name === "mistral") return <div style={{ ...wrap, background: "oklch(0.68 0.16 60)", color: "white" }}><svg width={s * 0.7} height={s * 0.7} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M4 4v16M9 4v16M14 4v16M19 4v16" /></svg></div>;
  if (name === "deepseek") return <div style={{ ...wrap, background: "oklch(0.50 0.14 250)", color: "white", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: s * 0.5 }}>DS</div>;
  return <div style={wrap} />;
}

// ─────── Bridge illustration: AI → FMAutoScript → FileMaker ───────
function BridgeIllustration() {
  return (
    <div className="window-mock" style={{ width: "100%", maxWidth: 1180, marginTop: 48, padding: 0 }}>
      <div className="window-mock-bar">
        <span className="dot" /><span className="dot" /><span className="dot" />
        <span style={{ flex: 1 }} />
        <span className="mono" style={{ fontSize: 11, color: "var(--fg-faint)" }}>le pont</span>
        <span style={{ flex: 1 }} />
      </div>
      <div style={{
        display: "grid",
        gridTemplateColumns: "1fr 32px 1fr 32px 1fr",
        gap: 0,
        padding: 28,
        background: "var(--surface)",
        alignItems: "stretch"
      }}>
        {/* Pane 1 — AI chat */}
        <BridgePane label="ChatGPT · chat.openai.com" tag="L'IA ÉCRIT" glyph={<AIGlyph name="chatgpt" size={18} />}>
          <div className="col gap-2" style={{ fontSize: 12, lineHeight: 1.55 }}>
            <div className="row gap-2" style={{ alignItems: "flex-start" }}>
              <div style={{ width: 18, height: 18, borderRadius: 999, background: "var(--surface)", flexShrink: 0 }} />
              <div style={{ color: "var(--fg-muted)" }}>Donne-moi un script FileMaker qui crée un patient avec validation.</div>
            </div>
            <div className="row gap-2" style={{ alignItems: "flex-start" }}>
              <AIGlyph name="chatgpt" size={18} />
              <div className="mono" style={{ fontSize: 11, color: "var(--fg)", background: "var(--bg-elevated)", border: "1px solid var(--border)", borderRadius: 6, padding: "8px 10px", lineHeight: 1.6 }}>
                <span className="tok-step">Set Error Capture</span> <span className="tok-bracket">[</span> <span style={{ color: "var(--code-fg)" }}>On</span> <span className="tok-bracket">]</span><br />
                <span className="tok-step">New Record/Request</span><br />
                <span className="tok-step">Set Field</span> <span className="tok-bracket">[</span><span className="tok-field">Patients::Nom</span><span className="tok-bracket">]</span><br />
                <span className="tok-keyword">If</span> <span className="tok-bracket">[</span> <span className="tok-step">Get</span>(LastError)=<span className="tok-number">0</span> <span className="tok-bracket">]</span><br />
                <span style={{ color: "var(--fg-faint)" }}>  …</span><br />
                <span className="tok-keyword">End If</span>
              </div>
            </div>
            <button className="btn btn-secondary btn-sm" style={{ alignSelf: "flex-end", marginTop: 4 }}>
              <Icon name="copy" size={11} /> Copier
            </button>
          </div>
        </BridgePane>

        <BridgeArrow />

        {/* Pane 2 — FMAutoScript editor */}
        <BridgePane label="FMAutoScript · l'éditeur" tag="VOUS COLLEZ" glyph={<Logo size={16} withText={false} />}>
          <div style={{ fontSize: 11, color: "var(--fg-faint)", marginBottom: 6, fontFamily: "var(--font-mono)" }}>Cmd+V</div>
          <CodeViewer code={`Set Error Capture [ On ]
New Record/Request
Set Field [ Patients::Nom ; "Dupont" ]
Set Field [ Patients::Prenom ; "Marie" ]
Commit Records/Requests
If [ Get(LastError) = 0 ]
  Show Custom Dialog [ "OK." ]
End If`} small />
          <button className="btn btn-primary btn-sm" style={{ alignSelf: "flex-end", marginTop: 8 }}>
            <Icon name="zap" size={11} /> Créer
          </button>
        </BridgePane>

        <BridgeArrow />

        {/* Pane 3 — FileMaker */}
        <BridgePane label="FileMaker Pro · Manage Scripts" tag="ON CRÉE" glyph={
          <div style={{ width: 18, height: 18, background: "oklch(0.55 0.18 140)", borderRadius: 4, display: "grid", placeItems: "center", color: "white", fontFamily: "var(--font-mono)", fontSize: 9, fontWeight: 700 }}>FM</div>
        }>
          <FmScriptPreview />
        </BridgePane>
      </div>
    </div>
  );
}

function BridgePane({ label, tag, glyph, children }) {
  return (
    <div className="col" style={{ background: "var(--bg-elevated)", border: "1px solid var(--border)", borderRadius: "var(--radius)", overflow: "hidden", minWidth: 0 }}>
      <div className="row gap-2" style={{ padding: "8px 10px", borderBottom: "1px solid var(--border)", background: "var(--surface)" }}>
        {glyph}
        <span style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--fg-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{label}</span>
        <span style={{ flex: 1 }} />
        <span style={{ fontSize: 9.5, fontWeight: 600, color: "var(--accent)", letterSpacing: "0.08em" }}>{tag}</span>
      </div>
      <div className="col grow" style={{ padding: 12 }}>
        {children}
      </div>
    </div>
  );
}

function BridgeArrow() {
  return (
    <div className="center" style={{ color: "var(--fg-faint)", height: "100%" }}>
      <Icon name="arrowRight" size={20} />
    </div>
  );
}

Object.assign(window, { AIGlyph, BridgeIllustration });

// ─────── Blueprint preview (sister product) ───────
function BlueprintPreview() {
  return (
    <div className="window-mock" style={{ background: "var(--surface)" }}>
      <div className="window-mock-bar">
        <span className="dot" /><span className="dot" /><span className="dot" />
        <span style={{ flex: 1 }} />
        <span className="mono" style={{ fontSize: 11, color: "var(--fg-faint)" }}>fmblueprint — schéma</span>
        <span style={{ flex: 1 }} />
      </div>
      <div style={{ position: "relative", height: 280, padding: 20 }}>
        <svg viewBox="0 0 400 240" preserveAspectRatio="none" width="100%" height="100%" style={{ position: "absolute", inset: 20 }}>
          <line x1="105" y1="60" x2="195" y2="60" stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="3 3" opacity="0.6" />
          <line x1="105" y1="180" x2="195" y2="120" stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="3 3" opacity="0.6" />
          <line x1="295" y1="60" x2="385" y2="60" stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="3 3" opacity="0.6" />
          <line x1="295" y1="120" x2="385" y2="180" stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="3 3" opacity="0.6" />
        </svg>
        {[
          [{ name: "Patients", x: 8, y: 20, fields: ["pk_Id", "Nom", "Prénom"] },
           { name: "Adresses", x: 8, y: 150, fields: ["pk_Id", "Rue", "Ville"] }],
          [{ name: "Consultations", x: 145, y: 30, fields: ["pk_Id", "fk_Patient", "Date"] }],
          [{ name: "Factures", x: 282, y: 20, fields: ["pk_Id", "Montant", "Date"] },
           { name: "Paiements", x: 282, y: 150, fields: ["pk_Id", "Montant", "Mode"] }],
        ].flat().map((t) => (
          <div key={t.name} style={{
            position: "absolute",
            left: t.x, top: t.y,
            width: 110,
            background: "var(--bg-elevated)",
            border: "1px solid var(--border-strong)",
            borderRadius: "var(--radius-sm)",
            fontSize: 10,
            overflow: "hidden",
            zIndex: 2
          }}>
            <div style={{ padding: "5px 9px", background: "var(--accent-soft)", color: "var(--accent-soft-fg)", fontWeight: 600, borderBottom: "1px solid var(--border)" }}>{t.name}</div>
            {t.fields.map((f) => (
              <div key={f} className="mono" style={{ padding: "3px 9px", borderTop: "1px solid var(--border)", color: "var(--fg-muted)", fontSize: 10 }}>{f}</div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { BlueprintPreview });
