function SignDone({ email, onClose }) {
  const { Button } = window.IAIGADesignSystem_db07e0;
  const { Icon } = window;
  const [copied, setCopied] = React.useState(false);

  const shareUrl = "https://iaiga.org";
  const shareText = "I just signed the IAIGA petition calling for global AI governance. Join me — eight billion people have a stake.";
  const encodedUrl = encodeURIComponent(shareUrl);

  const copyLink = () => {
    navigator.clipboard.writeText(shareUrl).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  return (
    <div className="sign sign--done">
      <div className="sign__seal" style={{ background: "var(--gold-500)" }}>
        <Icon.ArrowRight width={28} height={28} />
      </div>
      <h3 className="sign__title">Check your email.</h3>
      <p className="sign__sub">
        We sent a verification link to <strong style={{ fontFamily: "var(--font-mono)", color: "var(--gold-600)" }}>{email}</strong>.
        Click it to confirm your signature — it takes one click and your name will appear on the wall instantly.
      </p>
      <div style={{ marginTop: "var(--space-5)" }}>
        <p style={{ fontSize: "13px", color: "var(--text-muted)", marginBottom: "var(--space-3)", textAlign: "center" }}>While you wait — share with your network</p>
        <div className="share-bar">
          <button className="share-btn" onClick={copyLink}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
            {copied ? "Copied!" : "Copy link"}
          </button>
          <a className="share-btn" href={`https://x.com/intent/tweet?url=${encodedUrl}&text=${encodeURIComponent(shareText)}`} target="_blank" rel="noopener noreferrer">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.744l7.736-8.854L1.254 2.25H8.08l4.257 5.629L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"/></svg>
            X
          </a>
          <a className="share-btn" href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`} target="_blank" rel="noopener noreferrer">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M16 8a6 6 0 016 6v7h-4v-7a2 2 0 00-2-2 2 2 0 00-2 2v7h-4v-7a6 6 0 016-6zM2 9h4v12H2z"/><circle cx="4" cy="4" r="2"/></svg>
            LinkedIn
          </a>
          <a className="share-btn" href={`https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`} target="_blank" rel="noopener noreferrer">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z"/></svg>
            Facebook
          </a>
          <a className="share-btn" href={`https://wa.me/?text=${encodeURIComponent(shareText + " " + shareUrl)}`} target="_blank" rel="noopener noreferrer">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
            WhatsApp
          </a>
        </div>
      </div>
      <div style={{ marginTop: "var(--space-4)" }}>
        <Button variant="ghost" block onClick={onClose}>Back to the petition</Button>
      </div>
    </div>
  );
}

// Sign panel — collects signature, inserts to Supabase, sends verification email.
function SignPanel({ data, count, open, onClose }) {
  const { Button, Field, Input, Select, Checkbox, Logo } = window.IAIGADesignSystem_db07e0;
  const { Icon } = window;
  const [step, setStep] = React.useState("form"); // form | done | error
  const [signer, setSigner] = React.useState("individual");
  const [form, setForm] = React.useState({ name: "", email: "", country: "", profession: "", org: "", orgName: "", orgUrl: "", show: true });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    if (open) { setStep("form"); setSigner("individual"); setErrors({}); setLoading(false); }
  }, [open]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape" && open) onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  async function submit(e) {
    e.preventDefault();
    const next = {};
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) next.email = "Enter a valid email address.";
    if (signer === "individual") {
      if (!form.name.trim()) next.name = "Please enter your name.";
      if (!form.country) next.country = "Select your country.";
      if (!form.profession.trim()) next.profession = "Please enter your profession.";
    } else {
      if (!form.orgName.trim()) next.orgName = "Please enter the organization name.";
      if (!form.orgUrl.trim()) next.orgUrl = "Please enter the organization's website.";
      else if (!/^(https?:\/\/)?[^\s.]+\.[^\s]{2,}$/.test(form.orgUrl.trim())) next.orgUrl = "Enter a valid website URL.";
    }
    setErrors(next);
    if (Object.keys(next).length) return;

    setLoading(true);
    const sb = window._sb;

    const countryName = data.countries.find(
      (c) => c.toLowerCase().replace(/\s/g, "-") === form.country
    ) || form.country || null;

    const row = signer === "individual"
      ? { name: form.name.trim(), email: form.email.trim(), role: form.profession.trim(),
          org: form.org.trim() || null, country: countryName, kind: "individual",
          show_name: form.show, verified: false }
      : { name: form.orgName.trim(), email: form.email.trim(), country: countryName,
          org: form.orgUrl.trim(), kind: "org", show_name: true, verified: false };

    const { error: insertErr } = await sb.from("signatures").insert(row);
    if (insertErr) {
      setErrors({ submit: "Something went wrong saving your signature. Please try again." });
      setLoading(false);
      return;
    }

    const { error: otpErr } = await sb.auth.signInWithOtp({
      email: form.email.trim(),
      options: { shouldCreateUser: true, emailRedirectTo: window.location.origin + "/verify" },
    });

    setLoading(false);
    if (otpErr) {
      setErrors({ submit: "Could not send verification email. Please try again." });
      return;
    }

    setStep("done");
  }

  return (
    <div className="modal" role="dialog" aria-modal="true" aria-label="Sign the petition">
      <div className="modal__scrim" onClick={onClose}></div>
      <div className="modal__panel">
        <button className="modal__close" onClick={onClose} aria-label="Close">×</button>

        {step === "form" && (
          <form className="sign" onSubmit={submit} noValidate>
            <div className="sign__head">
              <Logo variant="gem" src="assets/mark-gem.svg" height={40} />
              <div>
                <h3 className="sign__title">Add your signature</h3>
                <p className="sign__sub">Join {(count ?? data.signatureCount).toLocaleString()} people calling for global AI governance.</p>
              </div>
            </div>
            <div className="sign__as">
              <span className="sign__as-label">Signing as</span>
              <div className="sign__seg" role="tablist">
                <button type="button" role="tab" aria-selected={signer === "individual"}
                  className={"sign__seg-btn" + (signer === "individual" ? " is-active" : "")}
                  onClick={() => { setSigner("individual"); setErrors({}); }}>Individual</button>
                <button type="button" role="tab" aria-selected={signer === "organization"}
                  className={"sign__seg-btn" + (signer === "organization" ? " is-active" : "")}
                  onClick={() => { setSigner("organization"); setErrors({}); }}>Organization</button>
              </div>
            </div>

            {signer === "individual" ? (
              <div className="sign__grid">
                <Field label="Full name" required error={errors.name}>
                  <Input value={form.name} onChange={set("name")} placeholder="Jane Okonkwo" autoFocus />
                </Field>
                <Field label="Country" required error={errors.country}>
                  <Select value={form.country} onChange={set("country")}>
                    <option value="" disabled>Choose your country…</option>
                    {data.countries.map((c) => (
                      <option key={c} value={c.toLowerCase().replace(/\s/g, "-")}>{c}</option>
                    ))}
                  </Select>
                </Field>
                <div className="sign__span">
                  <Field label="Email" required error={errors.email} help="We'll send a one-click verification link. Never shared.">
                    <Input type="email" value={form.email} onChange={set("email")} placeholder="you@example.org" />
                  </Field>
                </div>
                <Field label="Profession" required error={errors.profession}>
                  <Input value={form.profession} onChange={set("profession")} placeholder="e.g. Teacher, Engineer" />
                </Field>
                <Field label="Organization" optional>
                  <Input value={form.org} onChange={set("org")} placeholder="e.g. UN, Red Cross" />
                </Field>
              </div>
            ) : (
              <div className="sign__grid">
                <div className="sign__span">
                  <Field label="Organization name" required error={errors.orgName}>
                    <Input value={form.orgName} onChange={set("orgName")} placeholder="e.g. Nonlinear" autoFocus />
                  </Field>
                </div>
                <div className="sign__span">
                  <Field label="Website" required error={errors.orgUrl} help="We'll link to this and show your logo on the wall.">
                    <Input value={form.orgUrl} onChange={set("orgUrl")} placeholder="https://your-org.org" />
                  </Field>
                </div>
                <div className="sign__span">
                  <Field label="Email" required error={errors.email} help="We'll send a one-click verification link. Never shared.">
                    <Input type="email" value={form.email} onChange={set("email")} placeholder="contact@org.org" />
                  </Field>
                </div>
                <div className="sign__span">
                  <Field label="Country" optional>
                    <Select value={form.country} onChange={set("country")}>
                      <option value="">Choose a country (optional)…</option>
                      {data.countries.map((c) => (
                        <option key={c} value={c.toLowerCase().replace(/\s/g, "-")}>{c}</option>
                      ))}
                    </Select>
                  </Field>
                </div>
              </div>
            )}

            {signer === "individual" && (
              <Checkbox checked={form.show} onChange={(e) => setForm((f) => ({ ...f, show: e.target.checked }))}>
                Display my name on the public signatory wall.
              </Checkbox>
            )}

            <p className="sign__consent">
              {signer === "organization" ? (
                <React.Fragment>
                  By signing on behalf of this organization, I confirm I am authorised to do so and that
                  the organization supports the petition described on this website.{" "}
                  The organization's name and country will be shown publicly on the signatory wall.
                </React.Fragment>
              ) : (
                <React.Fragment>
                  By signing, I acknowledge that I am supporting the petition described on this website.
                  I understand that the information submitted above will be made public, except for my email
                  which will remain confidential and used solely for IAIGA communications.
                </React.Fragment>
              )}
            </p>

            {errors.submit && (
              <p style={{ color: "var(--danger)", fontSize: "13px", marginBottom: "var(--space-3)" }}>{errors.submit}</p>
            )}

            <Button variant="gold" size="lg" block type="submit" disabled={loading}
              iconRight={loading ? null : <Icon.ArrowRight />}>
              {loading ? "Submitting…" : "Sign the petition"}
            </Button>
            <p className="sign__fine">
              See our <a href="terms">terms of use</a> and <a href="privacy">privacy policy</a>.
            </p>
          </form>
        )}

        {step === "done" && <SignDone email={form.email} onClose={onClose} />}
      </div>
    </div>
  );
}
window.SignPanel = SignPanel;
