/* Grow in Uganda — modal flows (sponsor / donate / member / rejse / notify)
   Mounted once per page into #modal-root. Exposes window.GU.open*(). */

/* ---- Generic modal shell ---- */
function ModalShell({ title, onClose, children, width = 480 }) {
  useEffect(() => { refreshIcons(); });
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(46,24,9,.55)", backdropFilter: "blur(3px)", display: "flex",
      alignItems: "center", justifyContent: "center", padding: 20, animation: "fadeUp .25s ease both" }}>
      <div onClick={e => e.stopPropagation()} style={{ background: "var(--white)", borderRadius: "var(--r-xl)",
        width, maxWidth: "100%", maxHeight: "92vh", overflowY: "auto", boxShadow: "var(--shadow-lg)" }}>
        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--divider)", display: "flex",
          alignItems: "center", justifyContent: "space-between", position: "sticky", top: 0, background: "var(--white)", zIndex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <FlagRule w={36} />
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 19, color: "var(--brown-800)" }}>{title}</span>
          </div>
          <a onClick={onClose} style={{ cursor: "pointer", color: "var(--fg-subtle)", display: "flex" }}><Icon name="x" size={22} /></a>
        </div>
        {children}
      </div>
    </div>
  );
}

function AmountPicker({ amounts, value, onChange, suffix = " kr." }) {
  return (
    <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
      {amounts.map(a => (
        <div key={a} onClick={() => onChange(a)} style={{ flex: "1 1 22%", minWidth: 72, textAlign: "center", padding: "13px 0", borderRadius: "var(--r-sm)",
          fontWeight: 800, fontSize: 14, cursor: "pointer",
          border: "1.5px solid " + (value === a ? "var(--red-600)" : "var(--border)"),
          background: value === a ? "var(--red-50)" : "var(--white)",
          color: value === a ? "var(--red-600)" : "var(--brown-600)" }}>
          {a === "Andet" ? a : a + suffix}
        </div>
      ))}
    </div>
  );
}

function ThankYou({ icon = "heart-handshake", title, body, onClose }) {
  return (
    <div style={{ padding: "34px 26px 30px", textAlign: "center" }}>
      <div style={{ width: 72, height: 72, borderRadius: "var(--r-pill)", background: "var(--green-100)",
        display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 18px" }}>
        <Icon name={icon} size={34} color="var(--green-600)" />
      </div>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 24, color: "var(--brown-800)", marginBottom: 8 }}>{title}</div>
      <p style={{ color: "var(--fg-muted)", fontSize: 15, lineHeight: 1.65, maxWidth: 340, margin: "0 auto 22px" }}>{body}</p>
      <Button variant="primary" onClick={onClose}>Luk</Button>
    </div>
  );
}

/* ---- Sponsor flow ---- */
function SponsorModal({ child, onClose }) {
  const [step, setStep] = useState(1);
  const [amount, setAmount] = useState("200");
  return (
    <ModalShell title={step < 3 ? `Bliv ${child.name}s fadder` : "Tak for din støtte!"} onClose={onClose}>
      {step === 1 && (
        <div style={{ padding: 26 }}>
          <div style={{ display: "flex", gap: 14, marginBottom: 20, alignItems: "center" }}>
            <img src={child.photo || (ASSET + "placeholder-portrait.svg")} alt="" style={{ width: 72, height: 72, borderRadius: "var(--r-md)", objectFit: "cover", objectPosition: child.pos || "center" }} />
            <div>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 20, color: "var(--brown-800)" }}>{child.name}, {child.age} år</div>
              <div style={{ fontSize: 13.5, color: "var(--fg-subtle)" }}>{child.place} · {child.grade}</div>
            </div>
          </div>
          <label style={{ fontWeight: 700, fontSize: 13, color: "var(--fg-muted)", display: "block", marginBottom: 9 }}>Vælg dit månedlige bidrag</label>
          <AmountPicker amounts={["100", "200", "350", "Andet"]} value={amount} onChange={setAmount} />
          <div style={{ background: "var(--green-50)", borderRadius: "var(--r-md)", padding: "12px 14px", margin: "18px 0 20px",
            display: "flex", gap: 9, fontSize: 13.5, color: "var(--green-700)", lineHeight: 1.5 }}>
            <Icon name="shield-check" size={18} /> Hele dit bidrag går til {child.name}s skolegang, måltider og uniform.
          </div>
          <Button variant="primary" iconRight="arrow-right" style={{ width: "100%" }} onClick={() => setStep(2)}>Fortsæt</Button>
        </div>
      )}
      {step === 2 && (
        <div style={{ padding: 26 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 16 }}>
            <Field label="Fornavn" placeholder="Anna" />
            <Field label="Efternavn" placeholder="Hansen" />
            <Field label="E-mail" placeholder="anna@eksempel.dk" full />
            <Field label="Telefon" placeholder="+45" full />
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "14px 16px",
            background: "var(--sand-100)", borderRadius: "var(--r-md)", marginBottom: 20 }}>
            <span style={{ fontWeight: 700, color: "var(--fg-muted)", fontSize: 14 }}>Månedligt fadderskab</span>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 20, color: "var(--brown-800)" }}>
              {amount === "Andet" ? "200" : amount} kr./md.
            </span>
          </div>
          <Button variant="primary" icon="heart-handshake" style={{ width: "100%" }} onClick={() => setStep(3)}>Bekræft fadderskab</Button>
          <a onClick={() => setStep(1)} style={{ display: "block", textAlign: "center", marginTop: 14, cursor: "pointer", color: "var(--green-600)", fontWeight: 700, fontSize: 14 }}>← Tilbage</a>
        </div>
      )}
      {step === 3 && (
        <ThankYou title={`Du er nu ${child.name}s fadder`}
          body={`Du modtager snart et fadderskabsbevis med billede af ${child.name} — og en personlig hilsen én gang om året.`} onClose={onClose} />
      )}
    </ModalShell>
  );
}

/* ---- One-time / recurring donation ---- */
function DonateModal({ project, onClose }) {
  const [step, setStep] = useState(1);
  const [mode, setMode] = useState("once");
  const [amount, setAmount] = useState("300");
  return (
    <ModalShell title={step < 2 ? "Donér" : "Tak for din gave!"} onClose={onClose}>
      {step === 1 && (
        <div style={{ padding: 26 }}>
          {project && <div style={{ display: "flex", gap: 9, alignItems: "center", background: "var(--sand-100)", borderRadius: "var(--r-md)",
            padding: "11px 14px", marginBottom: 18, fontSize: 14, color: "var(--fg-muted)", fontWeight: 700 }}>
            <Icon name="target" size={17} color="var(--green-600)" /> Til: {project}</div>}
          <div style={{ display: "flex", gap: 8, marginBottom: 18 }}>
            {[["once", "Engangsbeløb"], ["monthly", "Månedligt"]].map(([k, l]) => (
              <div key={k} onClick={() => setMode(k)} style={{ flex: 1, textAlign: "center", padding: "11px 0", borderRadius: "var(--r-sm)",
                fontWeight: 800, fontSize: 14, cursor: "pointer",
                border: "1.5px solid " + (mode === k ? "var(--green-600)" : "var(--border)"),
                background: mode === k ? "var(--green-50)" : "var(--white)",
                color: mode === k ? "var(--green-700)" : "var(--brown-600)" }}>{l}</div>
            ))}
          </div>
          <label style={{ fontWeight: 700, fontSize: 13, color: "var(--fg-muted)", display: "block", marginBottom: 9 }}>Vælg beløb</label>
          <AmountPicker amounts={["150", "300", "500", "Andet"]} value={amount} onChange={setAmount} />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, margin: "18px 0 18px" }}>
            <Field label="Navn" placeholder="Anna Hansen" full />
            <Field label="E-mail" placeholder="anna@eksempel.dk" full />
          </div>
          <div style={{ background: "var(--green-50)", borderRadius: "var(--r-md)", padding: "12px 14px", marginBottom: 18,
            display: "flex", gap: 9, fontSize: 13.5, color: "var(--green-700)", lineHeight: 1.5 }}>
            <Icon name="badge-check" size={18} /> Din donation er fradragsberettiget efter §8A.
          </div>
          <Button variant="primary" icon="hand-coins" style={{ width: "100%" }} onClick={() => setStep(2)}>
            Donér {amount === "Andet" ? "" : amount + " kr."}{mode === "monthly" ? "/md." : ""}
          </Button>
          <p style={{ margin: "12px 0 0", textAlign: "center", color: "var(--fg-subtle)", fontSize: 11.5, lineHeight: 1.55 }}>
            Ved at fortsætte accepterer du vores <a href="aftalevilkaar.html" target="_blank" rel="noopener" style={{ color: "var(--green-700)", textDecoration: "underline" }}>aftalevilkår</a> og <a href="privatlivspolitik.html" target="_blank" rel="noopener" style={{ color: "var(--green-700)", textDecoration: "underline" }}>privatlivspolitik</a>.
          </p>
        </div>
      )}
      {step === 2 && (
        <ThankYou icon="heart" title="Tusind tak!"
          body="Din gave gør en konkret forskel for børnene i Uganda. Du modtager en kvittering på e-mail." onClose={onClose} />
      )}
    </ModalShell>
  );
}

/* ---- Membership ---- */
function MemberModal({ onClose }) {
  const [step, setStep] = useState(1);
  const [tier, setTier] = useState("200");
  const tiers = [["100", "Støttemedlem", "100 kr./år"], ["200", "Medlem", "200 kr./år"], ["500", "Ildsjæl", "500 kr./år"]];
  return (
    <ModalShell title={step < 2 ? "Bliv medlem" : "Velkommen!"} onClose={onClose}>
      {step === 1 && (
        <div style={{ padding: 26 }}>
          <p style={{ margin: "0 0 18px", fontSize: 14.5, color: "var(--fg-muted)", lineHeight: 1.6 }}>
            Som medlem støtter du foreningens arbejde bredt og er med til at gøre nye fadderskaber mulige.
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 20 }}>
            {tiers.map(([k, t, p]) => (
              <div key={k} onClick={() => setTier(k)} style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
                padding: "14px 16px", borderRadius: "var(--r-md)", cursor: "pointer",
                border: "1.5px solid " + (tier === k ? "var(--green-600)" : "var(--border)"),
                background: tier === k ? "var(--green-50)" : "var(--white)" }}>
                <span style={{ fontWeight: 800, color: "var(--brown-800)" }}>{t}</span>
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, color: tier === k ? "var(--green-700)" : "var(--brown-600)" }}>{p}</span>
              </div>
            ))}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 18 }}>
            <Field label="Navn" placeholder="Anna Hansen" full />
            <Field label="E-mail" placeholder="anna@eksempel.dk" full />
          </div>
          <Button variant="accent" icon="user-plus" style={{ width: "100%" }} onClick={() => setStep(2)}>Bliv medlem</Button>
        </div>
      )}
      {step === 2 && (
        <ThankYou icon="user-check" title="Velkommen som medlem"
          body="Tak fordi du støtter Grow in Uganda. Du modtager en bekræftelse og vores nyhedsbrev på e-mail." onClose={onClose} />
      )}
    </ModalShell>
  );
}

/* ---- Rejse interest ---- */
function RejseModal({ onClose }) {
  const [step, setStep] = useState(1);
  return (
    <ModalShell title={step < 2 ? "Tilmeld interesse" : "Tak!"} onClose={onClose}>
      {step === 1 && (
        <div style={{ padding: 26 }}>
          <div style={{ display: "flex", gap: 10, marginBottom: 18 }}>
            <Badge tone="gold">Næste hold: oktober 2026</Badge>
            <Badge tone="brown">14 dage</Badge>
          </div>
          <p style={{ margin: "0 0 18px", fontSize: 14.5, color: "var(--fg-muted)", lineHeight: 1.6 }}>
            Skriv dig op, så kontakter vi dig med program, pris og praktisk info — helt uforpligtende.
          </p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
            <Field label="Navn" placeholder="Anna Hansen" full />
            <Field label="E-mail" placeholder="anna@eksempel.dk" />
            <Field label="Telefon" placeholder="+45" />
            <Field label="Antal rejsende" placeholder="1" />
          </div>
          <Field label="Besked (valgfri)" placeholder="Fortæl os gerne lidt om jer …" as="textarea" full />
          <div style={{ marginTop: 18 }}>
            <Button variant="primary" icon="plane" style={{ width: "100%" }} onClick={() => setStep(2)}>Send tilmelding</Button>
          </div>
        </div>
      )}
      {step === 2 && (
        <ThankYou icon="plane" title="Tak for din interesse"
          body="Vi vender tilbage med program og pris for næste rejse til Masaka. Vi glæder os til at rejse med dig." onClose={onClose} />
      )}
    </ModalShell>
  );
}

/* ---- Notify (webshop) ---- */
function NotifyModal({ onClose }) {
  const [step, setStep] = useState(1);
  return (
    <ModalShell title={step < 2 ? "Få besked, når vi åbner" : "Tak!"} onClose={onClose} width={420}>
      {step === 1 && (
        <div style={{ padding: 26 }}>
          <p style={{ margin: "0 0 18px", fontSize: 14.5, color: "var(--fg-muted)", lineHeight: 1.6 }}>
            Webshoppen åbner op til skolestart. Skriv din e-mail, så sender vi dig en besked, før den åbner.
          </p>
          <Field label="E-mail" placeholder="anna@eksempel.dk" full />
          <div style={{ marginTop: 18 }}>
            <Button variant="gold" icon="bell" style={{ width: "100%" }} onClick={() => setStep(2)}>Hold mig opdateret</Button>
          </div>
        </div>
      )}
      {step === 2 && (
        <ThankYou icon="bell-ring" title="Du er på listen" body="Vi sender dig en e-mail, så snart webshoppen åbner." onClose={onClose} />
      )}
    </ModalShell>
  );
}

/* ---- Modal host: registers window.GU openers ---- */
function ModalHost() {
  const [modal, setModal] = useState(null);
  useEffect(() => {
    window.GU = window.GU || {};
    window.GU.openSponsor = (child) => setModal({ type: "sponsor", child });
    window.GU.openDonate  = (project) => setModal({ type: "donate", project: typeof project === "string" ? project : null });
    window.GU.openMember  = () => setModal({ type: "member" });
    window.GU.openRejse   = () => setModal({ type: "rejse" });
    window.GU.openNotify  = () => setModal({ type: "notify" });
  }, []);
  useEffect(() => {
    const esc = (e) => { if (e.key === "Escape") setModal(null); };
    window.addEventListener("keydown", esc);
    return () => window.removeEventListener("keydown", esc);
  }, []);
  if (!modal) return null;
  const close = () => setModal(null);
  if (modal.type === "sponsor") return <SponsorModal child={modal.child} onClose={close} />;
  if (modal.type === "donate")  return <DonateModal project={modal.project} onClose={close} />;
  if (modal.type === "member")  return <MemberModal onClose={close} />;
  if (modal.type === "rejse")   return <RejseModal onClose={close} />;
  if (modal.type === "notify")  return <NotifyModal onClose={close} />;
  return null;
}

Object.assign(window, { ModalHost, SponsorModal, DonateModal, MemberModal, RejseModal, NotifyModal, ModalShell, ThankYou, AmountPicker });
