/* global React, Icon, Button, Field, TextInput, Select, Qty, DishCard, euro, FEEST */
const { useState: useStateS } = React;

/* ============================================================
   STAP 1 — Gegevens
   ============================================================ */
function StepGegevens({ state, setParent, errors }) {
  const p = state.parent;
  return (
    <div className="wizard-main">
      <div className="section-block">
        <h2 className="section-title"><Icon name="user" size={22} style={{ color: "var(--primary)" }} /> Jouw gegevens</h2>
        <p className="section-sub">We gebruiken je e-mail alleen voor de bevestiging van deze bestelling.</p>
        <div className="card" style={{ padding: "var(--space-6)" }}>
          <div className="formgrid">
            <div className="col-2">
              <div className="namegrid">
                <Field label="Voornaam" required error={errors.voornaam}>
                  <TextInput value={p.voornaam || ""} error={errors.voornaam} placeholder="Bijv. Sanne" onChange={(e) => setParent("voornaam", e.target.value)} />
                </Field>
                <Field label="Tussenvoegsel" optional>
                  <TextInput value={p.tussenvoegsel || ""} placeholder="bijv. van der" onChange={(e) => setParent("tussenvoegsel", e.target.value)} />
                </Field>
                <Field label="Achternaam" required error={errors.achternaam}>
                  <TextInput value={p.achternaam || ""} error={errors.achternaam} placeholder="Bijv. de Vries" onChange={(e) => setParent("achternaam", e.target.value)} />
                </Field>
              </div>
            </div>
            <Field label="E-mailadres" required error={errors.email} hint={!errors.email ? "Hierheen sturen we de bevestiging." : null}>
              <TextInput type="email" value={p.email} error={errors.email} placeholder="ouder@voorbeeld.nl" onChange={(e) => setParent("email", e.target.value)} />
            </Field>
            <Field label="Telefoonnummer" required error={errors.telefoon} hint={!errors.telefoon ? "Voor het geval er iets is op de dag zelf." : null}>
              <TextInput type="tel" value={p.telefoon} error={errors.telefoon} placeholder="06 12 34 56 78" onChange={(e) => setParent("telefoon", e.target.value)} />
            </Field>
            <Field label="Met hoeveel volwassenen kom je?" required hint="Inclusief jezelf.">
              <div className="seg" role="group" aria-label="Aantal volwassenen" style={{ display: "flex", flexWrap: "wrap" }}>
                {[1, 2, 3, 4, 5, 6].map((n) => (
                  <button key={n} aria-pressed={p.volwassenen === n} onClick={() => setParent("volwassenen", n)}>{n}{n === 6 ? "+" : ""}</button>
                ))}
              </div>
            </Field>
            <div className="col-2">
              <Field label="Vraag of opmerking" optional hint="Bijvoorbeeld een allergie of iets wat we moeten weten.">
                <textarea className="inp" value={p.opmerking} placeholder="Waar kunnen we mee helpen?" onChange={(e) => setParent("opmerking", e.target.value)} />
              </Field>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   STAP 2 — Kinderen
   ============================================================ */
function KidCard({ kid, index, onChange, onRemove, canRemove, errors }) {
  // niet-actieve kindermenu's (D23) verbergen, behalve als dit kind er al een gekozen had (aanpassen)
  const kidsMenus = ((FEEST.menu.find((c) => c.id === window.KIDS_CLUSTER)?.items) || []).filter((m) => m.active !== false || kid.menu === m.id);
  return (
    <div className="card card--flat" style={{ padding: "var(--space-5)", marginBottom: 14, position: "relative" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 9, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16 }}>
          <span style={{ width: 26, height: 26, borderRadius: "50%", background: "var(--rust-100)", color: "var(--rust-600)", display: "grid", placeItems: "center", fontSize: 13 }}>{index + 1}</span>
          {kid.naam ? kid.naam : `Kind ${index + 1}`}
        </span>
        {canRemove && <button className="kid-del" onClick={onRemove} aria-label="Kind verwijderen"><Icon name="trash" size={18} /></button>}
      </div>
      <div className="formgrid">
        <div className="col-2">
          <div className="namegrid">
            <Field label="Voornaam kind" required error={errors?.voornaam}>
              <TextInput value={kid.voornaam || ""} error={errors?.voornaam} placeholder="Bijv. Noor" onChange={(e) => onChange("voornaam", e.target.value)} />
            </Field>
            <Field label="Tussenvoegsel" optional>
              <TextInput value={kid.tussenvoegsel || ""} placeholder="bijv. van der" onChange={(e) => onChange("tussenvoegsel", e.target.value)} />
            </Field>
            <Field label="Achternaam" required error={errors?.achternaam}>
              <TextInput value={kid.achternaam || ""} error={errors?.achternaam} placeholder="Bijv. de Vries" onChange={(e) => onChange("achternaam", e.target.value)} />
            </Field>
          </div>
        </div>
        <Field label="Zit dit kind op De Schovenhorst?" required>
          <div className="seg" role="group">
            <button aria-pressed={kid.opSchool === true} onClick={() => onChange("opSchool", true)}>Ja</button>
            <button aria-pressed={kid.opSchool === false} onClick={() => onChange("opSchool", false)}>Nee</button>
          </div>
        </Field>
        {kid.opSchool && (
          <Field label="Groep" required error={errors?.groep}>
            <Select value={kid.groep} onChange={(e) => onChange("groep", e.target.value)}>
              <option value="">Kies een groep…</option>
              {FEEST.groups.map((g) => <option key={g} value={g}>{g}</option>)}
            </Select>
          </Field>
        )}
        <div className="col-2">
          <Field label={`Welk kindermenu wil ${kid.voornaam ? kid.voornaam.trim() : "dit kind"}?`} required error={errors?.menu}>
            <div className="kidmenu-grid" role="radiogroup" aria-label="Kindermenu">
              {kidsMenus.map((m) => {
                const sel = kid.menu === m.id;
                return (
                  <button type="button" key={m.id} role="radio" aria-checked={sel}
                    className={"kidmenu-opt" + (sel ? " is-sel" : "")} onClick={() => onChange("menu", m.id)}>
                    <div className={"dish-thumb acc-" + m.accent}>
                      {m.tag && <span className="dish-tag">{m.tag}</span>}
                      {m.img
                        ? <img className="dish-photo" src={m.img} alt={m.name} loading="lazy" />
                        : <div className="ph"><Icon name="child" size={28} /></div>}
                    </div>
                    <div className="kidmenu-body">
                      <h4>{m.name}</h4>
                      <p>{m.desc}</p>
                      <span className="kidmenu-price tnum">{kid.opSchool ? "gratis" : euro(m.price)}</span>
                    </div>
                    <span className="kidmenu-check"><Icon name="check" size={14} /></span>
                  </button>
                );
              })}
              <button type="button" role="radio" aria-checked={kid.menu === "none"}
                className={"kidmenu-opt kidmenu-opt--none" + (kid.menu === "none" ? " is-sel" : "")} onClick={() => onChange("menu", "none")}>
                <div className="dish-thumb kidmenu-thumb--none"><div className="ph"><Icon name="x" size={26} /></div></div>
                <div className="kidmenu-body">
                  <h4>Geen kindermenu</h4>
                  <p>Dit kind hoeft geen kindermenu.</p>
                </div>
                <span className="kidmenu-check"><Icon name="check" size={14} /></span>
              </button>
            </div>
          </Field>
        </div>
      </div>
    </div>
  );
}

function StepKinderen({ state, addKid, updateKid, removeKid, errors }) {
  const schoolKids = state.kids.filter((k) => k.opSchool).length;
  return (
    <div className="wizard-main">
      <div className="section-block">
        <h2 className="section-title"><Icon name="child" size={22} style={{ color: "var(--primary)" }} /> Wie komen er mee?</h2>
        <p className="section-sub">Let op: Om mee te kunnen eten moeten schoolgaande kinderen worden aangemeld.</p>
        {state.kids.map((kid, i) => (
          <KidCard key={kid.id} kid={kid} index={i} canRemove={state.kids.length > 1}
            errors={errors.kids && errors.kids[kid.id]}
            onChange={(f, v) => updateKid(kid.id, f, v)} onRemove={() => removeKid(kid.id)} />
        ))}
        <Button variant="secondary" icon="plus" onClick={addKid}>Nog een kind toevoegen</Button>
        {schoolKids > 0 && (
          <div style={{ display: "flex", gap: 10, alignItems: "center", marginTop: 18, color: "var(--success)", fontSize: 14, fontWeight: 600 }}>
            <Icon name="check" size={18} /> {schoolKids} {schoolKids === 1 ? "kind hoeft" : "kinderen hoeven"} niet te betalen voor het eten.
          </div>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   STAP 3 — Eten & drinken
   ============================================================ */
function StepEten({ state, setItemQty, setTokens, setDonation, setVolunteer, baseline }) {
  const [customDonate, setCustomDonate] = useStateS("");
  const v = state.volunteer;
  const minTokens = 0; // ouders mogen ook verlagen (tot 0); een lagere bestelling -> terugbetaal-voorstel
  const minDon = 0;
  // niet-actieve gerechten (D23) zijn verborgen; staat er al een in een bestaande bestelling (aanpassen),
  // dan blijft hij zichtbaar en mag het aantal alleen omlaag.
  const prevQty = (id) => (baseline && baseline.items && baseline.items[id]) || 0;
  const shown = (it) => it.active !== false || prevQty(it.id) > 0;
  // omschrijving per feest (D25); een leeg ingesteld veld = geen omschrijving, niet terugvallen op het menu
  const catNote = (cat) => { const n = FEEST.categoryNotes || {}; return Object.prototype.hasOwnProperty.call(n, cat.id) ? n[cat.id] : cat.note; };
  const vol = FEEST.volunteer || {};
  // een eerder gekozen moment dat niet meer in de lijst staat, blijft kiesbaar (geen stille wijziging)
  const momenten = (vol.options || []).map((s) => s.trim()).filter(Boolean); // lege regels uit de admin-lijst negeren
  const dagdelen = momenten.concat(v.dagdeel && !momenten.includes(v.dagdeel) ? [v.dagdeel] : []);
  return (
    <div className="wizard-main">
      <div className="section-block" style={{ marginBottom: "var(--space-5)" }}>
        <h2 className="section-title"><Icon name="bag" size={22} style={{ color: "var(--primary)" }} /> Eten & drinken</h2>
        <p className="section-sub">{baseline ? "Je kunt bijbestellen of je bestelling verlagen tot " + FEEST.event.deadline + "." : "Kies wat je vooraf wilt bestellen. Aanpassen kan tot " + FEEST.event.deadline + "."}</p>
      </div>

      {/* kindermenu's kiezen ouders per kind op stap 2; hier alleen het overige aanbod */}
      {FEEST.menu.filter((cat) => cat.id !== window.KIDS_CLUSTER && cat.items.some(shown)).map((cat) => (
        <div className="cat" key={cat.id}>
          <div className="cat-head">
            <span className="ic"><Icon name="drumstick" size={22} /></span>
            <div><h2>{cat.label}</h2>{catNote(cat) && <p>{catNote(cat)}</p>}</div>
          </div>
          <div className="dishgrid">
            {cat.items.filter(shown).map((it) => (
              <DishCard key={it.id} item={it} qty={state.order.items[it.id] || 0} min={0}
                max={it.active === false ? prevQty(it.id) : undefined} onChange={(q) => setItemQty(it.id, q)} />
            ))}
          </div>
        </div>
      ))}

      {/* Drinkmuntjes */}
      <div className="panel fill-teal" style={{ marginBottom: "var(--space-5)" }}>
        <div className="panel-head">
          <span className="ic" style={{ background: "rgba(255,255,255,0.15)", color: "#fff" }}><Icon name="cup" size={24} /></span>
          <div style={{ flex: 1 }}>
            <h3 style={{ color: "#fff" }}>Drinkmuntjes</h3>
            <p>Voor drankjes op het feest. Eén muntje kost {euro(FEEST.tokenPrice)}. Koop vooraf en sla de rij over.</p>
            <div className="bundles">
              {FEEST.tokenBundles.map((b) => (
                <button key={b.id} className="bundle" style={{ background: "rgba(255,255,255,0.95)" }} onClick={() => setTokens(state.order.tokens + b.count)}>
                  <b style={{ color: "var(--teal-700)" }}>+{b.count}</b>
                  <span>{euro(b.count * FEEST.tokenPrice)}</span>
                </button>
              ))}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 18, flexWrap: "wrap" }}>
              <span style={{ color: "var(--teal-100)", fontSize: 14, fontWeight: 600 }}>In je mandje:</span>
              <Qty value={state.order.tokens} onChange={setTokens} min={minTokens} max={200} solid />
              <span style={{ color: "#fff", fontWeight: 700 }} className="tnum">{euro(state.order.tokens * FEEST.tokenPrice)}</span>
            </div>
          </div>
          <img className="drink-photo" src="assets/drinks.jpg" alt="Koude drankjes" loading="lazy" />
        </div>
      </div>

      {/* Donatie */}
      <div className="panel fill-gold" style={{ marginBottom: "var(--space-5)" }}>
        <div className="panel-head">
          <span className="ic" style={{ background: "var(--gold-300)", color: "var(--gold-900)" }}><Icon name="heart" size={22} /></span>
          <div style={{ flex: 1 }}>
            <h3>Bijdrage Ouderraad (OR)</h3>
            <p style={{ color: "var(--ink-700)" }}>De Ouderraad (OR) maakt het feest mogelijk. Een kleine bijdrage is heel welkom en helemaal vrijblijvend.</p>
            <div className="donate-row">
              {FEEST.donationPresets.map((d) => (
                <button key={d} className={"chip" + (state.order.donation === d ? " is-on" : "")} disabled={d < minDon} onClick={() => { setDonation(state.order.donation === d ? minDon : d); setCustomDonate(""); }}>{euro(d)}</button>
              ))}
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ color: "var(--ink-600)", fontWeight: 700 }}>€</span>
                <input className="inp" inputMode="decimal" placeholder="anders" value={customDonate} style={{ width: 90 }}
                  onChange={(e) => { const val = e.target.value.replace(",", "."); setCustomDonate(e.target.value); const n = parseFloat(val); setDonation(isNaN(n) ? minDon : n); }} />
              </div>
              {state.order.donation > minDon && <button className="linkbtn" onClick={() => { setDonation(minDon); setCustomDonate(""); }}>{minDon > 0 ? "terug naar " + euro(minDon) : "wissen"}</button>}
            </div>
          </div>
        </div>
      </div>

      {/* Vrijwilliger — teksten per feest instelbaar (D24); uitgezet = verborgen, tenzij je je al had aangemeld */}
      {(vol.active !== false || v.wil) && <div className="panel">
        <div className="panel-head">
          <span className="ic" style={{ background: "var(--rust-100)", color: "var(--rust-600)" }}><Icon name="hand" size={22} /></span>
          <div style={{ flex: 1 }}>
            <h3>{vol.title}</h3>
            <p>{vol.text}</p>
            <label style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 16, cursor: "pointer", fontWeight: 600, fontSize: 15 }}>
              <input type="checkbox" checked={v.wil} onChange={(e) => setVolunteer({ wil: e.target.checked })} style={{ width: 20, height: 20, accentColor: "var(--primary)" }} />
              Ja, ik wil graag een handje helpen
            </label>
            {v.wil && (
              <div className="formgrid" style={{ marginTop: 16 }}>
                <Field label="Wanneer help je mee?">
                  <Select value={v.dagdeel} onChange={(e) => setVolunteer({ dagdeel: e.target.value })}>
                    <option value="">Maakt niet uit</option>
                    {dagdelen.map((o) => <option key={o}>{o}</option>)}
                  </Select>
                </Field>
              </div>
            )}
          </div>
        </div>
      </div>}
    </div>
  );
}

Object.assign(window, { StepGegevens, StepKinderen, StepEten });
