// MostlyPrivacy — public, embeddable Data-Subject-Request form (F155).
// Served per-site at /dsar?site=<siteId> (drop into an <iframe> on a customer site).
// A visitor picks a right (access / delete / correct / opt-out / portability), gives
// the email we verify them at, and submits → submitDsar. We never expose anything but
// the confirmation; the verification link is emailed out-of-band. Matches the calm
// MostlyPrivacy banner styling (accent tile + soft card), standalone + SSR-friendly.
(function () {
const F = window.ForgeDesignSystem_e40d74;
const { Button, Field, Input, Select } = F;
const { Icon, ICONS, PrivacyMark, Wordmark } = window.MP;
const I18N = (typeof window !== "undefined" && window.ForgeI18n) || { t: (k) => k };
const tr = (k, d) => { const v = I18N.t(k); return v === k && d != null ? d : v; };

// The five data-subject rights we intake. `desc` is a plain-English hint; the labels
// mirror the request types the backend accepts (REQUEST_TYPES in functions/dsar.js).
const RIGHTS = [
  { id: "access", icon: ICONS.doc, label: tr("dsar.right.access", "Access my data"), desc: tr("dsar.right.access.desc", "Get a copy of the personal data held about you.") },
  { id: "delete", icon: ICONS.shieldAlert, label: tr("dsar.right.delete", "Delete my data"), desc: tr("dsar.right.delete.desc", "Ask for your personal data to be erased.") },
  { id: "correct", icon: ICONS.refresh, label: tr("dsar.right.correct", "Correct my data"), desc: tr("dsar.right.correct.desc", "Fix data that is wrong or out of date.") },
  { id: "opt-out", icon: ICONS.lock, label: tr("dsar.right.optout", "Opt out of sale/sharing"), desc: tr("dsar.right.optout.desc", "Stop the sale or sharing of your data.") },
  { id: "portability", icon: ICONS.download, label: tr("dsar.right.portability", "Export my data"), desc: tr("dsar.right.portability.desc", "Receive your data in a portable format.") },
];

function endpoint() {
  // The public onRequest submit URL. In live mode api.js resolves the functions base.
  const api = window.MPApi;
  const base = (api && api.consentApi) || "";
  return base ? base.replace(/\/+$/, "") + "/submitDsar" : "/submitDsar";
}

function DsarForm({ siteId }) {
  const params = (function () { try { return new URLSearchParams(location.search); } catch (e) { return new URLSearchParams(""); } })();
  const site = siteId || params.get("site") || params.get("siteId") || "";
  const locale = (window.ForgeI18n && window.ForgeI18n.locale) || "en";
  const countries = (window.MPJurisdictions && window.MPJurisdictions.countryList(locale)) || [];

  const [type, setType] = React.useState("access");
  const [email, setEmail] = React.useState("");
  const [country, setCountry] = React.useState("");
  const [details, setDetails] = React.useState("");
  const [state, setState] = React.useState("idle"); // idle | submitting | done | error
  const [err, setErr] = React.useState("");

  const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());

  async function submit(e) {
    if (e && e.preventDefault) e.preventDefault();
    if (!validEmail || state === "submitting") return;
    setState("submitting"); setErr("");
    const payload = { siteId: site, type, email: email.trim(), country: country || undefined, details: details.trim() || undefined };
    try {
      // Prefer the facade (handles demo mode); fall back to a direct POST when embedded
      // standalone without the SPA facade loaded.
      let r;
      if (window.MPApi && window.MPApi.submitDsar) {
        r = await window.MPApi.submitDsar(payload);
      } else {
        const res = await fetch(endpoint(), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
        r = await res.json();
        if (!res.ok || !r.ok) throw new Error((r && r.error) || "Request failed.");
      }
      if (r && r.ok === false) throw new Error(r.error || "Request failed.");
      setState("done");
    } catch (e2) {
      setErr((e2 && e2.message) || tr("dsar.form.error", "Could not submit your request. Please try again."));
      setState("error");
    }
  }

  return (
    <div className="dsar-page">
      <div className="dsar-card">
        <div className="dsar-card__head">
          <span className="dsar-mark"><PrivacyMark s={28} /></span>
          <div>
            <h1 className="dsar-title">{tr("dsar.form.title", "Submit a privacy request")}</h1>
            <p className="dsar-sub">{tr("dsar.form.subtitle", "Exercise your data-protection rights. We'll email you a link to verify it's really you.")}</p>
          </div>
        </div>

        {state === "done" ? (
          <div className="dsar-done">
            <span className="dsar-done__ic"><Icon d={ICONS.shieldCheck} size={30} /></span>
            <h2 className="dsar-done__t">{tr("dsar.done.title", "Check your email")}</h2>
            <p className="dsar-done__s">{tr("dsar.done.body", "We've sent a verification link to your email. Click it to confirm your request — the site owner will then respond within the statutory deadline.")}</p>
          </div>
        ) : (
          <form className="dsar-form" onSubmit={submit}>
            <div className="dsar-field-label">{tr("dsar.form.whatToDo", "What would you like to do?")}</div>
            <div className="dsar-rights">
              {RIGHTS.map((r) => (
                <button type="button" key={r.id} className={"dsar-right" + (type === r.id ? " is-active" : "")} onClick={() => setType(r.id)}>
                  <span className="dsar-right__ic"><Icon d={r.icon} size={17} /></span>
                  <span className="dsar-right__label">{r.label}</span>
                  <span className="dsar-right__desc">{r.desc}</span>
                </button>
              ))}
            </div>

            <Field label={tr("dsar.form.email", "Your email")} hint={tr("dsar.form.emailHint", "We only use this to verify the request and reach you. It is not stored in the clear.")}>
              <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" required />
            </Field>

            {countries.length > 0 && (
              <Field label={tr("dsar.form.country", "Your country (optional)")} hint={tr("dsar.form.countryHint", "Helps us apply the right law and deadline.")}>
                <Select value={country} onChange={(e) => setCountry(e && e.target ? e.target.value : e)}
                  options={[{ value: "", label: tr("dsar.form.countrySelect", "Select…") }].concat(countries.map((c) => ({ value: c.code, label: c.name })))} />
              </Field>
            )}

            <Field label={tr("dsar.form.details", "Anything to add? (optional)")}>
              <textarea className="dsar-textarea" value={details} maxLength={1000} rows={3}
                onChange={(e) => setDetails(e.target.value)} placeholder={tr("dsar.form.detailsPlaceholder", "Extra context for the site owner…")} />
            </Field>

            {err && <div className="dsar-err">{err}</div>}
            {!site && <div className="dsar-err">{tr("dsar.form.noSite", "This form is missing its site reference (?site=…).")}</div>}

            <Button variant="primary" type="submit" disabled={!validEmail || !site || state === "submitting"} style={{ width: "100%", marginTop: 6 }}>
              {state === "submitting" ? tr("dsar.form.submitting", "Submitting…") : tr("dsar.form.submit", "Submit request")}
            </Button>
            <p className="dsar-legal">{tr("dsar.form.legal", "By submitting you confirm the information is accurate. We verify every request before acting on it.")}</p>
          </form>
        )}

        <a className="dsar-badge" href="https://mostlyprivacy.com" target="_blank" rel="noopener">
          <span className="bolt"><Icon d={ICONS.bolt} size={11} /></span>{tr("dsar.form.poweredBy", "Powered by")}&nbsp;<Wordmark size={13} />
        </a>
      </div>
    </div>
  );
}

window.MPDsarForm = DsarForm;
window.MP = Object.assign(window.MP || {}, { DsarForm });
})();
