// Oryze — Onboarding compte pro (mobile). All 7 step screens.
// Registers each on window.OryzeOnb. Reuses design-system primitives + OryzeIcons.
// Mock only — no camera/biometrics actually invoked.
(function () {
  const DS = window.OryzeDesignSystem_78c60a;
  const { Button, Card, Input, Select, Toggle, SegmentedControl, OtpInput, Tag, StatusTimeline, Avatar } = DS;
  const Ic = window.OryzeIcons;

  const lbl = { fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" };
  const H = (t) => ({ fontWeight: 700, fontSize: 24, letterSpacing: "-0.02em", lineHeight: 1.18 });
  const sub = { fontSize: 14.5, color: "var(--text-muted)", lineHeight: 1.5, marginTop: 8 };

  // ---- 1. Création de compte -------------------------------------------
  function AccountScreen({ next, onLogin }) {
    const [email, setEmail] = React.useState("marie.lefevre@atelier.fr");
    return (
      <Step>
        <div style={{ marginBottom: 22 }}>
          <DonutMark />
        </div>
        <div style={H()}>Créez votre compte pro</div>
        <div style={sub}>La gestion financière de votre activité, au même endroit. Quelques minutes suffisent.</div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 24 }}>
          <Input label="Email professionnel" value={email} onChange={(e) => setEmail(e.target.value)} iconLeft={<Ic.file size={16} />} />
          <div style={{ fontSize: 12.5, color: "var(--text-subtle)", lineHeight: 1.5 }}>On vous enverra un code à usage unique par e-mail — pas de mot de passe à retenir.</div>
        </div>

        <Button fullWidth size="lg" style={{ marginTop: 24 }} iconRight={<Ic.arrowUpRight size={16} />} onClick={next}>Continuer</Button>

        <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "20px 0" }}>
          <div style={{ flex: 1, height: 1, background: "var(--line-divider)" }} />
          <span style={{ fontSize: 12, color: "var(--text-subtle)" }}>ou</span>
          <div style={{ flex: 1, height: 1, background: "var(--line-divider)" }} />
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <Button variant="secondary" style={{ flex: 1 }} onClick={next}>Google</Button>
          <Button variant="secondary" style={{ flex: 1 }} onClick={next}>Apple</Button>
        </div>
        <div style={{ fontSize: 11.5, color: "var(--text-subtle)", marginTop: 18, lineHeight: 1.5, textAlign: "center" }}>
          En continuant, vous acceptez les conditions d'utilisation et la politique de confidentialité d'Oryze.
        </div>
        {onLogin && (
          <div style={{ fontSize: 13, color: "var(--text-muted)", marginTop: 16, textAlign: "center" }}>
            Déjà un compte ?{" "}
            <button onClick={onLogin} style={{ border: "none", background: "none", color: "var(--text-link)", fontWeight: 600, fontSize: 13, cursor: "pointer", fontFamily: "var(--font-sans)", padding: 0 }}>
              Se connecter
            </button>
          </div>
        )}
      </Step>
    );
  }

  // ---- 2. Vérification OTP ---------------------------------------------
  function OtpScreen({ next }) {
    const [code, setCode] = React.useState("");
    const [secs, setSecs] = React.useState(38);
    React.useEffect(() => {
      if (secs <= 0) return;
      const t = setTimeout(() => setSecs((s) => s - 1), 1000);
      return () => clearTimeout(t);
    }, [secs]);
    return (
      <Step>
        <IconBadge><Ic.send size={22} /></IconBadge>
        <div style={H()}>Vérifiez votre email</div>
        <div style={sub}>On a envoyé un code à 6 chiffres à <strong style={{ color: "var(--text-strong)" }}>marie.lefevre@atelier.fr</strong>.</div>

        <div style={{ margin: "28px 0 18px" }}>
          <OtpInput length={6} value={code} onChange={setCode} onComplete={() => setTimeout(next, 350)} />
        </div>

        <div style={{ textAlign: "center", fontSize: 13, color: "var(--text-muted)" }}>
          {secs > 0
            ? <>Renvoyer le code dans <span style={{ fontFamily: "var(--font-mono)", color: "var(--text-strong)" }}>0:{String(secs).padStart(2, "0")}</span></>
            : <button onClick={() => setSecs(38)} style={linkBtn()}>Renvoyer le code</button>}
        </div>

        <Button fullWidth size="lg" style={{ marginTop: 26 }} disabled={code.length < 6} onClick={next}>Vérifier</Button>
      </Step>
    );
  }

  // ---- 3. Votre activité -----------------------------------------------
  function BusinessScreen({ next }) {
    const [form, setForm] = React.useState("micro");
    const [siret, setSiret] = React.useState("814 209 557 00018");
    const [sector, setSector] = React.useState("design");
    const [tva, setTva] = React.useState("franchise");
    return (
      <Step>
        <div style={H()}>Votre activité</div>
        <div style={sub}>Ces informations adaptent Oryze à votre régime — TVA, échéances, déclarations.</div>

        <div style={{ display: "flex", flexDirection: "column", gap: 16, marginTop: 24 }}>
          <Select label="Forme juridique" value={form} onChange={(e) => setForm(e.target.value)}
            options={[{ value: "micro", label: "Auto-entrepreneur / Micro" }, { value: "ei", label: "Entreprise individuelle" }, { value: "eurl", label: "EURL" }, { value: "sasu", label: "SASU" }, { value: "sarl", label: "SARL" }]} />
          <Input label="SIRET" value={siret} onChange={(e) => setSiret(e.target.value)} mono iconLeft={<Ic.building size={16} />} />
          <Select label="Secteur d'activité" value={sector} onChange={(e) => setSector(e.target.value)}
            options={[{ value: "design", label: "Design & création" }, { value: "conseil", label: "Conseil" }, { value: "dev", label: "Développement / IT" }, { value: "artisan", label: "Artisanat" }, { value: "autre", label: "Autre" }]} />
          <div>
            <div style={{ ...lbl, marginBottom: 8 }}>Régime de TVA</div>
            <SegmentedControl value={tva} onChange={setTva} style={{ width: "100%" }}
              options={[{ value: "franchise", label: "Franchise" }, { value: "reel", label: "Réel trimestriel" }]} />
            <div style={{ fontSize: 12, color: "var(--text-subtle)", marginTop: 8 }}>Vous pourrez l'ajuster dans les réglages.</div>
          </div>
        </div>

        <Button fullWidth size="lg" style={{ marginTop: 26 }} onClick={next} iconRight={<Ic.arrowUpRight size={16} />}>Continuer</Button>
      </Step>
    );
  }

  // ---- 4. Vérification d'identité (KYC) --------------------------------
  function KycScreen({ next }) {
    const [selfie, setSelfie] = React.useState(false);
    const docs = [
      { key: "recto", label: "Pièce d'identité — recto", icon: "file", state: "added" },
      { key: "verso", label: "Pièce d'identité — verso", icon: "file", state: "added" },
      { key: "selfie", label: "Photo de vérification (selfie)", icon: "search", state: selfie ? "added" : "todo" },
    ];
    return (
      <Step>
        <IconBadge tone="var(--oryze-lilac)"><Ic.search size={22} /></IconBadge>
        <div style={H()}>Vérifions votre identité</div>
        <div style={sub}>Une étape sécurisée, réalisée par notre établissement partenaire. Munissez-vous de votre pièce d'identité.</div>

        <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 22 }}>
          {docs.map((d) => {
            const DIcon = Ic[d.icon] || Ic.file;
            const added = d.state === "added";
            return (
              <Card key={d.key} variant="flat" padding="14px" style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <div style={{ width: 40, height: 40, flex: "none", borderRadius: "var(--radius-md)", background: added ? "var(--oryze-lilac)" : "var(--surface-page)", border: "var(--border-thin) solid var(--line-keyline)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-strong)" }}>
                  <DIcon size={18} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{d.label}</div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--text-subtle)", marginTop: 2 }}>
                    {added ? "Ajouté ✓" : "Ouvrir l'appareil photo"}
                  </div>
                </div>
                {added
                  ? <span style={{ color: "var(--text-muted)" }}><Ic.check size={20} /></span>
                  : <Button size="sm" variant="secondary" iconLeft={<Ic.plus size={15} />} onClick={() => setSelfie(true)}>Photo</Button>}
              </Card>
            );
          })}
        </div>

        <div style={{ display: "flex", alignItems: "flex-start", gap: 8, marginTop: 16, fontSize: 12, color: "var(--text-subtle)", lineHeight: 1.5 }}>
          <span style={{ flex: "none", marginTop: 1 }}><Ic.alert size={14} /></span>
          Vos documents sont chiffrés et utilisés uniquement pour la vérification.
        </div>

        <Button fullWidth size="lg" style={{ marginTop: 22 }} disabled={!selfie} onClick={next}>Lancer la vérification</Button>
      </Step>
    );
  }

  // ---- 5. Sécurité — code d'accès --------------------------------------
  function SecurityScreen({ next }) {
    const [pin, setPin] = React.useState("");
    const [bio, setBio] = React.useState(true);
    const press = (d) => setPin((p) => (p.length < 4 ? p + d : p));
    const del = () => setPin((p) => p.slice(0, -1));
    return (
      <Step>
        <IconBadge><Ic.settings size={22} /></IconBadge>
        <div style={H()}>Sécurisez votre accès</div>
        <div style={sub}>Choisissez un code à 4 chiffres pour ouvrir Oryze.</div>

        <div style={{ margin: "26px 0 18px" }}>
          <OtpInput length={4} mask value={pin} onChange={() => {}} autoFocus={false} />
        </div>

        <Keypad onPress={press} onDelete={del} />

        <div style={{ marginTop: 20 }}>
          <Card variant="flat" padding="14px" style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 38, height: 38, flex: "none", borderRadius: "var(--radius-md)", background: "var(--oryze-lilac)", border: "var(--border-thin) solid var(--line-keyline)", display: "flex", alignItems: "center", justifyContent: "center" }}><Ic.search size={18} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>Déverrouillage biométrique</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>Face ID / empreinte</div>
            </div>
            <Toggle checked={bio} onChange={setBio} />
          </Card>
        </div>

        <Button fullWidth size="lg" style={{ marginTop: 22 }} disabled={pin.length < 4} onClick={next}>Valider mon code</Button>
      </Step>
    );
  }

  // ---- 6. Vérification en cours ----------------------------------------
  function ReviewScreen({ next }) {
    const [approved, setApproved] = React.useState(false);
    React.useEffect(() => {
      const t = setTimeout(() => setApproved(true), 3500);
      return () => clearTimeout(t);
    }, []);
    return (
      <Step center>
        <IconBadge tone="var(--oryze-butter)" big><Ic.clock size={28} /></IconBadge>
        <div style={{ ...H(), textAlign: "center" }}>Votre dossier est en cours de vérification</div>
        <div style={{ ...sub, textAlign: "center" }}>Notre établissement partenaire vérifie votre dossier. Cela prend généralement quelques minutes — on vous prévient dès que votre compte pro est prêt.</div>

        <Card variant="flat" padding="18px" style={{ marginTop: 26, width: "100%", boxSizing: "border-box" }}>
          <StatusTimeline steps={[
            { label: "Compte créé", date: "✓", state: "done" },
            { label: "Identité reçue", date: "✓", state: "done" },
            { label: "Code & biométrie", date: "✓", state: "done" },
            { label: "Vérification par notre partenaire", date: "···", state: "current" },
            { label: "Accès à votre espace", date: "—", state: "future" },
          ]} />
        </Card>

        {approved ? (
          <React.Fragment>
            <Card variant="flat" padding="14px" background="var(--oryze-mint)" style={{ marginTop: 18, width: "100%", boxSizing: "border-box", display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ color: "#06371f", flex: "none" }}><Ic.check size={20} /></span>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-strong)" }}>Dossier approuvé par notre établissement partenaire — votre espace est prêt.</span>
            </Card>
            <Button fullWidth size="lg" style={{ marginTop: 16 }} iconRight={<Ic.arrowUpRight size={16} />} onClick={next}>Accéder à mon espace</Button>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <Button fullWidth size="lg" style={{ marginTop: 24 }} disabled>Vérification en cours…</Button>
            <div style={{ fontSize: 12, color: "var(--text-subtle)", marginTop: 12, textAlign: "center", lineHeight: 1.5 }}>On vous notifie dès l'approbation. Vous pouvez fermer l'app, on garde votre place.</div>
          </React.Fragment>
        )}
      </Step>
    );
  }

  // ---- 7. C'est prêt ----------------------------------------------------
  function DoneScreen({ finish }) {
    return (
      <Step center>
        <div style={{ position: "relative", marginBottom: 18 }}>
          <DonutMark size={92} />
          <span style={{ position: "absolute", right: -6, bottom: -6, width: 34, height: 34, borderRadius: "50%", background: "var(--fin-positive)", border: "var(--border-key) solid var(--line-keyline)", display: "flex", alignItems: "center", justifyContent: "center", color: "#06371f" }}>
            <Ic.check size={18} />
          </span>
        </div>
        <div style={{ ...H(), textAlign: "center" }}>Bienvenue, Marie</div>
        <div style={{ ...sub, textAlign: "center" }}>Votre compte pro Oryze est actif. Votre tableau de bord vous attend.</div>

        <Card variant="flat" padding="16px" style={{ marginTop: 24, width: "100%", boxSizing: "border-box", display: "flex", alignItems: "center", gap: 12 }}>
          <Avatar initials="ML" tone="lilac" size={40} />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>Atelier Lefèvre</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>Compte pro · •••• 4827</div>
          </div>
          <Tag tone="paid" dot>Actif</Tag>
        </Card>

        <Button fullWidth size="lg" style={{ marginTop: 22 }} iconRight={<Ic.arrowUpRight size={16} />} onClick={finish}>Accéder à mon espace</Button>
      </Step>
    );
  }

  // ---- shared bits ------------------------------------------------------
  function Step({ children, center }) {
    return <div style={{ padding: "8px 20px 24px", display: "flex", flexDirection: "column", alignItems: center ? "center" : "stretch" }}>{children}</div>;
  }
  function IconBadge({ children, tone, big }) {
    const d = big ? 68 : 56;
    return (
      <div style={{ width: d, height: d, borderRadius: "var(--radius-card)", background: tone || "var(--oryze-mint)", border: "var(--border-key) solid var(--line-keyline)", boxShadow: "var(--shadow-sm)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-strong)", marginBottom: 18 }}>
        {children}
      </div>
    );
  }
  function DonutMark({ size = 64 }) {
    return (
      <svg width={size} height={size} viewBox="0 0 100 100" aria-hidden="true">
        <circle cx="50" cy="50" r="38" fill="none" stroke="#5F3EF8" strokeWidth="22" strokeDasharray="119.4 238.8" transform="rotate(-90 50 50)" />
        <circle cx="50" cy="50" r="38" fill="none" stroke="#9D8CF6" strokeWidth="22" strokeDasharray="56.3 238.8" strokeDashoffset="-122.4" transform="rotate(-90 50 50)" />
        <circle cx="50" cy="50" r="38" fill="none" stroke="#ED99E1" strokeWidth="22" strokeDasharray="56.3 238.8" strokeDashoffset="-181.7" transform="rotate(-90 50 50)" />
      </svg>
    );
  }
  function Keypad({ onPress, onDelete }) {
    const keys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "", "0", "del"];
    return (
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10 }}>
        {keys.map((k, i) => {
          if (k === "") return <div key={i} />;
          const isDel = k === "del";
          return (
            <button key={i} onClick={() => (isDel ? onDelete() : onPress(k))}
              style={{ height: 52, borderRadius: "var(--radius-md)", border: "var(--border-thin) solid var(--line-keyline)", background: "var(--surface-card)", cursor: "pointer", fontFamily: "var(--font-mono)", fontSize: 20, fontWeight: 600, color: "var(--text-strong)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              {isDel ? <Ic.chevronRight size={20} style={{ transform: "rotate(180deg)" }} /> : k}
            </button>
          );
        })}
      </div>
    );
  }
  function linkBtn() { return { border: "none", background: "none", color: "var(--text-link)", fontWeight: 600, fontSize: 13, cursor: "pointer", fontFamily: "var(--font-sans)", padding: 0 }; }

  window.OryzeOnb = { AccountScreen, OtpScreen, BusinessScreen, KycScreen, SecurityScreen, ReviewScreen, DoneScreen };
})();
