/* Google Calendar booking modal — fake but realistic flow */
const { useState, useMemo } = React;

const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const DOW = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];

function buildMonth(year, month) {
  const first = new Date(year, month, 1);
  const startDay = first.getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < startDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);
  return cells;
}

function BookingModal({ onClose }) {
  // anchor "today" in the prototype
  const today = new Date(2026, 4, 1); // May 1 2026
  const [view, setView] = useState({ y: today.getFullYear(), m: today.getMonth() });
  const [selectedDay, setSelectedDay] = useState(5); // pre-pick May 5
  const [selectedSlot, setSelectedSlot] = useState(null);
  const [stage, setStage] = useState("pick"); // pick | confirm | done
  const [form, setForm] = useState({ name: "", email: "", company: "", notes: "" });

  const cells = useMemo(() => buildMonth(view.y, view.m), [view]);

  const slotsByDay = {
    5: [{ t: "9:30 AM" }, { t: "10:00 AM" }, { t: "11:30 AM" }, { t: "2:00 PM" }, { t: "3:30 PM" }],
    6: [{ t: "9:00 AM" }, { t: "10:30 AM" }, { t: "1:00 PM" }, { t: "2:30 PM" }, { t: "4:00 PM" }],
    7: [{ t: "9:30 AM" }, { t: "11:00 AM" }, { t: "1:30 PM" }, { t: "3:00 PM" }],
    8: [{ t: "10:00 AM" }, { t: "11:30 AM" }, { t: "2:00 PM" }],
    11: [{ t: "9:00 AM" }, { t: "10:30 AM" }, { t: "12:00 PM" }, { t: "2:30 PM" }, { t: "4:00 PM" }],
    12: [{ t: "9:30 AM" }, { t: "11:00 AM" }, { t: "1:00 PM" }, { t: "3:30 PM" }],
    13: [{ t: "10:00 AM" }, { t: "11:30 AM" }, { t: "2:00 PM" }, { t: "3:30 PM" }],
    14: [{ t: "9:00 AM" }, { t: "10:30 AM" }, { t: "1:00 PM" }, { t: "2:30 PM" }, { t: "4:00 PM" }],
    15: [{ t: "9:30 AM" }, { t: "11:00 AM" }, { t: "1:30 PM" }],
    18: [{ t: "9:00 AM" }, { t: "10:30 AM" }, { t: "12:00 PM" }, { t: "2:00 PM" }, { t: "3:30 PM" }],
    19: [{ t: "9:30 AM" }, { t: "11:00 AM" }, { t: "1:00 PM" }, { t: "3:00 PM" }],
    20: [{ t: "10:00 AM" }, { t: "11:30 AM" }, { t: "2:30 PM" }, { t: "4:00 PM" }],
  };

  const slots = slotsByDay[selectedDay] || [];

  function shiftMonth(d) {
    const nm = view.m + d;
    const ny = view.y + Math.floor(nm / 12);
    setView({ y: ny, m: ((nm % 12) + 12) % 12 });
    setSelectedDay(null);
    setSelectedSlot(null);
  }

  function submit(e) {
    e.preventDefault();
    if (!form.name || !form.email) return;
    setStage("done");
  }

  return (
    <div className="modal-bg" onClick={(e) => { if (e.target.className === "modal-bg") onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <aside className="modal-side">
          <div className="gcal"><span className="gcal-dot"/>Powered by Google Calendar</div>
          <h3>Book a 20-min intro call</h3>
          <div className="meta">
            <div className="row">
              <Icon name="clock"/> 20 minutes
            </div>
            <div className="row">
              <Icon name="video"/> Google Meet (auto-generated)
            </div>
            <div className="row">
              <Icon name="globe"/> America / Los Angeles · GMT-7
            </div>
            <div className="row">
              <Icon name="user"/> with Shiv, Founder
            </div>
          </div>
          <div style={{marginTop:"auto", fontFamily:"var(--mono)", fontSize:11, color:"var(--ink-dim)", lineHeight:1.6}}>
            We'll look at your current missed call volume, identify where leads drop off, and show how Pronto works with your phone number live. No deck.
          </div>
          <button onClick={onClose} style={{
            position:"absolute", top:14, right:14,
            width:30, height:30, borderRadius:999,
            border:"1px solid var(--line)",
            display:"flex", alignItems:"center", justifyContent:"center"
          }} aria-label="Close">×</button>
        </aside>

        <div className="modal-main">
          {stage === "pick" && (
            <>
              <div className="step-h">Step 1 of 2 — Pick a time</div>
              <div className="cal-grid">
                <div>
                  <div className="cal-month-head">
                    <div className="m">{MONTHS[view.m]} {view.y}</div>
                    <div className="nav-btns">
                      <button onClick={() => shiftMonth(-1)}>‹</button>
                      <button onClick={() => shiftMonth(1)}>›</button>
                    </div>
                  </div>
                  <div className="cal-days">
                    {DOW.map(d => <div key={d} className="cal-day-h">{d}</div>)}
                    {cells.map((d, i) => {
                      if (!d) return <div key={i} className="cal-day muted"/>;
                      const has = !!slotsByDay[d];
                      const sel = d === selectedDay;
                      const muted = !has;
                      return (
                        <div key={i}
                          className={`cal-day ${has ? "has" : "muted"} ${sel ? "sel" : ""}`}
                          onClick={() => has && setSelectedDay(d)}>
                          {d}
                        </div>
                      );
                    })}
                  </div>
                </div>

                <div>
                  <div className="cal-month-head">
                    <div className="m">
                      {selectedDay ? `${DOW[(new Date(view.y, view.m, selectedDay)).getDay()]}, ${MONTHS[view.m]} ${selectedDay}` : "Pick a day"}
                    </div>
                  </div>
                  <div className="slot-list">
                    {slots.length === 0 && (
                      <div style={{fontSize:13, color:"var(--ink-dim)", padding:"8px 0"}}>
                        Select a day with availability (dot) on the left.
                      </div>
                    )}
                    {slots.map((s) => (
                      <div key={s.t}
                        className={`slot ${selectedSlot === s.t ? "sel" : ""}`}
                        onClick={() => setSelectedSlot(s.t)}>
                        <span>{s.t}</span>
                        <span className="tz">PT</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </>
          )}

          {stage === "confirm" && (
            <>
              <div className="step-h">Step 2 of 2 — Your details</div>
              <div style={{
                fontFamily:"var(--mono)", fontSize:12, color:"var(--ink-dim)",
                padding:"10px 14px", border:"1px solid var(--line)", borderRadius:10, marginBottom:18
              }}>
                {DOW[(new Date(view.y, view.m, selectedDay)).getDay()]}, {MONTHS[view.m]} {selectedDay} at {selectedSlot} PT · 20 min · Google Meet
              </div>
              <form className="confirm-form" onSubmit={submit}>
                <div>
                  <label>Full name *</label>
                  <input value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="Jane Doe" required/>
                </div>
                <div>
                  <label>Work email *</label>
                  <input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} placeholder="jane@yourbusiness.com" required/>
                </div>
                <div>
                  <label>Business / website</label>
                  <input value={form.company} onChange={e => setForm({...form, company: e.target.value})} placeholder="Glow Med Spa, glowmedspa.com"/>
                </div>
                <div>
                  <label>What's your biggest intake bottleneck?</label>
                  <textarea value={form.notes} onChange={e => setForm({...form, notes: e.target.value})} placeholder="e.g. We get ~40 form fills a week and miss most of them after hours…"/>
                </div>
              </form>
            </>
          )}

          {stage === "done" && (
            <div className="success">
              <div className="check">✓</div>
              <h3>You're booked.</h3>
              <p>
                A Google Calendar invite is on its way to <strong style={{color:"var(--ink)"}}>{form.email || "you"}</strong>.<br/>
                Reply STOP anytime — we hate noisy inboxes too.
              </p>
              <div style={{marginTop:32, fontFamily:"var(--mono)", fontSize:11, color:"var(--ink-dim)", letterSpacing:".1em"}}>
                EVENT ID · LR-{Math.random().toString(36).slice(2,8).toUpperCase()}
              </div>
            </div>
          )}
        </div>

        <div className="modal-foot">
          <div className="legend">
            {stage === "pick" && "Times shown in your timezone · 20-min slots"}
            {stage === "confirm" && "We'll email you a Google Meet link instantly"}
            {stage === "done" && "Confirmation sent · Add to your calendar"}
          </div>
          <div style={{display:"flex", gap:8}}>
            {stage === "confirm" && (
              <button className="btn btn-ghost" style={{padding:"10px 16px"}} onClick={() => setStage("pick")}>Back</button>
            )}
            {stage === "pick" && (
              <button className="btn btn-primary"
                style={{padding:"10px 18px", opacity: selectedSlot ? 1 : 0.4, pointerEvents: selectedSlot ? "auto" : "none"}}
                onClick={() => setStage("confirm")}>
                Continue <span className="arrow">→</span>
              </button>
            )}
            {stage === "confirm" && (
              <button className="btn btn-primary" style={{padding:"10px 18px"}}
                onClick={submit} disabled={!form.name || !form.email}>
                Confirm booking <span className="arrow">→</span>
              </button>
            )}
            {stage === "done" && (
              <button className="btn btn-primary" style={{padding:"10px 18px"}} onClick={onClose}>
                Done
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function Icon({ name }) {
  const common = { width: 14, height: 14, fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" };
  if (name === "clock") return <svg {...common} viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
  if (name === "video") return <svg {...common} viewBox="0 0 24 24"><rect x="3" y="6" width="13" height="12" rx="2"/><path d="M16 10l5-3v10l-5-3"/></svg>;
  if (name === "globe") return <svg {...common} viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>;
  if (name === "user") return <svg {...common} viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>;
  return null;
}

window.BookingModal = BookingModal;
window.IconSvg = Icon;
