// Booking page — multi-step flow

function BookingPage() {
  const { lang } = useT();
  const L = window.I18N[lang].booking;
  const [step, setStep] = useState(0);
  const [booking, setBooking] = useState({
    date: null,
    time: null,
    template: null,
    childName: "",
    childAge: 7,
    parentName: "",
    parentEmail: "",
    parentPhone: "",
    notes: "",
  });
  const [ref, setRef] = useState("");

  const update = (k, v) => setBooking(b => ({ ...b, [k]: v }));

  const canNext = () => {
    if (step === 0) return !!booking.date;
    if (step === 1) return !!booking.time;
    if (step === 2) return !!booking.template;
    if (step === 3) return booking.childName.trim() && booking.parentName.trim() && booking.parentEmail.includes("@") && booking.parentPhone.length > 6;
    return true;
  };

  const goNext = () => {
    if (!canNext()) return;
    if (step === 4) {
      // confirm
      setRef("PXL-" + Math.floor(Math.random() * 90000 + 10000));
      setStep(5);
    } else {
      setStep(s => s + 1);
    }
  };
  const goBack = () => setStep(s => Math.max(0, s - 1));

  return (
    <div className="page-enter">
      <section style={{ paddingTop: 50, paddingBottom: 30 }}>
        <div className="container">
          <div className="eyebrow">{L.eyebrow} 🎟️</div>
          <h1 style={{ marginTop: 18, marginBottom: 0 }}>{L.title}</h1>
        </div>
      </section>

      {step < 5 && (
        <section style={{ paddingTop: 0, paddingBottom: 20 }}>
          <div className="container">
            <StepIndicator step={step} labels={L.stepLabels} />
          </div>
        </section>
      )}

      <section style={{ paddingTop: 0 }}>
        <div className="container">
          <div className="grid" style={{ gridTemplateColumns: step === 5 ? "1fr" : "1.5fr 1fr", gap: 32 }}>
            <div>
              <div className="card" style={{ background: "var(--paper)", padding: 36, minHeight: 420 }}>
                {step === 0 && <StepDate booking={booking} update={update} lang={lang} L={L} />}
                {step === 1 && <StepTime booking={booking} update={update} lang={lang} L={L} />}
                {step === 2 && <StepTemplate booking={booking} update={update} lang={lang} L={L} />}
                {step === 3 && <StepKid booking={booking} update={update} lang={lang} L={L} />}
                {step === 4 && <StepReview booking={booking} lang={lang} L={L} />}
                {step === 5 && <StepDone booking={booking} lang={lang} L={L} refCode={ref} restart={() => { setStep(0); setBooking({ date: null, time: null, template: null, childName: "", childAge: 7, parentName: "", parentEmail: "", parentPhone: "", notes: "" }); }} />}
              </div>

              {step < 5 && (
                <div className="row" style={{ justifyContent: "space-between", marginTop: 24 }}>
                  <button className="btn" onClick={goBack} disabled={step === 0} style={{ opacity: step === 0 ? 0.3 : 1, pointerEvents: step === 0 ? "none" : "auto" }}>{L.back}</button>
                  <button className="btn btn-red" onClick={goNext} disabled={!canNext()} style={{ opacity: canNext() ? 1 : 0.5, pointerEvents: canNext() ? "auto" : "none" }}>
                    {step === 4 ? L.confirm : L.next}
                  </button>
                </div>
              )}
            </div>

            {step < 5 && <BookingSummary booking={booking} lang={lang} L={L} />}
          </div>
        </div>
      </section>
    </div>
  );
}

// ============ Step indicator ============
function StepIndicator({ step, labels }) {
  return (
    <div style={{ display: "flex", gap: 8, marginBottom: 8, flexWrap: "wrap" }}>
      {labels.map((l, i) => {
        const done = i < step;
        const active = i === step;
        return (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, flex: "1 1 120px" }}>
            <div style={{
              width: 36, height: 36, borderRadius: 99,
              background: done ? "var(--green)" : active ? "var(--red)" : "var(--paper)",
              color: done || active ? "#fff" : "var(--ink)",
              border: "3px solid var(--ink)",
              display: "grid", placeItems: "center",
              fontFamily: "var(--font-display)",
              fontSize: "0.9rem",
              flexShrink: 0,
              boxShadow: "3px 3px 0 var(--ink)",
            }}>{done ? "✓" : i + 1}</div>
            <div className="hand" style={{ fontSize: "1.05rem", opacity: active ? 1 : 0.7, fontWeight: active ? 700 : 400 }}>{l}</div>
          </div>
        );
      })}
    </div>
  );
}

// ============ Booking summary panel ============
function BookingSummary({ booking, lang, L }) {
  const tpl = booking.template ? window.TEMPLATES.find(t => t.id === booking.template) : null;
  return (
    <div className="card" style={{ background: "var(--blue)", color: "var(--paper)", padding: 28, position: "sticky", top: 90, alignSelf: "flex-start", height: "fit-content" }}>
      <div className="tape" style={{ background: "var(--orange)", opacity: 0.7 }} />
      <div className="display" style={{ fontSize: "1.2rem", marginBottom: 16 }}>{L.summary}</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, fontSize: "1rem" }}>
        <SumRow label={L.stepLabels[0]} value={booking.date ? formatDate(booking.date, lang) : "—"} />
        <SumRow label={L.stepLabels[1]} value={booking.time || "—"} />
        <SumRow label={L.stepLabels[2]} value={tpl ? `${tpl.emoji} ${tpl[lang].name}` : "—"} />
        <SumRow label={L.childName} value={booking.childName || "—"} />
        <SumRow label={lang === "th" ? "อายุ" : "Age"} value={booking.childName ? booking.childAge : "—"} />
      </ul>
      <div style={{ marginTop: 20, paddingTop: 16, borderTop: "1px dashed rgba(255,255,255,0.4)", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <div className="display" style={{ fontSize: "1rem" }}>{L.total}</div>
        <div className="display" style={{ fontSize: "1.6rem", color: "var(--orange)" }}>590 ฿</div>
      </div>
    </div>
  );
}

function SumRow({ label, value }) {
  return (
    <li style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", gap: 10, borderBottom: "1px dashed rgba(255,255,255,0.2)" }}>
      <span className="hand" style={{ opacity: 0.8 }}>{label}</span>
      <span style={{ fontWeight: 700, textAlign: "right" }}>{value}</span>
    </li>
  );
}

function formatDate(date, lang) {
  if (!date) return "—";
  const d = new Date(date);
  const opts = { weekday: "short", month: "short", day: "numeric" };
  try {
    return d.toLocaleDateString(lang === "th" ? "th-TH" : "en-US", opts);
  } catch {
    return d.toDateString();
  }
}

// ============ Step 1: Date ============
function StepDate({ booking, update, lang, L }) {
  // Next 4 weeks of Saturdays + Sundays
  const today = new Date();
  const days = [];
  for (let i = 0; i < 21; i++) {
    const d = new Date(today);
    d.setDate(d.getDate() + i);
    const dow = d.getDay();
    if (dow === 0 || dow === 6 || dow === 5) days.push(d); // Fri Sat Sun
  }

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>{L.step1}</h2>
      <p className="hand" style={{ fontSize: "1.1rem", opacity: 0.7, marginBottom: 24 }}>
        {lang === "th" ? "เปิดวันศุกร์–อาทิตย์ เลือกวันที่ใช่!" : "We're open Fri–Sun. Pick one that works."}
      </p>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))", gap: 12 }}>
        {days.map((d, i) => {
          const iso = d.toISOString().slice(0, 10);
          const selected = booking.date === iso;
          const dow = d.toLocaleDateString(lang === "th" ? "th-TH" : "en-US", { weekday: "short" });
          const day = d.getDate();
          const month = d.toLocaleDateString(lang === "th" ? "th-TH" : "en-US", { month: "short" });
          return (
            <button key={iso} onClick={() => update("date", iso)} className="card" style={{
              padding: 16,
              cursor: "pointer",
              background: selected ? "var(--red)" : "var(--paper)",
              color: selected ? "#fff" : "var(--ink)",
              border: "3px solid var(--ink)",
              transform: selected ? "rotate(-2deg) scale(1.05)" : `rotate(${i % 2 === 0 ? -0.5 : 0.5}deg)`,
              transition: "transform 0.15s",
              textAlign: "center",
              borderRadius: 12,
              boxShadow: selected ? "6px 6px 0 var(--ink)" : "4px 4px 0 var(--ink)",
            }}>
              <div className="hand" style={{ fontSize: "1rem", opacity: 0.7 }}>{dow}</div>
              <div className="display" style={{ fontSize: "1.8rem", lineHeight: 1, margin: "4px 0" }}>{day}</div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: "0.75rem" }}>{month}</div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ============ Step 2: Time ============
function StepTime({ booking, update, lang, L }) {
  const times = [
    { t: "10:00", left: 4 },
    { t: "12:00", left: 0 },
    { t: "14:00", left: 2 },
    { t: "16:00", left: 6 },
    { t: "18:00", left: 1 },
  ];
  return (
    <div>
      <h2 style={{ marginBottom: 12 }}>{L.step2}</h2>
      <p className="hand" style={{ fontSize: "1.1rem", opacity: 0.7, marginBottom: 24 }}>
        {lang === "th" ? "เวิร์กช็อปใช้เวลา 90 นาที" : "Each workshop runs 90 minutes."}
      </p>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))", gap: 12 }}>
        {times.map((time, i) => {
          const full = time.left === 0;
          const selected = booking.time === time.t;
          return (
            <button key={time.t} onClick={() => !full && update("time", time.t)} className="card" disabled={full} style={{
              padding: 18,
              cursor: full ? "not-allowed" : "pointer",
              background: full ? "rgba(0,0,0,0.05)" : selected ? "var(--blue)" : "var(--paper)",
              color: full ? "rgba(0,0,0,0.4)" : selected ? "#fff" : "var(--ink)",
              transform: selected ? "rotate(-1deg) scale(1.03)" : `rotate(${i % 2 === 0 ? -0.4 : 0.4}deg)`,
              transition: "transform 0.15s",
              textAlign: "left",
              border: "3px solid var(--ink)",
              borderRadius: 12,
              opacity: full ? 0.5 : 1,
            }}>
              <div className="display" style={{ fontSize: "1.6rem", marginBottom: 4 }}>{time.t}</div>
              <div className="hand" style={{ fontSize: "1rem", opacity: 0.9 }}>
                {full ? L.noslot : `${time.left} ${time.left === 1 ? L.slotsLeft : L.slotsLeftPl}`}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ============ Step 3: Template ============
function StepTemplate({ booking, update, lang, L }) {
  const tpls = window.TEMPLATES;
  return (
    <div>
      <h2 style={{ marginBottom: 12 }}>{L.step3}</h2>
      <p className="hand" style={{ fontSize: "1.1rem", opacity: 0.7, marginBottom: 24 }}>
        {lang === "th" ? "ลูกอยากสร้างเกมแบบไหน?" : "What kind of game does your kid want to make?"}
      </p>
      <div className="grid grid-2">
        {tpls.map((t, i) => {
          const selected = booking.template === t.id;
          return (
            <button key={t.id} onClick={() => update("template", t.id)} className="card" style={{
              padding: 20,
              cursor: "pointer",
              background: selected ? t.color : "var(--paper)",
              color: selected ? "#fff" : "var(--ink)",
              transform: selected ? `rotate(${i % 2 === 0 ? -2 : 2}deg) scale(1.03)` : `rotate(${i % 2 === 0 ? -1 : 1}deg)`,
              transition: "transform 0.15s",
              textAlign: "left",
              borderRadius: 12,
              border: "3px solid var(--ink)",
              minHeight: 160,
              display: "flex",
              flexDirection: "column",
              justifyContent: "space-between",
            }}>
              <div style={{ fontSize: "3rem", lineHeight: 1 }}>{t.emoji}</div>
              <div>
                <div className="display" style={{ fontSize: "1.2rem", marginBottom: 4 }}>{t[lang].name}</div>
                <div className="hand" style={{ fontSize: "1.05rem", opacity: 0.95 }}>{t[lang].tag}</div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ============ Step 4: Kid info ============
function StepKid({ booking, update, lang, L }) {
  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>{L.step4}</h2>
      <div className="grid grid-2" style={{ gap: 18 }}>
        <div className="field">
          <label>{L.childName}</label>
          <input value={booking.childName} onChange={(e) => update("childName", e.target.value)} placeholder="Pim" />
        </div>
        <div className="field">
          <label>{L.childAge}</label>
          <select value={booking.childAge} onChange={(e) => update("childAge", +e.target.value)}>
            {[5,6,7,8,9,10,11,12].map(a => <option key={a} value={a}>{a}</option>)}
          </select>
        </div>
        <div className="field">
          <label>{L.parentName}</label>
          <input value={booking.parentName} onChange={(e) => update("parentName", e.target.value)} />
        </div>
        <div className="field">
          <label>{L.parentEmail}</label>
          <input type="email" value={booking.parentEmail} onChange={(e) => update("parentEmail", e.target.value)} />
        </div>
        <div className="field" style={{ gridColumn: "1 / -1" }}>
          <label>{L.parentPhone}</label>
          <input value={booking.parentPhone} onChange={(e) => update("parentPhone", e.target.value)} placeholder="08X-XXX-XXXX" />
        </div>
        <div className="field" style={{ gridColumn: "1 / -1" }}>
          <label>{L.notes}</label>
          <textarea rows={3} value={booking.notes} onChange={(e) => update("notes", e.target.value)} />
        </div>
      </div>
    </div>
  );
}

// ============ Step 5: Review ============
function StepReview({ booking, lang, L }) {
  const tpl = window.TEMPLATES.find(t => t.id === booking.template);
  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>{L.step5}</h2>
      <div className="grid grid-2" style={{ gap: 16 }}>
        <ReviewRow icon="📅" label={L.stepLabels[0]} value={formatDate(booking.date, lang)} />
        <ReviewRow icon="🕐" label={L.stepLabels[1]} value={booking.time} />
        <ReviewRow icon={tpl.emoji} label={L.stepLabels[2]} value={tpl[lang].name} />
        <ReviewRow icon="🎨" label={L.childName} value={`${booking.childName}, ${booking.childAge}`} />
        <ReviewRow icon="👤" label={L.parentName} value={booking.parentName} />
        <ReviewRow icon="✉️" label={L.parentEmail} value={booking.parentEmail} />
        <ReviewRow icon="📞" label={L.parentPhone} value={booking.parentPhone} fullWidth />
        {booking.notes && <ReviewRow icon="📝" label={L.notes} value={booking.notes} fullWidth />}
      </div>
      <div className="card mt-4" style={{ background: "var(--ink)", color: "var(--paper)", display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "16px 24px" }}>
        <div className="display">{L.total}</div>
        <div className="display" style={{ fontSize: "1.8rem", color: "var(--green)" }}>590 ฿</div>
      </div>
    </div>
  );
}

function ReviewRow({ icon, label, value, fullWidth }) {
  return (
    <div style={{ gridColumn: fullWidth ? "1 / -1" : undefined, display: "flex", gap: 12, padding: "10px 14px", border: "3px solid var(--ink)", borderRadius: 12, background: "#fffaca", alignItems: "center" }}>
      <div style={{ fontSize: "1.5rem", flexShrink: 0 }}>{icon}</div>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div className="hand" style={{ fontSize: "0.95rem", opacity: 0.65 }}>{label}</div>
        <div style={{ fontWeight: 700, wordBreak: "break-word" }}>{value || "—"}</div>
      </div>
    </div>
  );
}

// ============ Step 6: Done ============
function StepDone({ booking, lang, L, refCode, restart }) {
  return (
    <div className="center">
      <div style={{ display: "inline-block", animation: "spinSlow 4s linear infinite" }}>
        <Burst size={120} color="var(--green)" />
      </div>
      <h1 style={{ marginTop: 16, marginBottom: 12 }}>{L.done}</h1>
      <p style={{ fontSize: "1.2rem", maxWidth: 480, margin: "0 auto 24px" }}>{L.doneBody}</p>
      <div className="card" style={{ background: "var(--ink)", color: "var(--paper)", display: "inline-block", padding: "16px 32px", margin: "0 auto" }}>
        <div className="hand" style={{ fontSize: "1rem", opacity: 0.7 }}>{L.doneRef}</div>
        <div className="display" style={{ fontSize: "2rem", color: "var(--orange)", letterSpacing: "0.1em" }}>{refCode}</div>
      </div>
      <div className="row row-center mt-4">
        <button className="btn" onClick={restart}>{L.pickAnother}</button>
        <a className="btn btn-red" href="#/games" onClick={(e) => { e.preventDefault(); location.hash = "#/games"; }}>
          {lang === "th" ? "ดูเกมที่เด็กๆทำ" : "See what kids made"} →
        </a>
      </div>
      <style>{`
        @keyframes spinSlow { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

window.BookingPage = BookingPage;
