/* =========================================================
   RENFECHT — Registration form
   ========================================================= */

function RegisterPage({ onNavigate }) {
  useReveal();
  const v = useValues();

  const initialGear = Object.fromEntries(v.gear.map(g => [g.key, false]));

  const [form, setForm] = React.useState({
    firstName: "", lastName: "", pronouns: "",
    email: "", phone: "", emergencyName: "", emergencyPhone: "",
    divisions: [], rating: "", experience: v.experienceLevels[2],
    club: "", clubCity: "", captainEmail: "",
    gearInspection: v.inspectionSlots[0],
    gearChecklist: initialGear,
    waiverAck: false, codeAck: false, photoAck: false,
    shirtSize: "M", swag: [], donateAmount: 0,
    paymentMethod: "card",
    notes: "",
  });
  const [submitted, setSubmitted] = React.useState(false);

  const set = (k, val) => setForm(f => ({ ...f, [k]: val }));
  const toggleArr = (k, val) => setForm(f => ({ ...f, [k]: f[k].includes(val) ? f[k].filter(x => x !== val) : [...f[k], val] }));

  const fee = form.divisions.length * v.event.feePerList;
  const swagMap = Object.fromEntries(v.swag.map(s => [s.name, s.price]));
  const swagTotal = form.swag.reduce((s, x) => s + (swagMap[x] || 0), 0);
  const total = fee + swagTotal + Number(form.donateAmount || 0);

  const required = form.firstName && form.lastName && form.email && form.divisions.length && form.waiverAck && form.codeAck;

  if (submitted) {
    return (
      <main>
        <PageBanner eyebrow="ENTRY RECEIVED" title="Welcome to the Lists" lead="Your entry has been logged. A confirmation will arrive by post within the hour." />
        <section className="section">
          <div className="wrap" style={{ maxWidth: 720, textAlign: "center" }}>
            <Crest size={120} />
            <p className="lede" style={{ marginTop: 18 }}>You are entered in <strong>{form.divisions.join(", ")}</strong>. Payment of <strong>${total}</strong> has been recorded.</p>
            <div className="rule" style={{ marginTop: 32 }} />
            <p>Inspect your gear before Friday. Bring your steel.</p>
            <div style={{ marginTop: 28, display: "flex", gap: 14, justifyContent: "center", flexWrap: "wrap" }}>
              <a href="#home" className="btn btn-ghost" onClick={(e) => { e.preventDefault(); onNavigate("home"); }}>Back to Home</a>
              <a href="#event" className="btn btn-accent" onClick={(e) => { e.preventDefault(); onNavigate("event"); }}>Event Details</a>
            </div>
          </div>
        </section>
      </main>
    );
  }

  return (
    <main>
      <PageBanner
        eyebrow="ENTRY"
        title="Enter the Lists"
        lead={`One form. All three lists. Complete before ${v.event.deadline} to secure your slot — entries close hard at capacity.`}
      />

      <section className="section-tight">
        <div className="wrap reg-grid" style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: "var(--space-7)", alignItems: "start" }}>
          <form onSubmit={(e) => { e.preventDefault(); setSubmitted(true); window.scrollTo({ top: 0, behavior: "smooth" }); }}>

            <FormSection num="I" title="Identity" sub="Name as you wish it announced in the ring.">
              <div className="row-2">
                <Field label="First name *"><input className="input" required value={form.firstName} onChange={e => set("firstName", e.target.value)} /></Field>
                <Field label="Surname *"><input className="input" required value={form.lastName} onChange={e => set("lastName", e.target.value)} /></Field>
              </div>
              <Field label="Pronouns (optional)" hint="Used by heralds when calling bouts.">
                <input className="input" value={form.pronouns} onChange={e => set("pronouns", e.target.value)} placeholder="she/her, he/him, they/them…" />
              </Field>
            </FormSection>

            <FormSection num="II" title="Contact" sub="We will use this to send your bracket draw and gear-inspection slot.">
              <div className="row-2">
                <Field label="Email *"><input className="input" type="email" required value={form.email} onChange={e => set("email", e.target.value)} /></Field>
                <Field label="Phone"><input className="input" type="tel" value={form.phone} onChange={e => set("phone", e.target.value)} placeholder="+1 (___) ___-____" /></Field>
              </div>
              <div className="row-2">
                <Field label="Emergency contact — name"><input className="input" value={form.emergencyName} onChange={e => set("emergencyName", e.target.value)} /></Field>
                <Field label="Emergency contact — phone"><input className="input" type="tel" value={form.emergencyPhone} onChange={e => set("emergencyPhone", e.target.value)} /></Field>
              </div>
            </FormSection>

            <FormSection num="III" title="Division(s)" sub="Enter as many lists as you wish. Each is fenced separately; you may compete in all three.">
              <div className="div-grid">
                {v.divisions.map(d => {
                  const on = form.divisions.includes(d.title);
                  return (
                    <button type="button" key={d.id}
                      className={"div-pick " + (on ? "is-on" : "")}
                      onClick={() => toggleArr("divisions", d.title)}>
                      <div className="div-pick-head">
                        <CrossedSwordsIcon size={24} />
                        <span className="pill">{on ? "ENTERED" : `$${d.fee}`}</span>
                      </div>
                      <div className="div-pick-name">{d.title}</div>
                      <div className="eyebrow">{d.sub}</div>
                    </button>
                  );
                })}
              </div>
              <div className="row-2" style={{ marginTop: 24 }}>
                <Field label="HEMA Ratings ID (if any)" hint="Used for pool seeding. Leave blank if unrated.">
                  <input className="input" value={form.rating} onChange={e => set("rating", e.target.value)} placeholder="e.g. 1842" />
                </Field>
                <Field label="Self-reported experience">
                  <select className="select" value={form.experience} onChange={e => set("experience", e.target.value)}>
                    {v.experienceLevels.map(l => <option key={l}>{l}</option>)}
                  </select>
                </Field>
              </div>
            </FormSection>

            <FormSection num="IV" title="Club Affiliation" sub="Independent fighters welcome — leave blank if unaffiliated.">
              <div className="row-2">
                <Field label="Club / school"><input className="input" value={form.club} onChange={e => set("club", e.target.value)} placeholder="e.g. Houston Sword & Pen" /></Field>
                <Field label="City"><input className="input" value={form.clubCity} onChange={e => set("clubCity", e.target.value)} /></Field>
              </div>
              <Field label="Captain's email (optional)" hint="If your club is sending more than one fighter, we'll coordinate inspection slots together.">
                <input className="input" type="email" value={form.captainEmail} onChange={e => set("captainEmail", e.target.value)} />
              </Field>
            </FormSection>

            <FormSection num="V" title="Gear" sub="Tick what you'll bring. Anything unchecked, we'll provide from the loaner pool — subject to availability.">
              <Field label="Inspection slot">
                <div className="radio-row">
                  {v.inspectionSlots.map(t => (
                    <label key={t} className={"radio-pill " + (form.gearInspection === t ? "is-on" : "")}>
                      <input type="radio" name="insp" value={t} checked={form.gearInspection === t} onChange={() => set("gearInspection", t)} />
                      <span>{t}</span>
                    </label>
                  ))}
                </div>
              </Field>

              <div className="field-label" style={{ marginTop: 24 }}>Gear checklist</div>
              <div className="gear-grid">
                {v.gear.map(g => (
                  <label key={g.key} className="check">
                    <input type="checkbox" checked={form.gearChecklist[g.key]}
                      onChange={() => set("gearChecklist", { ...form.gearChecklist, [g.key]: !form.gearChecklist[g.key] })} />
                    <span><strong>{g.name}</strong><br/><span style={{ color: "var(--ink-mute)", fontSize: "0.88rem" }}>{g.spec}</span></span>
                  </label>
                ))}
              </div>
            </FormSection>

            <FormSection num="VI" title="Waiver, Code, Likeness">
              <div className="waiver-box">
                <p className="dropcap" style={{ fontSize: "0.95rem", color: "var(--ink-soft)" }}>
                  HEMA is a full-contact combat sport. Injuries — including bruises, sprains, fractures, and concussions — are possible despite the best gear and intentions. By entering, you affirm you have read the Combatant Agreement, that you are physically fit to compete, and that you accept the risks of the art.
                </p>
              </div>
              <label className="check"><input type="checkbox" required checked={form.waiverAck} onChange={() => set("waiverAck", !form.waiverAck)} /><span>I have read and agree to the <a href="#" onClick={e => e.preventDefault()}>Combatant Waiver</a>. *</span></label>
              <label className="check"><input type="checkbox" required checked={form.codeAck} onChange={() => set("codeAck", !form.codeAck)} /><span>I have read and agree to the <a href="#" onClick={e => e.preventDefault()}>Code of Conduct</a>. *</span></label>
              <label className="check"><input type="checkbox" checked={form.photoAck} onChange={() => set("photoAck", !form.photoAck)} /><span>I consent to my likeness being used in event footage, photography, and promotional material.</span></label>
            </FormSection>

            <FormSection num="VII" title="Swag & Support" sub="Optional. All proceeds support the marshals' fund.">
              <div className="row-2">
                <Field label="T-shirt size">
                  <select className="select" value={form.shirtSize} onChange={e => set("shirtSize", e.target.value)}>
                    {v.shirtSizes.map(s => <option key={s}>{s}</option>)}
                  </select>
                </Field>
                <Field label="Donate to the marshals' fund" hint="Marshals are volunteers. We feed them with this.">
                  <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                    {v.donationAmounts.map(a => (
                      <label key={a} className={"radio-pill " + (Number(form.donateAmount) === a ? "is-on" : "")}>
                        <input type="radio" name="donate" checked={Number(form.donateAmount) === a} onChange={() => set("donateAmount", a)} />
                        <span>${a}</span>
                      </label>
                    ))}
                  </div>
                </Field>
              </div>
              <div className="field-label" style={{ marginTop: 18 }}>Add to your kit</div>
              <div className="swag-grid">
                {v.swag.map(item => {
                  const on = form.swag.includes(item.name);
                  return (
                    <button type="button" key={item.name} className={"swag-card " + (on ? "is-on" : "")} onClick={() => toggleArr("swag", item.name)}>
                      <Placeholder label={item.name.toUpperCase()} ratio="1 / 1" style={{ border: 0 }} />
                      <div style={{ padding: "10px 12px 12px" }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                          <span style={{ fontFamily: "var(--font-display)", letterSpacing: "0.04em", fontSize: "0.95rem" }}>{item.name}</span>
                          <span className="mono" style={{ fontSize: "0.78rem", color: "var(--accent)" }}>${item.price}</span>
                        </div>
                        <div className="eyebrow" style={{ marginTop: 4 }}>{on ? "ADDED" : "ADD →"}</div>
                      </div>
                    </button>
                  );
                })}
              </div>
            </FormSection>

            <FormSection num="VIII" title="Payment">
              <Field label="Payment method">
                <div className="radio-row">
                  {[["card", "Card"], ["check", "Check / Mail"], ["cash", "Cash at gate"]].map(([val, l]) => (
                    <label key={val} className={"radio-pill " + (form.paymentMethod === val ? "is-on" : "")}>
                      <input type="radio" name="pm" checked={form.paymentMethod === val} onChange={() => set("paymentMethod", val)} />
                      <span>{l}</span>
                    </label>
                  ))}
                </div>
              </Field>

              {form.paymentMethod === "card" && (
                <div>
                  <Field label="Card number"><input className="input mono" placeholder="•••• •••• •••• ••••" /></Field>
                  <div className="row-3">
                    <Field label="MM / YY"><input className="input mono" placeholder="11 / 28" /></Field>
                    <Field label="CVC"><input className="input mono" placeholder="•••" /></Field>
                    <Field label="ZIP"><input className="input mono" placeholder="77363" /></Field>
                  </div>
                </div>
              )}
              {form.paymentMethod === "check" && (
                <p style={{ color: "var(--ink-soft)" }}>Mail check, made out to <em>RenFecht Tournament Co.</em>, to {v.event.boxAddress}. Must clear by {v.event.checkBy}.</p>
              )}
              {form.paymentMethod === "cash" && (
                <p style={{ color: "var(--ink-soft)" }}>Pay at gate Friday between 14:00–18:00. Bring exact change where possible. Slot is held pending payment receipt.</p>
              )}

              <Field label="Anything we should know?" hint="Dietary needs, accessibility, anything.">
                <textarea className="textarea" value={form.notes} onChange={e => set("notes", e.target.value)} />
              </Field>
            </FormSection>

            <div className="rule-double" />
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 18 }}>
              <div className="mono" style={{ fontSize: "0.85rem", color: "var(--ink-mute)" }}>
                * required · entries close {v.event.deadlineFull.toUpperCase()}
              </div>
              <button type="submit" className="btn btn-accent" disabled={!required} style={{ opacity: required ? 1 : 0.4, cursor: required ? "pointer" : "not-allowed" }}>
                Submit Entry · ${total} →
              </button>
            </div>
          </form>

          <SummaryCard form={form} swagMap={swagMap} total={total} />
        </div>
        <style>{`@media (max-width: 960px) { .reg-grid { grid-template-columns: 1fr !important; } }`}</style>
      </section>

      <FormStyles />
    </main>
  );
}

function FormSection({ num, title, sub, children }) {
  return (
    <section className="form-sect reveal">
      <div className="form-sect-head">
        <div className="form-sect-num">{num}</div>
        <div>
          <h3 style={{ textTransform: "none", letterSpacing: "0.02em", fontSize: "var(--scale-6)" }}>{title}</h3>
          {sub && <p style={{ color: "var(--ink-mute)", fontStyle: "italic", marginTop: 4, fontSize: "1rem" }}>{sub}</p>}
        </div>
      </div>
      <div className="form-sect-body">{children}</div>
    </section>
  );
}

function Field({ label, hint, children }) {
  return (
    <label className="field">
      <span className="field-label">{label}</span>
      {children}
      {hint && <span className="field-hint">{hint}</span>}
    </label>
  );
}

function SummaryCard({ form, swagMap, total }) {
  const v = useValues();
  return (
    <aside style={{ position: "sticky", top: 96 }}>
      <div className="frame frame--ornate">
        <CornerDots />
        <div className="eyebrow" style={{ color: "var(--accent)" }}>YOUR ENTRY</div>
        <div className="rule" style={{ margin: "12px 0" }} />

        <div className="sum-row">
          <span>Combatant</span>
          <span style={{ fontFamily: "var(--font-display)", letterSpacing: "0.04em" }}>
            {form.firstName || form.lastName ? `${form.firstName} ${form.lastName}`.trim() : <em style={{ color: "var(--ink-mute)" }}>name…</em>}
          </span>
        </div>
        <div className="sum-row">
          <span>Club</span>
          <span>{form.club || <em style={{ color: "var(--ink-mute)" }}>—</em>}</span>
        </div>

        <div className="rule" />
        <div className="eyebrow" style={{ marginBottom: 8 }}>LISTS ENTERED</div>
        {form.divisions.length === 0 ? (
          <div style={{ color: "var(--ink-mute)", fontStyle: "italic", fontSize: "0.95rem" }}>None yet — pick at least one above.</div>
        ) : (
          <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
            {form.divisions.map(d => (
              <li key={d} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "1px dashed var(--rule)" }}>
                <span>{d}</span>
                <span className="mono" style={{ color: "var(--accent)" }}>${v.event.feePerList}</span>
              </li>
            ))}
          </ul>
        )}

        {form.swag.length > 0 && <>
          <div className="rule" />
          <div className="eyebrow" style={{ marginBottom: 8 }}>SWAG</div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
            {form.swag.map(s => (
              <li key={s} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "1px dashed var(--rule)", fontSize: "0.95rem" }}>
                <span>{s}</span>
                <span className="mono">${swagMap[s]}</span>
              </li>
            ))}
          </ul>
        </>}

        <div className="rule-double" style={{ margin: "18px 0 12px" }} />
        <div className="sum-row sum-row-big"><span>Total</span><span>${total}</span></div>
        {form.donateAmount > 0 && (
          <div className="mono" style={{ fontSize: "0.75rem", color: "var(--ink-mute)", marginTop: 6 }}>
            INCLUDES ${form.donateAmount} MARSHALS' FUND
          </div>
        )}
      </div>

      <div className="mono" style={{ fontSize: "0.75rem", color: "var(--ink-mute)", letterSpacing: "0.2em", textTransform: "uppercase", marginTop: 14, textAlign: "center" }}>
        SECURED BY STRIPE · PCI
      </div>
    </aside>
  );
}

function FormStyles() {
  return (
    <style>{`
      .form-sect { padding: var(--space-7) 0; border-bottom: 1px solid var(--rule); }
      .form-sect:last-of-type { border-bottom: 0; }
      .form-sect-head { display: grid; grid-template-columns: 88px 1fr; gap: var(--space-4); align-items: start; margin-bottom: var(--space-5); }
      .form-sect-num { font-family: var(--font-display); font-size: var(--scale-7); color: var(--accent); letter-spacing: 0.04em; line-height: 1; border-right: 1px solid var(--rule); padding-right: var(--space-4); text-align: right; }
      .form-sect-body { padding-left: 88px; }
      @media (max-width: 720px) {
        .form-sect-head { grid-template-columns: 1fr; }
        .form-sect-num { border-right: 0; border-bottom: 1px solid var(--rule); padding: 0 0 8px; text-align: left; font-size: var(--scale-6); }
        .form-sect-body { padding-left: 0; }
      }
      .row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-4); }
      .row-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: var(--space-4); }
      @media (max-width: 600px) { .row-2, .row-3 { grid-template-columns: 1fr; } }

      .div-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: var(--space-4); }
      .div-pick { text-align: left; background: var(--paper); border: 1px solid var(--rule); border-bottom: 3px solid var(--ink); padding: 18px 18px 16px; cursor: pointer; font-family: inherit; color: var(--ink); transition: all .15s; }
      .div-pick:hover { transform: translateY(-2px); border-color: var(--ink); }
      .div-pick.is-on { background: var(--ink); color: var(--paper); border-color: var(--ink); border-bottom: 3px solid var(--accent); }
      .div-pick.is-on .pill { background: var(--accent); color: var(--paper); border-color: var(--accent); }
      .div-pick.is-on .eyebrow { color: color-mix(in oklab, var(--paper) 70%, transparent); }
      .div-pick-head { display: flex; justify-content: space-between; align-items: center; color: var(--accent); margin-bottom: 16px; }
      .div-pick.is-on .div-pick-head { color: var(--accent-soft); }
      .div-pick-name { font-family: var(--font-display); font-size: var(--scale-5); letter-spacing: 0.04em; }

      .radio-row { display: flex; flex-wrap: wrap; gap: 10px; }
      .radio-pill { display: inline-flex; align-items: center; gap: 6px; font-family: var(--font-display); font-size: 0.85rem; letter-spacing: 0.14em; text-transform: uppercase; padding: 10px 18px; border: 1px solid var(--rule); background: var(--paper); cursor: pointer; transition: all .15s; }
      .radio-pill:hover { border-color: var(--ink); }
      .radio-pill.is-on { background: var(--ink); color: var(--paper); border-color: var(--ink); }
      .radio-pill input { display: none; }

      .gear-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 8px 24px; }
      .waiver-box { background: color-mix(in oklab, var(--paper-deep) 60%, var(--paper)); border: 1px solid var(--rule); border-left: 4px solid var(--accent); padding: 18px 22px; margin-bottom: var(--space-4); }

      .swag-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: var(--space-4); }
      .swag-card { padding: 0; background: var(--paper); border: 1px solid var(--rule); border-bottom: 3px solid var(--rule); cursor: pointer; text-align: left; font-family: inherit; color: var(--ink); transition: all .15s; overflow: hidden; }
      .swag-card:hover { transform: translateY(-2px); border-bottom-color: var(--ink); }
      .swag-card.is-on { border-bottom-color: var(--accent); }
      .swag-card.is-on .eyebrow { color: var(--accent); }

      .sum-row { display: flex; justify-content: space-between; align-items: baseline; padding: 6px 0; font-size: 0.95rem; }
      .sum-row-big { font-family: var(--font-display); font-size: var(--scale-6); letter-spacing: 0.04em; padding: 8px 0; }
    `}</style>
  );
}

Object.assign(window, { RegisterPage });
