/* global React, Star, Icon */
const { useState: useStateD } = React;

const PRESETS = [25, 50, 100, 250];

/* Replace with your deployed Worker URL */
const DONATE_WORKER_URL = "YOUR_DONATE_WORKER_URL";

function DonatePage({ navigate }) {
  const [amt, setAmt] = useStateD("50");
  const [form, setForm] = useStateD({ name: "", email: "" });
  const [optOut, setOptOut] = useStateD(false);
  const [submitting, setSubmitting] = useStateD(false);
  const [error, setError] = useStateD(null);

  const amtNum = parseFloat(amt) || 0;
  const valid = form.name.trim().length > 0 && form.email.includes("@") && amtNum >= 1;
  const up = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const handleSubmit = async () => {
    if (!valid || submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch(DONATE_WORKER_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name.trim(),
          email: form.email.trim(),
          amount: amtNum,
          optOut
        })
      });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        throw new Error(data.error || "Something went wrong");
      }
    } catch (e) {
      setError(e.message);
      setSubmitting(false);
    }
  };

  return (
    <div className="wrap" style={{ paddingBlock: "clamp(36px,6vw,72px)", maxWidth: 1040 }}>

      {/* Header */}
      <div className="row between" style={{ flexWrap: "wrap", gap: 14, marginBottom: 28, alignItems: "flex-end" }}>
        <div>
          <span className="kicker">
            <Icon name="heart" size={13} color="var(--coral)" /> 501(c)(3) non-profit · Tax-deductible gift
          </span>
          <h1 style={{ fontSize: "clamp(30px,4.5vw,48px)", marginTop: 10 }}>Support FTW</h1>
        </div>
        <span className="tag tag--teal" style={{ alignSelf: "center" }}>
          <Icon name="shield" size={13} stroke={2.4} /> Secure · Processed by Square
        </span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 24, alignItems: "start" }}>

        {/* ── Form column ── */}
        <div style={{ display: "grid", gap: 20 }}>

          {/* Amount picker */}
          <div className="card" style={{ padding: "clamp(22px,4vw,30px)" }}>
            <h3 style={{ fontSize: 19, marginBottom: 6 }}>Choose an amount</h3>
            <p className="muted" style={{ fontSize: 14, marginBottom: 18 }}>
              Every dollar goes directly toward keeping the program accessible to every kid who wants to be here.
            </p>

            <div className="row gap-8" style={{ flexWrap: "wrap", marginBottom: 16 }}>
              {PRESETS.map((p) =>
              <button key={p} onClick={() => setAmt(String(p))}
              className="btn btn--sm"
              style={{
                background: amtNum === p ? "var(--gold)" : "var(--white)",
                border: amtNum === p ? "var(--bd-ink)" : "2px solid var(--paper-2)",
                boxShadow: amtNum === p ? "var(--shadow-sm)" : "none",
                fontFamily: "var(--display)", fontWeight: 700, fontSize: 15
              }}>
                  ${p}
                </button>
              )}
            </div>

            <div className="field">
              <label>Or enter a custom amount</label>
              <div style={{ position: "relative" }}>
                <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)",
                  fontFamily: "var(--display)", fontWeight: 600, fontSize: 20, color: "var(--ink-soft)" }}>$</span>
                <input className="input"
                value={amt}
                onChange={(e) => setAmt(e.target.value.replace(/[^\d.]/g, ""))}
                inputMode="decimal"
                placeholder="0"
                style={{ paddingLeft: 30, fontFamily: "var(--display)", fontWeight: 700, fontSize: 20 }} />
              </div>
            </div>
          </div>

          {/* Contact info */}
          <div className="card" style={{ padding: "clamp(22px,4vw,30px)" }}>
            <h3 style={{ fontSize: 19, marginBottom: 16 }}>Your info</h3>

            <div className="field" style={{ marginBottom: 14 }}>
              <label>Full name</label>
              <input className="input" value={form.name} onChange={up("name")} placeholder="Jane Smith" />
            </div>

            <div className="field" style={{ marginBottom: 22 }}>
              <label>Email address</label>
              <input className="input" type="email" value={form.email} onChange={up("email")} placeholder="jane@example.com" />
              <div className="muted" style={{ fontSize: 13, marginTop: 5 }}>
                Your Square receipt will be sent here.
              </div>
            </div>

            <label style={{ display: "flex", gap: 10, alignItems: "flex-start", cursor: "pointer",
              padding: "14px 16px", borderRadius: "var(--r-md)",
              border: "2px solid var(--paper-2)", background: "var(--paper)" }}>
              <input type="checkbox"
              checked={optOut}
              onChange={(e) => setOptOut(e.target.checked)}
              style={{ marginTop: 2, width: 16, height: 16, accentColor: "var(--gold)", flexShrink: 0 }} />
              <span style={{ fontSize: 14, color: "var(--ink-soft)", lineHeight: 1.5 }}>
                Please exclude me from the FTW mailing list.
                <span style={{ display: "block", fontSize: 12.5, marginTop: 2, color: "var(--ink-soft)", opacity: .75 }}>
                  By default, donors get occasional program updates. Uncheck to opt in, check to opt out.
                </span>
              </span>
            </label>

            {error &&
            <div style={{ marginTop: 16, padding: "12px 16px", background: "var(--coral-tint)",
              border: "var(--bd-ink)", borderRadius: "var(--r-md)", fontSize: 14 }}>
                <b>Something went wrong:</b> {error}. Please try again or{" "}
                <button onClick={() => navigate("contact")}
              style={{ background: "none", border: "none", cursor: "pointer", textDecoration: "underline",
                fontFamily: "inherit", fontSize: "inherit", padding: 0 }}>
                  contact us
                </button>.
              </div>
            }

            <button
              className="btn btn--gold btn--lg"
              disabled={!valid || submitting}
              onClick={handleSubmit}
              style={{ width: "100%", justifyContent: "center", marginTop: 24 }}>
              {submitting ?
              "Redirecting to Square…" :
              <>
                    <Icon name="heart" size={18} color="var(--ink)" />
                    Donate {amtNum >= 1 ? `$${amtNum % 1 === 0 ? amtNum : amtNum.toFixed(2)}` : "—"}
                    <Icon name="arrow" size={16} stroke={2.6} />
                  </>}
            </button>

            <div style={{ display: "flex", justifyContent: "center", gap: 6, marginTop: 14,
              color: "var(--ink-soft)", fontSize: 13 }}>
              <Icon name="shield" size={15} /> Processed securely by Square. Receipt emailed automatically.
            </div>
          </div>
        </div>

        {/* ── Sidebar ── */}
        <div style={{ display: "grid", gap: 16, position: "sticky", top: 90 }}>

          {/* 501c3 */}
          <div className="card" style={{ padding: 22 }}>
            <div style={{ display: "flex", gap: 8, alignItems: "center",
              fontFamily: "var(--display)", fontWeight: 600, fontSize: 15, marginBottom: 8 }}>
              <Icon name="shield" size={16} color="var(--teal)" /> Tax-deductible
            </div>
            <p className="muted" style={{ fontSize: 13.5 }}>
              Foothill Theatre Workshop is a registered 501(c)(3) non-profit organization.
              Donations are tax-deductible to the extent allowed by law.
              Keep your Square receipt for your records.
            </p>
          </div>

          {/* Mission */}
          <div className="card" style={{ padding: 22, background: "var(--teal-tint, #e8f4f2)" }}>
            <div style={{ display: "flex", gap: 8, alignItems: "center",
              fontFamily: "var(--display)", fontWeight: 600, fontSize: 15, marginBottom: 8 }}>
              <Star size={16} fill="var(--gold)" /> 20+ years on stage
            </div>
            <p className="muted" style={{ fontSize: 13.5 }}>Since 2000, FTW has given kids in the San Gabriel Valley their first taste of the spotlight. Tuition is kept low on purpose — and audience support and donations make that possible.



            </p>
          </div>

        </div>
      </div>
    </div>);

}

Object.assign(window, { DonatePage });