/* global React */
const { useState: useState2, useEffect: useEffect2, useMemo: useMemo2, useRef: useRef2 } = React;

/* ============================================================
   BOOKING — two implementations live here:

   1. <BookingEmbed/>  — FREE plan. Embeds Square's hosted booking
      flow in an iframe. Active now (see USE_SQUARE_EMBED in index.html).

   2. <Booking/>        — CUSTOM design + Square Bookings API (/api/*).
      Requires a PAID Square Appointments plan (write operations).
      Fully built and ready — flip the switch in index.html to use it
      once Jeff upgrades. Do NOT delete.
   ============================================================ */

// Paste the booking flow URL from Square here.
// Square Dashboard → Appointments → Access your booking flow → "Get URL"
// (or the src="..." inside the "Get embed code" snippet).
const SQUARE_BOOKING_URL = "https://app.squareup.com/appointments/book/gxsdutg4xxeygj/LJ1QNNCDK6XPZ/start";

/* ============== BOOKING (Square embed — free plan) ============== */
function BookingEmbed() {
  const ready = SQUARE_BOOKING_URL && SQUARE_BOOKING_URL.indexOf("http") === 0;
  return (
    <section className="booking" id="booking">
      <div className="container">
        <div className="section-header">
          <span className="eyebrow">Reserve Your Chair</span>
          <h2>Book an Appointment</h2>
          <span className="script-sub">or just walk on in</span>
          <div className="underline" />
        </div>
        <div className="booking-card" style={{ padding: 0, overflow: "hidden" }}>
          {ready ? (
            <iframe
              title="Book an appointment at Rinaldo's Barber Shop"
              src={SQUARE_BOOKING_URL}
              style={{ width: "100%", minHeight: 920, border: "none", display: "block" }}
              loading="lazy"
            />
          ) : (
            <div style={{ padding: 40, textAlign: "center", color: "#888" }}>
              Booking is being set up. Please check back shortly, or call the shop.
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
window.BookingEmbed = BookingEmbed;

/* ============== BOOKING WIDGET (custom design + API — paid plan) ============== */
function Booking() {
  const [step, setStep] = useState2(0); // 0 service, 1 date+time, 2 details, 3 confirm
  const [service, setService] = useState2(null);
  const [monthOffset, setMonthOffset] = useState2(0);
  const [selDate, setSelDate] = useState2(null);
  const [selSlot, setSelSlot] = useState2(null); // { startAt, time, teamMemberId }
  const [slots, setSlots] = useState2([]);
  const [slotsLoading, setSlotsLoading] = useState2(false);
  const [slotsError, setSlotsError] = useState2(null);
  const [name, setName] = useState2("");
  const [phone, setPhone] = useState2("");
  const [email, setEmail] = useState2("");
  const [notes, setNotes] = useState2("");
  const [submitting, setSubmitting] = useState2(false);
  const [submitError, setSubmitError] = useState2(null);
  const [confirmedRef, setConfirmedRef] = useState2("");

  const today = new Date();
  today.setHours(0,0,0,0);
  const viewMonth = useMemo2(() => {
    const d = new Date(today.getFullYear(), today.getMonth() + monthOffset, 1);
    return d;
  }, [monthOffset]);

  const days = useMemo2(() => {
    const start = new Date(viewMonth);
    const startDow = start.getDay();
    const daysInMonth = new Date(viewMonth.getFullYear(), viewMonth.getMonth()+1, 0).getDate();
    const cells = [];
    for (let i = 0; i < startDow; i++) {
      const d = new Date(viewMonth);
      d.setDate(d.getDate() - (startDow - i));
      cells.push({ date: d, outside: true });
    }
    for (let i = 1; i <= daysInMonth; i++) {
      cells.push({ date: new Date(viewMonth.getFullYear(), viewMonth.getMonth(), i), outside: false });
    }
    while (cells.length % 7 !== 0) {
      const last = cells[cells.length - 1].date;
      const d = new Date(last);
      d.setDate(d.getDate() + 1);
      cells.push({ date: d, outside: true });
    }
    return cells;
  }, [viewMonth]);

  function isClosed(date) {
    const dow = date.getDay(); // 0 sun
    return dow === 0;
  }
  function isPast(date) {
    return date < today;
  }

  // Fetch real availability from Square whenever a date is picked on step 1.
  useEffect2(() => {
    if (step !== 1 || !selDate || !service) return;
    let cancelled = false;
    setSlotsLoading(true);
    setSlotsError(null);
    setSlots([]);
    setSelSlot(null);
    const y = selDate.getFullYear();
    const m = String(selDate.getMonth() + 1).padStart(2, "0");
    const d = String(selDate.getDate()).padStart(2, "0");
    const dateStr = `${y}-${m}-${d}`;
    fetch(`/api/availability?service=${encodeURIComponent(service.name)}&date=${dateStr}`)
      .then((r) => r.json().then((j) => ({ ok: r.ok, j })))
      .then(({ ok, j }) => {
        if (cancelled) return;
        if (!ok) throw new Error(j.error || "Couldn't load times");
        setSlots(j.slots || []);
      })
      .catch((e) => { if (!cancelled) setSlotsError(e.message); })
      .finally(() => { if (!cancelled) setSlotsLoading(false); });
    return () => { cancelled = true; };
  }, [step, selDate, service]);

  function fmtDate(d) {
    if (!d) return "";
    return d.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" });
  }

  function gcalLink() {
    if (!selSlot || !service) return "#";
    const start = new Date(selSlot.startAt);
    const end = new Date(start.getTime() + service.duration * 60000);
    const fmt = (d) => d.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z";
    const params = new URLSearchParams({
      action: "TEMPLATE",
      text: `Rinaldo's Barber Shop — ${service.name}`,
      dates: `${fmt(start)}/${fmt(end)}`,
      details: `Appointment with Jeff Packer at Rinaldo's Barber Shop.\nReference: ${confirmedRef}\nService: ${service.name} ($${service.price} cash / $${service.priceCard} card)\n\n${notes || ""}`,
      location: "107 S. Allen St, State College, PA 16801",
    });
    return `https://www.google.com/calendar/render?${params.toString()}`;
  }

  // Create the real booking in Square, then advance to the confirmation step.
  async function submitBooking() {
    if (submitting) return;
    setSubmitting(true);
    setSubmitError(null);
    try {
      const resp = await fetch("/api/book", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          service: service.name,
          startAt: selSlot.startAt,
          teamMemberId: selSlot.teamMemberId,
          name, phone, email, notes,
        }),
      });
      const data = await resp.json();
      if (!resp.ok || !data.ok) throw new Error(data.error || "Booking failed. Please try again.");
      setConfirmedRef(data.bookingId ? "RNB-" + data.bookingId.slice(-6).toUpperCase() : "RNB-" + Math.floor(Math.random()*9000+1000));
      setStep(3);
    } catch (e) {
      setSubmitError(e.message);
    } finally {
      setSubmitting(false);
    }
  }

  const canNextFromStep0 = !!service;
  const canNextFromStep1 = !!selSlot;
  const canConfirm = !!name && !!phone;

  const tabs = ["Service", "Date & Time", "Your Info", "Confirm"];

  function reset() {
    setStep(0); setService(null); setSelDate(null); setSelSlot(null);
    setSlots([]); setSlotsError(null); setSubmitError(null);
    setName(""); setPhone(""); setEmail(""); setNotes("");
  }

  return (
    <section className="booking" id="booking">
      <div className="container">
        <div className="section-header">
          <span className="eyebrow">Reserve Your Chair</span>
          <h2>Book an Appointment</h2>
          <span className="script-sub">or just walk on in</span>
          <div className="underline" />
        </div>
        <div className="booking-card">
          <div className="booking-tabs">
            {tabs.map((t, i) => (
              <div className={`booking-tab ${step === i ? "active" : ""} ${step > i ? "complete" : ""}`} key={i}>
                <span className="num">{step > i ? "✓" : i + 1}</span>{t}
              </div>
            ))}
          </div>
          <div className="booking-body">
            {step === 0 && (
              <div className="booking-step">
                <h3>What'll It Be?</h3>
                <span className="script">pick your service</span>
                <div className="svc-options">
                  {SERVICES.map((s) => (
                    <button
                      key={s.id}
                      className={`svc-option ${service?.id === s.id ? "selected" : ""}`}
                      onClick={() => setService(s)}
                    >
                      <div>
                        <div className="name">{s.name}</div>
                        <div className="meta">{s.desc} · ~{s.duration} min</div>
                      </div>
                      <div className="price">${s.price}</div>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {step === 1 && (
              <div className="booking-step">
                <h3>Pick a Day & Time</h3>
                <span className="script">we're open six days a week</span>
                <div className="cal-grid">
                  <div className="cal-month">
                    <div className="cal-header">
                      <div className="month">
                        {viewMonth.toLocaleString("en-US", { month: "long", year: "numeric" })}
                      </div>
                      <div className="cal-nav">
                        <button onClick={() => setMonthOffset(Math.max(0, monthOffset - 1))} disabled={monthOffset === 0}>‹</button>
                        <button onClick={() => setMonthOffset(monthOffset + 1)}>›</button>
                      </div>
                    </div>
                    <div className="cal-grid-days">
                      {["S","M","T","W","T","F","S"].map((d, i) => (
                        <div className="dow" key={i}>{d}</div>
                      ))}
                      {days.map((c, i) => {
                        const closed = isClosed(c.date);
                        const past = isPast(c.date);
                        const sel = selDate && c.date.toDateString() === selDate.toDateString();
                        const isToday = c.date.toDateString() === new Date().toDateString();
                        return (
                          <button
                            key={i}
                            className={`cal-day ${c.outside ? "outside" : ""} ${sel ? "selected" : ""} ${isToday ? "today" : ""}`}
                            disabled={c.outside || closed || past}
                            onClick={() => { setSelDate(c.date); setSelSlot(null); }}
                          >
                            {c.date.getDate()}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                  <div className="cal-times">
                    <div className="cal-times-header">
                      Available Times
                      <span className="date">{selDate ? fmtDate(selDate) : "select a date"}</span>
                    </div>
                    <div className="time-slots">
                      {!selDate && <div className="time-slot-empty">PICK A DATE TO SEE TIMES</div>}
                      {selDate && slotsLoading && <div className="time-slot-empty">LOADING TIMES…</div>}
                      {selDate && !slotsLoading && slotsError && <div className="time-slot-empty">COULDN'T LOAD TIMES — TRY AGAIN</div>}
                      {selDate && !slotsLoading && !slotsError && slots.length === 0 && <div className="time-slot-empty">NO TIMES AVAILABLE</div>}
                      {selDate && !slotsLoading && !slotsError && slots.map((t, i) => (
                        <button
                          key={i}
                          className={`time-slot ${selSlot && selSlot.startAt === t.startAt ? "selected" : ""}`}
                          onClick={() => setSelSlot(t)}
                        >
                          {t.time}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="booking-step">
                <h3>Your Details</h3>
                <span className="script">just so we know who's coming in</span>
                <div className="bk-form">
                  <div className="bk-row">
                    <div className="bk-field">
                      <label>Name *</label>
                      <input value={name} onChange={(e) => setName(e.target.value)} placeholder="John Smith" />
                    </div>
                    <div className="bk-field">
                      <label>Phone *</label>
                      <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="(814) 555-0123" />
                    </div>
                  </div>
                  <div className="bk-field">
                    <label>Email</label>
                    <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="for the calendar invite" />
                  </div>
                  <div className="bk-field">
                    <label>Anything we should know?</label>
                    <textarea rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="First-time visitor, picky about sideburns, etc." />
                  </div>
                </div>
                <div className="bk-summary">
                  <h4>YOUR APPOINTMENT</h4>
                  <div className="row"><span>Service</span><span>{service?.name}</span></div>
                  <div className="row"><span>Date</span><span>{fmtDate(selDate)}</span></div>
                  <div className="row"><span>Time</span><span>{selSlot ? selSlot.time : ""}</span></div>
                  <div className="row"><span>Barber</span><span>Jeff Packer</span></div>
                  <div className="row"><span>TOTAL</span><span>${service?.price} cash · ${service?.priceCard} card</span></div>
                </div>
                {submitError && (
                  <div style={{marginTop:14, padding:"10px 14px", background:"#fdecea", color:"#a12", borderRadius:6, fontSize:14}}>
                    {submitError}
                  </div>
                )}
              </div>
            )}

            {step === 3 && (
              <div className="bk-confirm">
                <div className="stamp">CONFIRMED</div>
                <h3>You're In.</h3>
                <span className="script-sub">we'll see you in the chair</span>
                <p>
                  Your appointment is booked with Jeff{email ? ` — a confirmation is on its way to ${email}` : ""}. Square will text {phone || "you"} a
                  reminder before your visit. Walk in five minutes early so we can get you settled.
                </p>
                <div className="receipt">
                  <h4>RECEIPT · {confirmedRef}</h4>
                  <div className="row"><b>WHO</b><span>{name}</span></div>
                  <div className="row"><b>WHAT</b><span>{service?.name}</span></div>
                  <div className="row"><b>WHEN</b><span>{fmtDate(selDate)}</span></div>
                  <div className="row"><b>TIME</b><span>{selSlot ? selSlot.time : ""}</span></div>
                  <div className="row"><b>WHERE</b><span>107 S. Allen St.</span></div>
                  <div className="row"><b>BARBER</b><span>Jeff Packer</span></div>
                </div>
                <div className="actions">
                  <a href={gcalLink()} target="_blank" rel="noopener" className="btn btn-blue">
                    📅 Add to Google Calendar
                  </a>
                  <button className="btn btn-cream" onClick={reset}>Book Another</button>
                </div>
              </div>
            )}
          </div>

          {step < 3 && (
            <div className="booking-footer">
              <div className="summary-mini">
                {service && <span>SERVICE: <b>{service.name}</b></span>}
                {selDate && <span style={{marginLeft: 18}}>DATE: <b>{selDate.toLocaleDateString("en-US",{month:"short",day:"numeric"})}</b></span>}
                {selSlot && <span style={{marginLeft: 18}}>TIME: <b>{selSlot.time}</b></span>}
                {!service && <span style={{opacity:0.5}}>NO SERVICE SELECTED YET</span>}
              </div>
              <div style={{display:"flex", gap: 12}}>
                {step > 0 && <button className="btn btn-cream btn-sm" onClick={() => setStep(step - 1)}>← Back</button>}
                {step === 0 && <button className="btn btn-sm" disabled={!canNextFromStep0} onClick={() => setStep(1)} style={!canNextFromStep0?{opacity:0.4,pointerEvents:"none"}:{}}>Next →</button>}
                {step === 1 && <button className="btn btn-sm" disabled={!canNextFromStep1} onClick={() => setStep(2)} style={!canNextFromStep1?{opacity:0.4,pointerEvents:"none"}:{}}>Next →</button>}
                {step === 2 && <button className="btn btn-sm" disabled={!canConfirm || submitting} onClick={submitBooking} style={(!canConfirm||submitting)?{opacity:0.4,pointerEvents:"none"}:{}}>{submitting ? "Booking…" : "Confirm Booking →"}</button>}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

window.Booking = Booking;
