/* ============================================================
   Book a demo — new design, real calendar + working POST.
   Calendar/submit logic mirrors the live site; styled to v2.
   ============================================================ */

const BK_TIMES = ["09:30", "11:00", "13:30", "15:00", "16:30"];

/* full-month calendar helpers — real dates, weekends + past disabled */
function startOfToday() { const d = new Date(); d.setHours(0, 0, 0, 0); return d; }
function isBookable(date, today) { const wd = date.getDay(); return date >= today && wd !== 0 && wd !== 6; }
function firstBookable(today) {
  const d = new Date(today);
  for (let i = 0; i < 62; i++) { if (isBookable(d, today)) return new Date(d); d.setDate(d.getDate() + 1); }
  return new Date(today);
}
function sameDay(a, b) { return !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); }
function monthGrid(view, today) {
  const first = new Date(view.getFullYear(), view.getMonth(), 1);
  const start = new Date(first); start.setDate(first.getDate() - first.getDay());   // Sunday-first
  const cells = [];
  for (let i = 0; i < 42; i++) {
    const date = new Date(start); date.setDate(start.getDate() + i);
    const inMonth = date.getMonth() === view.getMonth();
    cells.push({ date, inMonth, bookable: inMonth && isBookable(date, today) });
  }
  return cells;
}
function fmtBookingDate(lang, d, D) {
  const day = d.getDate(), mon = D.monthsLong[d.getMonth()], yr = d.getFullYear();
  return lang === "da" ? `${day}. ${mon} ${yr}` : `${day} ${mon} ${yr}`;
}
const capFirst = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);

function BookingCard() {
  const { lang, L } = useT();
  const D = L.demo;
  const [today] = useState(startOfToday);
  const [selected, setSelected] = useState(() => firstBookable(today));
  const [view, setView] = useState(() => { const s = firstBookable(today); return new Date(s.getFullYear(), s.getMonth(), 1); });
  const [step, setStep] = useState(0);     // 0 date+time, 1 details, 2 done
  const [time, setTime] = useState(null);
  const [email, setEmail] = useState("");
  const [vol, setVol] = useState("");
  const [err, setErr] = useState("");
  const [sending, setSending] = useState(false);

  const humanDate = selected ? fmtBookingDate(lang, selected, D) : "";
  const curMonthStart = new Date(today.getFullYear(), today.getMonth(), 1).getTime();
  const prevDisabled = view.getTime() <= curMonthStart;
  const cells = monthGrid(view, today);
  const weekHeads = D.weekdaysShort.map((w) => w.slice(0, 2));

  const field = { width: "100%", height: 46, padding: "0 14px", borderRadius: 12, fontSize: 14.5, fontFamily: "var(--sans)", border: "1px solid var(--line-2)", background: "var(--surface)", outline: "none", color: "var(--ink)" };

  const submit = async () => {
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { setErr(D.errEmail); return; }
    if (!vol) { setErr(D.errVol); return; }
    setErr(""); setSending(true);
    try {
      const r = await fetch("/api/book-demo", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email.trim(), volume: vol, date: humanDate, time }),
      });
      if (!r.ok) throw new Error("book failed");
      setSending(false); setStep(2);
    } catch (e) { setSending(false); setErr(D.bookErr); }
  };

  return (
    <div className="shot" style={{ borderRadius: 24, padding: 28 }}>
      {/* progress */}
      <div style={{ display: "flex", gap: 8, marginBottom: 24 }}>
        {D.steps.map((s, i) => (
          <div key={s} style={{ flex: 1 }}>
            <div style={{ height: 4, borderRadius: 3, background: step >= i ? "var(--primary)" : "var(--bg-tint)", transition: "background .3s" }}></div>
            <div className="mono-label" style={{ marginTop: 8, fontSize: 10, color: step >= i ? "var(--primary)" : "var(--ink-4)" }}>{`0${i + 1} · ${s}`}</div>
          </div>
        ))}
      </div>

      {step === 0 && (
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
            <span style={{ fontWeight: 700, fontSize: 15 }}>{capFirst(D.monthsLong[view.getMonth()])} {view.getFullYear()}</span>
            <span style={{ display: "flex", gap: 6 }}>
              <button type="button" disabled={prevDisabled} aria-label="‹"
                onClick={() => setView(new Date(view.getFullYear(), view.getMonth() - 1, 1))}
                style={{ width: 30, height: 30, borderRadius: 8, display: "grid", placeItems: "center", boxShadow: "inset 0 0 0 1px var(--line-2)", color: "var(--ink-3)", opacity: prevDisabled ? .35 : 1, cursor: prevDisabled ? "default" : "pointer" }}>‹</button>
              <button type="button" aria-label="›"
                onClick={() => setView(new Date(view.getFullYear(), view.getMonth() + 1, 1))}
                style={{ width: 30, height: 30, borderRadius: 8, display: "grid", placeItems: "center", boxShadow: "inset 0 0 0 1px var(--line-2)", color: "var(--ink-3)", cursor: "pointer" }}>›</button>
            </span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 4, marginBottom: 6 }}>
            {weekHeads.map((w, i) => (
              <div key={i} className="mono-label" style={{ fontSize: 9.5, textAlign: "center", color: "var(--ink-4)" }}>{w}</div>
            ))}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 4, marginBottom: 20 }}>
            {cells.map((c, i) => {
              const sel = sameDay(c.date, selected);
              return (
                <button key={i} type="button" disabled={!c.bookable}
                  onClick={() => c.bookable && setSelected(c.date)}
                  style={{ height: 34, borderRadius: 9, fontSize: 13, fontWeight: 600, textAlign: "center",
                    background: sel ? "var(--primary)" : c.bookable ? "var(--bg-2)" : "transparent",
                    color: sel ? "#fff" : (c.bookable ? "var(--ink)" : "var(--ink-4)"),
                    opacity: c.inMonth ? (c.bookable ? 1 : .4) : .25,
                    cursor: c.bookable ? "pointer" : "default", transition: "all .12s" }}>
                  {c.date.getDate()}
                </button>
              );
            })}
          </div>
          <div className="mono-label" style={{ marginBottom: 10 }}>{D.chooseTime}</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8, marginBottom: 24 }}>
            {BK_TIMES.map((t) => (
              <button key={t} onClick={() => setTime(t)} style={{
                padding: "11px 0", borderRadius: 12, fontSize: 14, fontWeight: 600,
                background: time === t ? "var(--sky)" : "var(--bg-2)",
                color: time === t ? "var(--primary-ink)" : "var(--ink-2)",
                boxShadow: time === t ? "inset 0 0 0 1.5px var(--primary)" : "none", transition: "all .15s" }}>{t}</button>
            ))}
          </div>
          <button disabled={!time} onClick={() => time && setStep(1)}
            style={{ width: "100%", height: 50, borderRadius: 999, fontWeight: 600, fontSize: 15,
              background: time ? "var(--contrast-bg)" : "var(--bg-2)", color: time ? "var(--contrast-fg)" : "var(--ink-4)",
              cursor: time ? "pointer" : "not-allowed", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
            {time ? fill(D.continue, { date: humanDate, time }) : D.selectTime}
          </button>
        </div>
      )}

      {step === 1 && (
        <div style={{ display: "grid", gap: 16 }}>
          <div>
            <label className="mono-label" style={{ display: "block", marginBottom: 8 }}>{D.emailLabel}</label>
            <input value={email} onChange={(e) => { setEmail(e.target.value); setErr(""); }} placeholder={D.emailPh} type="email" style={field} />
          </div>
          <div>
            <label className="mono-label" style={{ display: "block", marginBottom: 8 }}>{D.volLabel}</label>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
              {D.volOpts.map((o) => (
                <button key={o} onClick={() => { setVol(o); setErr(""); }} style={{
                  padding: "11px 13px", borderRadius: 12, fontSize: 13, fontWeight: 600, textAlign: "left",
                  background: vol === o ? "var(--sky)" : "var(--bg-2)",
                  color: vol === o ? "var(--primary-ink)" : "var(--ink-2)",
                  boxShadow: vol === o ? "inset 0 0 0 1.5px var(--primary)" : "none", transition: "all .15s" }}>{o}</button>
              ))}
            </div>
          </div>
          {err && <div style={{ fontSize: 12.5, color: "var(--stop)", fontWeight: 500 }}>{err}</div>}
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={() => setStep(0)} className="btn btn-ghost" style={{ flex: "none" }}>{D.back}</button>
            <button onClick={submit} disabled={sending} className="btn btn-primary" style={{ flex: 1, opacity: sending ? .7 : 1, cursor: sending ? "wait" : "pointer" }}>{sending ? D.sending : D.book}</button>
          </div>
          <div className="mono-label" style={{ fontSize: 10, color: "var(--ink-4)" }}>{fill(D.selected, { date: humanDate, time: time || "—" })}</div>
        </div>
      )}

      {step === 2 && (
        <div style={{ textAlign: "center", padding: "22px 0 10px" }}>
          <div style={{ width: 60, height: 60, margin: "0 auto 18px", borderRadius: 18, background: "var(--auto-tint)", color: "var(--auto)", display: "grid", placeItems: "center" }}>
            <Icon.check style={{ width: 30, height: 30 }} />
          </div>
          <h3 style={{ fontSize: 24, marginBottom: 8 }}>{D.doneTitle}</h3>
          <p style={{ fontSize: 14.5, color: "var(--ink-2)", maxWidth: 320, margin: "0 auto 20px", lineHeight: 1.5 }}>
            {D.doneBody.split("{email}").map((part, i) => (
              <React.Fragment key={i}>{i > 0 ? <strong style={{ color: "var(--ink)" }}>{email}</strong> : null}{part}</React.Fragment>
            ))}
          </p>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 10, padding: "12px 20px", borderRadius: 999, background: "var(--sky)" }}>
            <Icon.book style={{ width: 18, height: 18, color: "var(--primary)" }} />
            <span style={{ fontWeight: 600, fontSize: 14, color: "var(--primary-ink)" }}>{fill(D.doneChip, { date: humanDate, time })}</span>
          </div>
          <div><button onClick={() => { setStep(0); setTime(null); setEmail(""); setVol(""); }} style={{ marginTop: 18, fontSize: 13, color: "var(--ink-3)", fontWeight: 500 }}>{D.another}</button></div>
        </div>
      )}
    </div>
  );
}

function Booking() {
  const { L } = useT();
  const D = L.demo;
  return (
    <section id="demo" className="section ruled dotted" style={{ paddingBottom: 140 }}>
      <div className="wrap">
        <div className="book-grid" style={{ display: "grid", gridTemplateColumns: "1.05fr .95fr", gap: 80, alignItems: "center" }}>
          <Reveal>
            <h2 style={{ fontSize: "clamp(38px,4.6vw,68px)", fontWeight: 700, letterSpacing: "-0.04em", lineHeight: 1.04, marginBottom: 28 }}>
              <Lines text={D.title} />
            </h2>
            <p className="lead" style={{ marginBottom: 34, maxWidth: 480 }}>{D.lead}</p>
            <div style={{ display: "grid", gap: 14 }}>
              {D.bullets.map((t) => (
                <div key={t} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <span style={{ width: 24, height: 24, flex: "none", borderRadius: 8, background: "var(--sky)", color: "var(--primary)", display: "grid", placeItems: "center" }}>
                    <Icon.check style={{ width: 13, height: 13 }} />
                  </span>
                  <span style={{ fontSize: 15, color: "var(--ink-2)" }}>{t}</span>
                </div>
              ))}
            </div>
          </Reveal>
          <Reveal className="rise-d1"><BookingCard /></Reveal>
        </div>
      </div>
      <style>{`@media (max-width:940px){ .book-grid{ grid-template-columns:1fr !important; gap:44px !important; } }`}</style>
    </section>
  );
}

Object.assign(window, { Booking, BookingCard });
