// MostlyPrivacy — Documents hub (library) + generator wizard (screen D).
(function () {
const F = window.ForgeDesignSystem_e40d74;
const { Button, Badge, Switch, Field, Input, Select, Card, CardBody } = F;
const { Icon, ICONS, LangSwitch, STR } = window.MP;

/* ── The document library — full breadth, grouped by category ──────────── */
const DOC_LIBRARY = [
  { cat: "Core documents", items: [
    { id: "privacy", icon: ICONS.shieldCheck, title: "Privacy Policy", desc: "How you collect, use and protect personal data." },
    { id: "cookie", icon: ICONS.cookie, title: "Cookie Policy", desc: "What you store on visitors' devices, and why." },
    { id: "terms", icon: ICONS.doc, title: "Terms of Service", desc: "The rules and contract for using your site." },
  ] },
  { cat: "Commerce", items: [
    { id: "refund", icon: ICONS.refund, title: "Return & Refund Policy", desc: "Conditions, timelines and how refunds work." },
    { id: "shipping", icon: ICONS.truck, title: "Shipping Policy", desc: "Delivery options, costs and timeframes." },
    { id: "eula", icon: ICONS.lock, title: "EULA", desc: "End User License Agreement for software & apps." },
  ] },
  { cat: "Disclosure", items: [
    { id: "disclaimer", icon: ICONS.alertTriangle, title: "Disclaimer", desc: "Limit liability for the content you publish." },
    { id: "aup", icon: ICONS.shieldAlert, title: "Acceptable Use Policy", desc: "What users may and may not do on your service." },
    { id: "affiliate", icon: ICONS.megaphone, title: "Affiliate / Advertising Disclosure", desc: "Disclose paid links and sponsorships (FTC)." },
  ] },
  { cat: "Regional", items: [
    { id: "imprint", icon: ICONS.building, title: "Imprint / Impressum", desc: "Legal notice required across the EU & Germany." },
    { id: "accessibility", icon: ICONS.personStanding, title: "Accessibility Statement", desc: "Your WCAG commitment and conformance status." },
  ] },
];
const DOC_BY_ID = Object.fromEntries(DOC_LIBRARY.flatMap((g) => g.items.map((it) => [it.id, it])));
const DOC_COUNT = Object.keys(DOC_BY_ID).length;

/* Type-appropriate opening line per document kind ({ORG} is filled live).
   Core types are localized; others fall back to English (better than mislabelling). */
const DOC_INTRO = {
  cookie: {
    en: "This Cookie Policy explains how {ORG} uses cookies and similar technologies on our website, and how you can control them.",
    de: "Diese Cookie-Richtlinie erläutert, wie {ORG} Cookies und ähnliche Technologien auf unserer Website verwendet und wie Sie diese steuern können.",
    fr: "Cette politique relative aux cookies explique comment {ORG} utilise les cookies et technologies similaires sur notre site, et comment les contrôler.",
    it: "La presente Cookie Policy spiega come {ORG} utilizza i cookie e tecnologie simili sul nostro sito e come puoi controllarli." },
  terms: {
    en: "These Terms of Service govern your access to and use of {ORG} and form a binding agreement between you and us.",
    de: "Diese Nutzungsbedingungen regeln Ihren Zugang zu und Ihre Nutzung von {ORG} und bilden eine verbindliche Vereinbarung zwischen Ihnen und uns.",
    fr: "Ces conditions d'utilisation régissent votre accès à {ORG} et son utilisation, et constituent un accord contraignant entre vous et nous.",
    it: "I presenti Termini di servizio disciplinano l'accesso e l'uso di {ORG} e costituiscono un accordo vincolante tra te e noi." },
  refund: { en: "This Return & Refund Policy explains the conditions under which {ORG} accepts returns and issues refunds." },
  shipping: { en: "This Shipping Policy sets out how {ORG} processes, ships and delivers your orders." },
  eula: { en: "This End User License Agreement governs your use of the software provided by {ORG}." },
  disclaimer: { en: "This Disclaimer sets out the limits of liability for the information {ORG} publishes on this website." },
  aup: { en: "This Acceptable Use Policy defines how you may and may not use the services provided by {ORG}." },
  affiliate: { en: "This Affiliate & Advertising Disclosure explains the paid relationships behind some of the content on {ORG}." },
  imprint: { en: "This Imprint provides the legal information about {ORG} required by law across the EU and in Germany." },
  accessibility: { en: "This Accessibility Statement sets out {ORG}'s commitment to making this website usable for everyone." },
};

/* English body sections per document kind (intro & contact are localized below) */
const DOC_BODY = {
  cookie: [["What cookies are", "Cookies are small text files placed on your device. We use them to keep the site working, remember your choices and understand how it is used."],
    ["Cookies we use", "Strictly necessary cookies are always active. Analytics, marketing and preference cookies run only with your consent, which you can change anytime via the cookie banner."]],
  terms: [["Using the service", "By accessing {ORG}, you agree to these terms. You must use the service lawfully and not attempt to disrupt or misuse it."],
    ["Accounts", "You are responsible for activity under your account and for keeping your credentials secure."],
    ["Liability", "The service is provided “as is.” To the extent permitted by law, {ORG} is not liable for indirect or consequential loss."]],
  refund: [["Returns", "You may return eligible items within 14 days of delivery in their original condition. Some items are non-returnable for hygiene reasons."],
    ["Refund timelines", "Approved refunds are issued to your original payment method within 5–10 business days of us receiving the return."]],
  shipping: [["Delivery times", "Orders are processed within 1–2 business days. Standard delivery takes 3–5 business days; express options are available at checkout."],
    ["Shipping costs", "Shipping is calculated at checkout based on destination and weight. {ORG} is not responsible for customs duties on international orders."]],
  eula: [["Licence grant", "{ORG} grants you a personal, non-exclusive, non-transferable licence to use the software for its intended purpose."],
    ["Restrictions", "You may not copy, modify, reverse-engineer, resell or sublicense the software except as permitted by law."]],
  disclaimer: [["No professional advice", "Content on {ORG} is for general information only and is not professional, legal or medical advice. Act on it at your own risk."],
    ["External links", "We link to third-party sites for convenience and are not responsible for their content or practices."]],
  aup: [["Prohibited uses", "You may not use {ORG} to break the law, infringe rights, send spam, distribute malware, or attempt to gain unauthorised access."],
    ["Enforcement", "We may suspend or terminate access for violations, and cooperate with authorities where required."]],
  affiliate: [["Affiliate relationships", "{ORG} may earn a commission when you buy through links on our site, at no extra cost to you."],
    ["FTC disclosure", "We only recommend products we believe in. Sponsored content and paid placements are clearly labelled, in line with FTC guidance."]],
  imprint: [["Company details", "{ORG}, registered address on file, company registration and VAT number available on request."],
    ["Responsible for content", "The person responsible for the content of this website is the management of {ORG}, reachable at the contact details below."]],
  accessibility: [["Our commitment", "{ORG} is committed to making this website usable for everyone, including people who rely on assistive technologies."],
    ["Conformance status", "We aim to conform to WCAG 2.2 level AA. If you encounter a barrier, contact us and we will work to resolve it promptly."]],
};

/* ── Jurisdictions — each enabled region adds its own section ───────────── */
const JURIS = [
  { id: "gdpr", law: "GDPR", region: "EU/EEA", title: "GDPR", sub: "European Union & EEA", on: true },
  { id: "ukgdpr", law: "UK GDPR", region: "the UK", title: "UK GDPR", sub: "United Kingdom", on: true },
  { id: "ccpa", law: "CCPA/CPRA", region: "California", title: "CCPA / CPRA", sub: "California, USA", on: true },
  { id: "lgpd", law: "LGPD", region: "Brazil", title: "LGPD", sub: "Brazil", on: false },
  { id: "pipeda", law: "PIPEDA", region: "Canada", title: "PIPEDA", sub: "Canada", on: false },
  { id: "au", law: "the Privacy Act 1988", region: "Australia", title: "Australia Privacy Act", sub: "Australia", on: false },
];
const RIGHTS_TPL = {
  en: (law, region) => `Under ${law}, individuals in ${region} can access, correct, export and delete their personal data, and object to or restrict processing. We verify and honour requests within the statutory time limit.`,
  de: (law, region) => `Gemäß ${law} können Personen in ${region} ihre personenbezogenen Daten einsehen, berichtigen, exportieren und löschen sowie der Verarbeitung widersprechen. Wir prüfen Anfragen und kommen ihnen innerhalb der gesetzlichen Frist nach.`,
  fr: (law, region) => `En vertu du ${law}, les personnes situées en ${region} peuvent accéder à leurs données, les corriger, les exporter et les supprimer, et s'opposer au traitement. Nous traitons les demandes vérifiées dans le délai légal.`,
  it: (law, region) => `Ai sensi del ${law}, le persone in ${region} possono accedere, correggere, esportare ed eliminare i propri dati e opporsi al trattamento. Diamo seguito alle richieste verificate entro i termini di legge.`,
};
const CCPA_BODY = {
  en: "California residents may opt out of the “sale” or “sharing” of personal information and request disclosure of data collected. We honour Global Privacy Control signals.",
  de: "Einwohner Kaliforniens können dem „Verkauf“ oder „Teilen“ personenbezogener Daten widersprechen und Auskunft über erhobene Daten verlangen. Wir beachten Global-Privacy-Control-Signale.",
  fr: "Les résidents de Californie peuvent refuser la « vente » ou le « partage » de leurs données et demander la divulgation des données collectées. Nous respectons les signaux Global Privacy Control.",
  it: "I residenti in California possono rifiutare la “vendita” o “condivisione” dei dati personali e richiedere la divulgazione dei dati raccolti. Rispettiamo i segnali Global Privacy Control.",
};

const STEPS = [
  ["Business details", "Who is the document for?"],
  ["Jurisdictions", "Which laws apply to you?"],
  ["Data practices", "What does your site actually do?"],
  ["Languages", "Where will it be read?"],
  ["Review & publish", "You're covered."],
];
const PRACTICES = [
  ["analytics", "Analytics", "Google Analytics, Plausible, etc."],
  ["marketing", "Marketing & ads", "Retargeting, email, pixels"],
  ["payments", "Payments", "Stripe, PayPal, checkout"],
  ["accounts", "User accounts", "Sign-up, login, profiles"],
];

/* ══ Documents hub — the browsable library ═════════════════════════════ */
function DocsHub({ nav }) {
  return (
    <div className="app-view app-view--wide">
      <div className="app-view__head">
        <div>
          <h1 className="app-h1">Documents</h1>
          <p className="app-sub">Generate any legal document your site needs — localized, hosted and kept up to date.</p>
        </div>
        <Badge tone="accent">{DOC_COUNT} document types</Badge>
      </div>

      <div className="wz-transparent" style={{ marginTop: 0, marginBottom: 22 }}>
        <Icon d={ICONS.shieldCheck} size={18} />
        <span><b style={{ color: "var(--fg)" }}>Every type is included.</b> No per-document fees and no per-clause unlocks — pick one and answer a few questions to generate it in 30+ languages.</span>
      </div>

      {DOC_LIBRARY.map((group) => (
        <div className="docs-cat" key={group.cat}>
          <div className="docs-cat__label">{group.cat}</div>
          <div className="docs-grid">
            {group.items.map((it) => (
              <Card key={it.id} className="doc-tile" onClick={() => nav("app", "wizard", it.id)}>
                <CardBody>
                  <span className="doc-tile__icon"><Icon d={it.icon} size={20} /></span>
                  <h3 className="doc-tile__title">{it.title}</h3>
                  <p className="doc-tile__desc">{it.desc}</p>
                  <span className="doc-tile__go">Generate <Icon d={ICONS.arrow} size={13} /></span>
                </CardBody>
              </Card>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ══ The generator wizard ══════════════════════════════════════════════ */
function Wizard({ lang, setLang, nav, initial }) {
  const docType = initial && DOC_BY_ID[initial] ? initial : "privacy";
  const meta = DOC_BY_ID[docType];
  const [step, setStep] = React.useState(0);
  const [org, setOrg] = React.useState("Café Lumière");
  const [email, setEmail] = React.useState("privacy@cafe-lumiere.fr");
  const [juris, setJuris] = React.useState(Object.fromEntries(JURIS.map((j) => [j.id, j.on])));
  const [practices, setPractices] = React.useState({ analytics: true, marketing: false, payments: true, accounts: true });
  const [docLangs, setDocLangs] = React.useState(["en", "fr", "de"]);

  const [pub, setPub] = React.useState({ state: "idle", url: null, err: "" }); // idle|busy|done|error

  React.useEffect(() => { setStep(0); setPub({ state: "idle", url: null, err: "" }); }, [docType]);
  const next = () => setStep((s) => Math.min(STEPS.length - 1, s + 1));
  const back = () => setStep((s) => Math.max(0, s - 1));
  const toggleLang = (c) => setDocLangs((p) => p.includes(c) ? p.filter((x) => x !== c) : [...p, c]);
  const enabledJuris = JURIS.filter((j) => juris[j.id]);

  // wizard juris id → backend legaldocs jurisdiction key
  const JURIS_KEY = { gdpr: "gdpr", ukgdpr: "uk_gdpr", ccpa: "ccpa", lgpd: "lgpd", pipeda: "pipeda", au: "au" };
  async function publishDoc() {
    const api = window.MPApi || { ready: false };
    const website = (email.split("@")[1] || "your-site.com").trim();
    const req = {
      docType, // backend supports privacy/cookie/terms today; others return a clear error
      answers: { org, website, email, effectiveDate: new Date().toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" }) },
      jurisdictions: enabledJuris.map((j) => JURIS_KEY[j.id]).filter(Boolean),
      locales: docLangs,
    };
    if (!api.ready) { setPub({ state: "done", url: website + "/legal/" + docType, err: "" }); return; }
    setPub({ state: "busy", url: null, err: "" });
    try {
      const gen = await api.generateDocument(req);
      const out = await api.publishDocument(gen.documentId);
      const url = (out && out.exports && out.exports[docLangs[0]] && out.exports[docLangs[0]].html) || null;
      setPub({ state: "done", url, err: "" });
    } catch (e) {
      setPub({ state: "error", url: null, err: (e && e.message) || "Could not publish. Try again." });
    }
  }

  return (
    <div className="wz">
      {/* rail */}
      <div className="wz__rail">
        <button className="wz-back" onClick={() => nav("app", "documents")}><Icon d={ICONS.arrow} size={14} style={{ transform: "rotate(180deg)" }} /> All documents</button>
        <div className="wz-doctype">
          <span className="wz-doctype__ic"><Icon d={meta.icon} size={18} /></span>
          <div><div className="wz-doctype__t">{meta.title}</div><div className="wz-doctype__s">{meta.desc}</div></div>
        </div>
        <ol className="wz-steps">
          {STEPS.map(([t, s], i) => (
            <li key={t} className={"wz-step" + (i === step ? " is-active" : "") + (i < step ? " is-done" : "")} onClick={() => setStep(i)}>
              <span className="wz-step__dot">{i < step ? <Icon d={ICONS.check} size={14} /> : i + 1}</span>
              <div><div className="wz-step__t">{t}</div><div className="wz-step__s">{s}</div></div>
            </li>
          ))}
        </ol>
      </div>

      {/* form + doc */}
      <div className="wz__main">
        <div className="wz__form">
          <div className="wz-form__head">
            <div className="wz-form__eyebrow">{meta.title} · Step {step + 1} of {STEPS.length}</div>
            <h2 className="wz-form__h">{STEPS[step][0]}</h2>
            <p className="wz-form__sub">{STEPS[step][1]}</p>
          </div>

          {step === 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <Field label="Legal / business name" hint="Appears throughout the document."><Input value={org} onChange={(e) => setOrg(e.target.value)} /></Field>
              <Field label="Website"><Input defaultValue="café-lumiere.fr" /></Field>
              <Field label="Contact email" hint="Where data requests are sent."><Input value={email} onChange={(e) => setEmail(e.target.value)} /></Field>
              <Field label="Company type"><Select options={["Sole trader / freelancer", "Limited company", "Non-profit", "Agency"]} defaultValue="Limited company" /></Field>
            </div>
          )}

          {step === 1 && (
            <div className="wz-juris">
              {JURIS.map((j) => (
                <div key={j.id} className={"wz-toggle-card" + (juris[j.id] ? " is-on" : "")} onClick={() => setJuris((p) => ({ ...p, [j.id]: !p[j.id] }))}>
                  <div><div className="wz-toggle-card__t">{j.title}</div><div className="wz-toggle-card__s">{j.sub}</div></div>
                  <span className="wz-toggle-card__sw"><Switch checked={juris[j.id]} onChange={() => setJuris((p) => ({ ...p, [j.id]: !p[j.id] }))} /></span>
                </div>
              ))}
            </div>
          )}

          {step === 2 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {PRACTICES.map(([id, t, d]) => (
                <div key={id} className={"wz-toggle-card" + (practices[id] ? " is-on" : "")} onClick={() => setPractices((p) => ({ ...p, [id]: !p[id] }))}>
                  <div><div className="wz-toggle-card__t">{t}</div><div className="wz-toggle-card__s">{d}</div></div>
                  <span className="wz-toggle-card__sw"><Switch checked={practices[id]} onChange={() => setPractices((p) => ({ ...p, [id]: !p[id] }))} /></span>
                </div>
              ))}
            </div>
          )}

          {step === 3 && (
            <div>
              <div className="bb-group__label" style={{ marginBottom: 12 }}>Translate this document into</div>
              <div className="bb-langrow">
                {window.MP.LANGS.map((l) => (
                  <button key={l.code} className={"bb-langchip" + (docLangs.includes(l.code) ? " is-active" : "")} onClick={() => toggleLang(l.code)}>
                    {l.name}{docLangs.includes(l.code) && <span className="x"><Icon d={ICONS.check} size={9} /></span>}
                  </button>
                ))}
              </div>
              <div style={{ fontSize: 12.5, color: "var(--fg-muted)", marginTop: 14, lineHeight: 1.5 }}>
                Your document will be generated and kept in sync across {docLangs.length} languages. Preview any of them on the right.
              </div>
            </div>
          )}

          {step === 4 && (
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div className="relief" style={{ margin: 0 }}>
                <span className="relief__badge"><Icon d={ICONS.shieldCheck} size={26} /></span>
                <div><div className="relief__t">Your {meta.title} is ready.</div><div className="relief__s">{docLangs.length} languages · {enabledJuris.length} jurisdictions</div></div>
              </div>
              <Field label="Publish to a hosted URL" hint="Auto-updates as the law and your answers change.">
                <Input defaultValue={"café-lumiere.fr/legal/" + docType} icon={<Icon d={ICONS.globe} size={15} />} />
              </Field>
              <div style={{ display: "flex", gap: 8 }}>
                <Button variant="secondary" size="sm" iconLeft={<Icon d={ICONS.download} size={14} />}>HTML</Button>
                <Button variant="secondary" size="sm" iconLeft={<Icon d={ICONS.download} size={14} />}>PDF</Button>
                <Button variant="secondary" size="sm" iconLeft={<Icon d={ICONS.download} size={14} />}>DOCX</Button>
              </div>
              {pub.state === "done" && (
                <div className="wz-transparent" style={{ background: "var(--accent-bg-soft)" }}>
                  <Icon d={ICONS.check} size={18} />
                  <span><b style={{ color: "var(--fg)" }}>Published.</b> {pub.url ? <>Live at <a href={/^https?:/.test(pub.url) ? pub.url : "https://" + pub.url} target="_blank" rel="noopener">{pub.url}</a>.</> : "Your document is live and auto-updating."} Review the generated text before relying on it.</span>
                </div>
              )}
              {pub.state === "error" && <div style={{ color: "var(--danger, #b3261e)", fontSize: 13 }}>{pub.err}</div>}
            </div>
          )}

          <div className="wz-form__actions">
            {step > 0 && <Button variant="secondary" onClick={back}>Back</Button>}
            {step < STEPS.length - 1
              ? <Button variant="primary" iconRight={<Icon d={ICONS.arrow} size={15} />} onClick={next}>Continue</Button>
              : <Button variant="primary" disabled={pub.state === "busy"} iconLeft={<Icon d={ICONS.publish} size={15} />} onClick={publishDoc}>{pub.state === "busy" ? "Publishing…" : pub.state === "done" ? "Published ✓" : "Publish document"}</Button>}
          </div>

          {step < 4 && (
            <div className="wz-transparent">
              <Icon d={ICONS.shieldCheck} size={18} />
              <span><b style={{ color: "var(--fg)" }}>What you see is included.</b> No per-clause unlock fees, no “upgrade to reveal.” Every clause your answers require is in the document.</span>
            </div>
          )}
        </div>

        {/* live doc */}
        <div className="wz__doc">
          <div className="doc-toolbar">
            <Badge tone="accent" dot>Updating live</Badge>
            <span className="grow" />
            <LangSwitch value={lang} onChange={setLang} />
          </div>
          <LiveDoc docType={docType} org={org} email={email} enabledJuris={enabledJuris} practices={practices} lang={lang} />
        </div>
      </div>
    </div>
  );
}

function LiveDoc({ docType, org, email, enabledJuris, practices, lang }) {
  const p = STR[lang].policy;
  const meta = DOC_BY_ID[docType];
  const orgName = org || "Your business";
  const fillOrg = (s) => {
    const parts = s.split("{ORG}");
    return parts.flatMap((seg, i) => i === 0 ? [seg] : [<span className="fill" key={i}>{orgName}</span>, seg]);
  };
  const showRegions = docType === "privacy" || docType === "cookie";

  // intro — type-appropriate (privacy/cookie/terms localized; others English)
  const introStr = docType === "privacy"
    ? p.intro
    : (DOC_INTRO[docType] && (DOC_INTRO[docType][lang] || DOC_INTRO[docType].en)) || p.intro;
  const introParts = introStr.split("{ORG}");
  let n = 0; const num = () => String(++n).padStart(2, "0");

  // middle sections
  const middle = [];
  if (docType === "privacy") {
    const dataItems = { analytics: "usage analytics", marketing: "marketing identifiers", payments: "billing details", accounts: "account credentials" };
    const collected = ["your name and email", ...Object.entries(practices).filter(([, v]) => v).map(([k]) => dataItems[k])].join(", ");
    middle.push([p.secs[0][0], lang === "en"
      ? <>We collect <span className="fill">{collected}</span>, plus data gathered automatically such as your IP address and cookies.</>
      : p.secs[0][1]]);
    middle.push([p.secs[1][0], p.secs[1][1]]);
  } else {
    (DOC_BODY[docType] || []).forEach(([h, body]) => middle.push([h, fillOrg(body)]));
  }

  return (
    <div className="doc-paper">
      <div className="doc-paper__brandline">
        <span className="doc-paper__org">{orgName}</span>
        <span style={{ fontSize: 11, color: "var(--fg-subtle)", fontFamily: "var(--font-mono)" }}>{lang.toUpperCase()}</span>
      </div>
      <h1 className="doc-h1">{docType === "privacy" ? p.title : meta.title}</h1>
      <div className="doc-meta">{p.updated}: 10 Jun 2026{showRegions && enabledJuris.length ? " · " + enabledJuris.map((j) => j.title).join(" · ") : ""}</div>

      <div className="doc-sec"><p>{introParts[0]}<span className="fill">{orgName}</span>{introParts[1]}</p></div>

      {middle.map(([h, body], i) => (
        <div className="doc-sec" key={"m" + i}>
          <h2 className="doc-sec__h"><span className="num">{num()}</span>{h}</h2>
          <p>{body}</p>
        </div>
      ))}

      {showRegions && enabledJuris.map((j) => (
        <div className="doc-sec" key={j.id}>
          <h2 className="doc-sec__h"><span className="num">{num()}</span>{j.id === "ccpa" ? "California privacy rights" : "Your rights"} <span className="fill" style={{ fontWeight: 600 }}>· {j.title}</span></h2>
          <p>{j.id === "ccpa" ? CCPA_BODY[lang] : RIGHTS_TPL[lang](j.law, j.region)}</p>
        </div>
      ))}

      <div className="doc-sec">
        <h2 className="doc-sec__h"><span className="num">{num()}</span>Contact</h2>
        <p>{lang === "en" ? <>Questions about this document? Email us at <span className="fill">{email || "your email"}</span>.</> : <>{orgName}: <span className="fill">{email}</span></>}</p>
      </div>
    </div>
  );
}

Object.assign(window.MP, { Wizard, DocsHub, DOC_COUNT });
})();
