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

/* Demo family data — in production this comes from Airtable via webhook
   keyed on the logged-in parent's email. */
const DEMO_FAMILY = {
  parent: "The Reyes family",
  students: [
    { id: "ava", name: "Ava Reyes", note: "Disney's Frozen · Mainstage", tuition: 600, paid: 50 },
    { id: "milo", name: "Milo Reyes", note: "Disney's Frozen · Ensemble", tuition: 600, paid: 50 },
  ],
};
const DUE_DATE = "July 13, 2026";

function PaymentPage({ navigate }) {
  const family = DEMO_FAMILY;
  const totalTuition = family.students.reduce((a, s) => a + s.tuition, 0);
  const totalPaid = family.students.reduce((a, s) => a + s.paid, 0);
  const balance = Math.max(0, totalTuition - totalPaid);
  const pctPaid = totalTuition ? Math.round((totalPaid / totalTuition) * 100) : 0;

  const [amt, setAmt] = useStateP(String(balance));
  const [card, setCard] = useStateP({ name: "", num: "", exp: "", cvc: "", zip: "" });
  const [paying, setPaying] = useStateP(false);
  const [done, setDone] = useStateP(false);
  const up = (k) => (e) => setCard({ ...card, [k]: e.target.value });

  const fmtNum = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(.{4})/g, "$1 ").trim();
  const amtNum = Number(amt) || 0;
  const valid = card.name && card.num.replace(/\s/g, "").length >= 15 && card.exp.length >= 4 && card.cvc.length >= 3 && amtNum > 0;

  const pay = () => {
    setPaying(true);
    setTimeout(() => { setPaying(false); setDone(true); window.scrollTo({ top: 0, behavior: "smooth" }); }, 1400);
  };

  if (done) {
    const newBalance = Math.max(0, balance - amtNum);
    return (
      <div className="wrap" style={{ paddingBlock: "clamp(48px,8vw,90px)", maxWidth: 620 }}>
        <div className="card pop" style={{ padding: "clamp(28px,5vw,52px)", textAlign: "center" }}>
          <div style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--mint)", border: "var(--bd-ink)",
            display: "grid", placeItems: "center", margin: "0 auto 20px", boxShadow: "var(--shadow-sm)" }}>
            <Icon name="check" size={38} stroke={3} />
          </div>
          <h1 style={{ fontSize: "clamp(28px,4.5vw,42px)" }}>Payment received!</h1>
          <p className="muted" style={{ fontSize: 17, marginTop: 12, maxWidth: 460, margin: "12px auto 0" }}>
            We've charged <b style={{ color: "var(--ink)" }}>${amtNum.toFixed(2)}</b> via Square and emailed your receipt.
            {newBalance === 0
              ? " You're all paid up — see you on stage! 🎉"
              : <> Remaining family balance: <b style={{ color: "var(--ink)" }}>${newBalance.toFixed(2)}</b>, due by {DUE_DATE}.</>}
          </p>
          <div className="row gap-12" style={{ justifyContent: "center", marginTop: 26, flexWrap: "wrap" }}>
            <button className="btn btn--gold btn--lg" onClick={() => navigate("hub")}>Go to Family Hub</button>
            <button className="btn btn--lg" onClick={() => navigate("home")}>Back home</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="wrap" style={{ paddingBlock: "clamp(36px,6vw,72px)", maxWidth: 1040 }}>
      <div className="row between" style={{ flexWrap: "wrap", gap: 14, marginBottom: 26, alignItems: "flex-end" }}>
        <div>
          <span className="kicker"><Star size={13} fill="var(--gold-deep)" /> Secure tuition payment</span>
          <h1 style={{ fontSize: "clamp(30px,4.5vw,48px)", marginTop: 10 }}>Make a payment</h1>
        </div>
        {balance > 0 && (
          <span className="tag tag--coral" style={{ alignSelf: "center" }}>
            <Icon name="clock" size={13} stroke={2.4} /> Balance due in full by {DUE_DATE}
          </span>
        )}
      </div>

      <div className="pay-grid" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 24, alignItems: "start" }}>
        {/* Form */}
        <div style={{ display: "grid", gap: 20 }}>
          {/* Family balance */}
          <div className="card" style={{ padding: "clamp(22px,4vw,30px)" }}>
            <div className="row between" style={{ marginBottom: 6, alignItems: "flex-end", flexWrap: "wrap", gap: 8 }}>
              <h3 style={{ fontSize: 19 }}>{family.parent}</h3>
              <span className="muted" style={{ fontSize: 13 }}>{family.students.length} students · {pctPaid}% paid</span>
            </div>
            <div style={{ height: 12, borderRadius: 999, background: "var(--paper-2)", border: "var(--bd-ink)",
              overflow: "hidden", marginBottom: 18 }}>
              <div style={{ width: pctPaid + "%", height: "100%", background: "var(--gold)", transition: "width .3s" }} />
            </div>
            <div style={{ display: "grid", gap: 10 }}>
              {family.students.map(s => {
                const bal = Math.max(0, s.tuition - s.paid);
                const paidUp = bal === 0;
                return (
                  <div key={s.id} className="row between" style={{ padding: "12px 14px",
                    border: "2px solid var(--paper-2)", borderRadius: "var(--r-md)", gap: 12, flexWrap: "wrap" }}>
                    <div>
                      <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 16 }}>{s.name}</div>
                      <div className="muted" style={{ fontSize: 13 }}>{s.note}</div>
                    </div>
                    <div style={{ textAlign: "right" }}>
                      <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 17,
                        color: paidUp ? "var(--mint)" : "var(--ink)" }}>
                        {paidUp ? "Paid in full ✓" : `$${bal} due`}
                      </div>
                      <div className="muted" style={{ fontSize: 12.5 }}>${s.paid} of ${s.tuition} paid</div>
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="row between" style={{ marginTop: 18, paddingTop: 14, borderTop: "2px dashed rgba(33,29,23,.18)" }}>
              <span style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 17 }}>Family balance</span>
              <span style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 28 }}>${balance}</span>
            </div>
          </div>

          {/* Amount + card */}
          <div className="card" style={{ padding: "clamp(22px,4vw,30px)" }}>
            <h3 style={{ fontSize: 19, marginBottom: 6 }}>How much would you like to pay?</h3>
            <p className="muted" style={{ fontSize: 14, marginBottom: 16 }}>Pay any amount toward your family balance.</p>
            <div className="row gap-8" style={{ flexWrap: "wrap", marginBottom: 22 }}>
              {[["Full balance", balance], ["Half", Math.round(balance / 2)], ["Installment", 275], ["Deposit", 50]]
                .filter(([, v]) => v > 0 && v <= balance).map(([l, v]) => (
                <button key={l} className="btn btn--sm" onClick={() => setAmt(String(v))}
                  style={{ background: amtNum === v ? "var(--gold)" : "var(--white)" }}>
                  {l} · ${v}
                </button>
              ))}
              <div className="field" style={{ flex: "1 1 140px", minWidth: 130 }}>
                <div style={{ position: "relative" }}>
                  <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)",
                    fontFamily: "var(--display)", fontWeight: 600, fontSize: 18 }}>$</span>
                  <input className="input" value={amt} onChange={(e) => setAmt(e.target.value.replace(/[^\d.]/g, ""))}
                    inputMode="decimal" style={{ paddingLeft: 28, fontFamily: "var(--display)", fontWeight: 600, fontSize: 18 }} />
                </div>
              </div>
            </div>

            <hr className="divider" style={{ opacity: .12, marginBottom: 22 }} />

            <h3 style={{ fontSize: 19, marginBottom: 16 }}>Card details</h3>
            <div className="field" style={{ marginBottom: 14 }}><label>Name on card</label>
              <input className="input" value={card.name} onChange={up("name")} placeholder="Jordan Reyes" /></div>
            <div className="field" style={{ marginBottom: 14 }}><label>Card number</label>
              <div style={{ position: "relative" }}>
                <input className="input" value={card.num} onChange={(e) => setCard({ ...card, num: fmtNum(e.target.value) })}
                  placeholder="4242 4242 4242 4242" inputMode="numeric" style={{ paddingRight: 50 }} />
                <Icon name="card" size={22} color="var(--ink-soft)"
                  style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)" }} />
              </div></div>
            <div className="form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
              <div className="field"><label>Expiry</label>
                <input className="input" value={card.exp}
                  onChange={(e) => setCard({ ...card, exp: e.target.value.replace(/\D/g, "").slice(0, 4).replace(/(\d{2})(\d)/, "$1/$2") })}
                  placeholder="MM/YY" inputMode="numeric" /></div>
              <div className="field"><label>CVC</label>
                <input className="input" value={card.cvc} onChange={(e) => setCard({ ...card, cvc: e.target.value.replace(/\D/g, "").slice(0, 4) })}
                  placeholder="123" inputMode="numeric" /></div>
              <div className="field"><label>ZIP</label>
                <input className="input" value={card.zip} onChange={up("zip")} placeholder="91767" inputMode="numeric" /></div>
            </div>

            <button className="btn btn--gold btn--lg" disabled={!valid || paying} onClick={pay}
              style={{ width: "100%", justifyContent: "center", marginTop: 24 }}>
              {paying ? "Processing…" : <>Pay ${amtNum.toFixed(2)} with Square <Icon name="arrow" size={18} stroke={2.6} /></>}
            </button>
            <div className="row gap-8 center" style={{ justifyContent: "center", marginTop: 14, color: "var(--ink-soft)", fontSize: 13 }}>
              <Icon name="shield" size={15} /> Processed by Square. Receipt is emailed instantly.
            </div>
          </div>
        </div>

        {/* Sidebar */}
        <div style={{ display: "grid", gap: 16, position: "sticky", top: 90 }}>
          <div className="card" style={{ padding: 22, background: "var(--paper-2)" }}>
            <h3 style={{ fontSize: 18, marginBottom: 14 }}>Tuition rates</h3>
            {[
              ["One show", "$600"],
              ["Both shows", "$800"],
              ["SAE student", "Sponsored"],
              ["Scholarship", "Sponsored"],
            ].map(([k, v]) => (
              <div key={k} className="row between" style={{ padding: "7px 0", fontSize: 14.5 }}>
                <span className="muted">{k}</span>
                <span style={{ fontFamily: "var(--display)", fontWeight: 600 }}>{v}</span>
              </div>
            ))}
            <div className="muted" style={{ fontSize: 12.5, marginTop: 10, paddingTop: 10, borderTop: "1.5px dashed rgba(33,29,23,.2)" }}>
              Tuition for siblings is rolled into one family balance — pay it down however works for you.
            </div>
          </div>

          <div className="card" style={{ padding: 22, background: "var(--white)" }}>
            <div className="row gap-8" style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 16, marginBottom: 6 }}>
              <Icon name="heart" size={18} color="var(--coral)" /> Need a hand?
            </div>
            <p className="muted" style={{ fontSize: 13.5 }}>
              Need-based scholarships are available — no student is turned away for cost.
              Reply to your weekly balance email or message us, and we'll set one up quietly.
            </p>
          </div>

          <div className="card" style={{ padding: 22, background: "var(--gold-tint)" }}>
            <div className="row gap-8" style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 16, marginBottom: 6 }}>
              <Icon name="bell" size={18} /> Weekly reminder
            </div>
            <p className="muted" style={{ fontSize: 13.5 }}>
              You'll get a friendly email each week with your current balance and a link back to this page.
              Unsubscribe anytime in your Family Hub.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PaymentPage, DEMO_FAMILY, DUE_DATE });
