// Réglages — sections partagées web + mobile : Sécurité (2FA, mot de passe,
// appareils), Équipe (membres + invitation validée), Abonnement (démo — la
// tarification n'est PAS définie : garde-fou readme, aucun prix inventé),
// Support. Contenus sans conteneur. window.OryzeShared.{SecuritySection,
// TeamSection, SubscriptionSection, SupportSection}
(function () {
  const { Button, Input, Select, Toggle, Tag, Avatar, StatusBadge } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;

  const kick = { fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" };
  const err = { fontSize: 12.5, color: "var(--fin-negative)", fontWeight: 600, marginTop: 6 };
  const help = { fontSize: 12, color: "var(--text-subtle)", lineHeight: 1.5 };
  const cardBox = { border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-lg)", overflow: "hidden", background: "var(--surface-card)" };

  function RowShell({ children, last }) {
    return <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", borderBottom: last ? "none" : "1px solid var(--line-divider)" }}>{children}</div>;
  }
  function IconTile({ children }) {
    return <span style={{ width: 32, height: 32, borderRadius: 8, background: "var(--surface-sunken)", border: "var(--border-hair) solid var(--line-divider)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none", color: "var(--text-body)" }}>{children}</span>;
  }
  function TwoLines({ title, sub }) {
    return (
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600 }}>{title}</div>
        {sub && <div style={{ fontSize: 11.5, color: "var(--text-subtle)", marginTop: 1 }}>{sub}</div>}
      </div>
    );
  }

  /* ---------------- Sécurité ---------------- */

  function SecuritySection({ compact = false }) {
    const [twofa, setTwofa] = React.useState(true);
    const [pwdOpen, setPwdOpen] = React.useState(false);
    const [cur, setCur] = React.useState("");
    const [n1, setN1] = React.useState("");
    const [n2, setN2] = React.useState("");
    const [pwdErr, setPwdErr] = React.useState(null);
    const [pwdDone, setPwdDone] = React.useState(false);
    const [phoneOut, setPhoneOut] = React.useState(false);

    function savePwd() {
      setPwdErr(null);
      if (!cur) { setPwdErr("Saisissez votre mot de passe actuel."); return; }
      if (n1.length < 8) { setPwdErr("Le nouveau mot de passe doit faire au moins 8 caractères."); return; }
      if (n1 !== n2) { setPwdErr("Les deux saisies ne correspondent pas."); return; }
      setPwdDone(true);
      setTimeout(() => { setPwdDone(false); setPwdOpen(false); setCur(""); setN1(""); setN2(""); }, 1400);
    }

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div style={cardBox}>
          <RowShell>
            <IconTile><Ic.shield size={16} /></IconTile>
            <TwoLines title="Double authentification" sub="Code demandé à chaque connexion" />
            <Toggle checked={twofa} onChange={setTwofa} aria-label="Double authentification" />
          </RowShell>
          <RowShell>
            <IconTile><Ic.smartphone size={16} /></IconTile>
            <TwoLines title="Application d'authentification" sub="Méthode principale — codes hors ligne" />
            {twofa ? <Tag tone="paid" dot>Active</Tag> : <Tag>Désactivée</Tag>}
          </RowShell>
          <RowShell last>
            <IconTile><Ic.lock size={16} /></IconTile>
            <TwoLines title="Mot de passe" sub="Modifié il y a 3 mois" />
            <Button size="sm" variant="ghost" onClick={() => setPwdOpen((o) => !o)}>{pwdOpen ? "Fermer" : "Modifier"}</Button>
          </RowShell>
        </div>

        {pwdOpen && (
          <div style={{ display: "flex", flexDirection: "column", gap: 10, padding: "14px", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-lg)", background: "var(--surface-sunken)" }}>
            {pwdDone ? (
              <div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--oryze-mint-ink)", fontWeight: 600, fontSize: 13.5 }}>
                <Ic.check size={17} /> Mot de passe modifié — vos autres sessions sont déconnectées.
              </div>
            ) : (
              <React.Fragment>
                <Input label="Mot de passe actuel" type="password" value={cur} onChange={(e) => setCur(e.target.value)} />
                <div style={{ display: "grid", gridTemplateColumns: compact ? "minmax(0,1fr)" : "minmax(0,1fr) minmax(0,1fr)", gap: 10 }}>
                  <Input label="Nouveau" type="password" value={n1} onChange={(e) => setN1(e.target.value)} placeholder="8 caractères min." />
                  <Input label="Confirmer" type="password" value={n2} onChange={(e) => setN2(e.target.value)} />
                </div>
                {pwdErr && <div style={err}>{pwdErr}</div>}
                <Button size="sm" onClick={savePwd} style={{ alignSelf: "flex-end" }}>Enregistrer</Button>
              </React.Fragment>
            )}
          </div>
        )}

        <div>
          <div style={{ ...kick, marginBottom: 8 }}>Appareils connectés</div>
          <div style={cardBox}>
            <RowShell>
              <IconTile><Ic.laptop size={16} /></IconTile>
              <TwoLines title="MacBook — Lyon" sub="Actif maintenant · Safari" />
              <Tag tone="mint" dot>Cet appareil</Tag>
            </RowShell>
            <RowShell last>
              <IconTile><Ic.smartphone size={16} /></IconTile>
              <TwoLines title="iPhone — Lyon" sub={phoneOut ? "Session déconnectée" : "Il y a 2 h · app Oryze"} />
              {phoneOut
                ? <Tag>Déconnecté</Tag>
                : <Button size="sm" variant="ghost" iconLeft={<Ic.logout size={14} />} onClick={() => setPhoneOut(true)}>Déconnecter</Button>}
            </RowShell>
          </div>
        </div>
      </div>
    );
  }

  /* ---------------- Équipe ---------------- */

  const ROLES = [
    { value: "admin", label: "Admin" },
    { value: "comptable", label: "Comptable" },
    { value: "lecture", label: "Lecture seule" },
  ];

  function TeamSection({ compact = false }) {
    const [members, setMembers] = React.useState([
      { id: "m1", name: "Marie Lefèvre", email: "marie.lefevre@atelier.fr", role: "Titulaire", init: "ML", tone: "lilac", you: true },
      { id: "m2", name: "Paul Verdier", email: "paul@cabinet-verdier.fr", role: "Comptable", init: "PV", tone: "mint" },
    ]);
    const [inviteOpen, setInviteOpen] = React.useState(false);
    const [email, setEmail] = React.useState("");
    const [role, setRole] = React.useState("comptable");
    const [invErr, setInvErr] = React.useState(null);

    function invite() {
      setInvErr(null);
      const v = email.trim();
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) { setInvErr("Adresse électronique invalide."); return; }
      if (members.some((m) => m.email === v)) { setInvErr("Cette adresse fait déjà partie de l'équipe."); return; }
      const roleLabel = (ROLES.find((r) => r.value === role) || {}).label;
      setMembers((ms) => [...ms, { id: "m" + (ms.length + 1), name: v, email: v, role: roleLabel, init: v.slice(0, 2).toUpperCase(), tone: "butter", pending: true }]);
      setEmail(""); setInviteOpen(false);
    }

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
          <div style={{ fontSize: 13, color: "var(--text-muted)" }}>{members.length} membres — les rôles bornent ce que chacun peut voir et émettre.</div>
          <Button size="sm" iconLeft={<Ic.plus size={15} />} onClick={() => setInviteOpen((o) => !o)} style={{ flex: "none" }}>Inviter</Button>
        </div>

        {inviteOpen && (
          <div style={{ display: "flex", flexDirection: "column", gap: 10, padding: "14px", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-lg)", background: "var(--surface-sunken)" }}>
            <div style={{ display: "grid", gridTemplateColumns: compact ? "minmax(0,1fr)" : "minmax(0,1fr) 150px", gap: 10 }}>
              <Input label="Adresse électronique" value={email} onChange={(e) => setEmail(e.target.value)} mono placeholder="prenom@cabinet.fr" iconLeft={<Ic.mail size={16} />} />
              <Select label="Rôle" value={role} onChange={(e) => setRole(e.target.value)} options={ROLES} />
            </div>
            {invErr && <div style={err}>{invErr}</div>}
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
              <Button size="sm" variant="ghost" onClick={() => setInviteOpen(false)}>Annuler</Button>
              <Button size="sm" iconLeft={<Ic.send size={14} />} onClick={invite}>Envoyer l'invitation</Button>
            </div>
          </div>
        )}

        <div style={cardBox}>
          {members.map((m, i) => (
            <RowShell key={m.id} last={i === members.length - 1}>
              <Avatar initials={m.init} tone={m.tone} size={34} />
              <TwoLines title={m.name + (m.you ? " (vous)" : "")} sub={m.email} />
              {m.pending ? <Tag tone="butter" dot>Invitation envoyée</Tag> : <Tag mono>{m.role}</Tag>}
            </RowShell>
          ))}
        </div>
        <div style={help}>L'invité reçoit un courriel et choisit son mot de passe — ses accès s'appliquent dès l'acceptation.</div>
      </div>
    );
  }

  /* ---------------- Abonnement ---------------- */

  function SubscriptionSection() {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ padding: "16px", border: "var(--border-key) solid var(--line-keyline)", borderRadius: "var(--radius-lg)", background: "var(--oryze-lilac)", boxShadow: "var(--shadow-sm)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
            <span style={{ fontWeight: 700, fontSize: 16, color: "var(--oryze-lilac-ink)" }}>Oryze Pro</span>
            <Tag mono>DÉMO</Tag>
          </div>
          <div style={{ fontSize: 12.5, color: "var(--oryze-lilac-ink)", marginTop: 6, lineHeight: 1.5 }}>
            Compte pro, facturation conforme 2026, intelligence financière — périmètre complet en démo.
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 12px", background: "var(--oryze-butter)", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-md)" }}>
          <Ic.alert size={15} style={{ color: "var(--oryze-butter-ink)", flex: "none" }} />
          <span style={{ fontSize: 12.5, color: "var(--oryze-butter-ink)", fontWeight: 600 }}>Tarification non définie — aucun prix n'est affiché en démo.</span>
        </div>
        <div style={cardBox}>
          <RowShell>
            <IconTile><Ic.card size={16} /></IconTile>
            <TwoLines title="Moyen de paiement" sub="Carte •••• 4827 — prélèvement à l'activation" />
            <Tag tone="mint" dot>Prête</Tag>
          </RowShell>
          <RowShell last>
            <IconTile><Ic.file size={16} /></IconTile>
            <TwoLines title="Reçus d'abonnement" sub="La facturation s'activera au lancement" />
            <Tag>Aucun</Tag>
          </RowShell>
        </div>
      </div>
    );
  }

  /* ---------------- Support ---------------- */

  function SupportSection() {
    const [msg, setMsg] = React.useState("");
    const [sent, setSent] = React.useState(false);
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={cardBox}>
          <RowShell>
            <IconTile><Ic.mail size={16} /></IconTile>
            <TwoLines title="Écrire au support" sub={<span style={{ fontFamily: "var(--font-mono)" }}>support@oryze.fr — réponse sous 1 j ouvré</span>} />
          </RowShell>
          <RowShell last>
            <IconTile><Ic.folder size={16} /></IconTile>
            <TwoLines title="Guides & documentation" sub="Facturation 2026, TVA, prise en main" />
            <Ic.chevronRight size={16} style={{ color: "var(--text-subtle)" }} />
          </RowShell>
        </div>
        <div>
          <div style={{ ...kick, marginBottom: 8 }}>Signaler un problème</div>
          {sent ? (
            <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 14px", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-lg)", background: "var(--oryze-mint)", color: "var(--oryze-mint-ink)", fontWeight: 600, fontSize: 13.5 }}>
              <Ic.check size={17} /> Signalement envoyé — réf. SUP-2026-118. On revient vers vous par courriel.
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <textarea value={msg} onChange={(e) => setMsg(e.target.value)} rows={4} placeholder="Décrivez ce qui ne fonctionne pas — écran concerné, action tentée…"
                style={{ resize: "vertical", padding: "10px 12px", fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-strong)", background: "var(--surface-card)", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-md)", outline: "none" }} />
              <Button size="sm" iconLeft={<Ic.send size={14} />} disabled={!msg.trim()} onClick={() => setSent(true)} style={{ alignSelf: "flex-end" }}>Envoyer</Button>
            </div>
          )}
        </div>
      </div>
    );
  }

  window.OryzeShared = window.OryzeShared || {};
  Object.assign(window.OryzeShared, { SecuritySection, TeamSection, SubscriptionSection, SupportSection });
})();
