// page-book.jsx — Meeting booking calendar

/* ── Mini calendar ────────────────────────────────────────────── */
function BookingCalendar({ date, onSelect }) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const [viewYear,  setViewYear]  = React.useState(date ? date.getFullYear()  : today.getFullYear());
  const [viewMonth, setViewMonth] = React.useState(date ? date.getMonth()     : today.getMonth());

  const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  const DAYS   = ['Su','Mo','Tu','We','Th','Fr','Sa'];

  const maxDate = new Date(today);
  maxDate.setMonth(maxDate.getMonth() + 3);

  const goMonth = (dir) => {
    let m = viewMonth + dir, y = viewYear;
    if (m < 0)  { m = 11; y--; }
    if (m > 11) { m = 0;  y++; }
    setViewYear(y); setViewMonth(m);
  };

  const canPrev = (viewYear > today.getFullYear()) || (viewYear === today.getFullYear() && viewMonth > today.getMonth());
  const firstDow    = new Date(viewYear, viewMonth, 1).getDay();
  const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate();

  return (
    <div className="book-cal">
      <div className="book-cal-nav">
        <button className="book-cal-arrow" onClick={() => goMonth(-1)} disabled={!canPrev}>←</button>
        <span className="book-cal-title">{MONTHS[viewMonth]} {viewYear}</span>
        <button className="book-cal-arrow" onClick={() => goMonth(1)}>→</button>
      </div>
      <div className="book-cal-grid">
        {DAYS.map(d => <div key={d} className="book-cal-dow">{d}</div>)}
        {Array.from({ length: firstDow }, (_, i) => <div key={`e${i}`} />)}
        {Array.from({ length: daysInMonth }, (_, i) => {
          const d       = new Date(viewYear, viewMonth, i + 1);
          const isPast  = d < today;
          const isSun   = d.getDay() === 0;
          const isFar   = d > maxDate;
          const disabled = isPast || isSun || isFar;
          const isSel   = date && d.toDateString() === date.toDateString();
          const isToday = d.toDateString() === today.toDateString();
          return (
            <button
              key={i}
              className={`book-cal-day${disabled ? ' dis' : ''}${isSel ? ' sel' : ''}${isToday ? ' today' : ''}`}
              disabled={disabled}
              onClick={() => onSelect(d)}
            >
              {i + 1}
            </button>
          );
        })}
      </div>
      <p className="book-cal-note">Mon – Sat · 10 AM – 7 PM IST</p>
    </div>
  );
}

/* ── Main booking page ────────────────────────────────────────── */
function BookingPage() {
  const [step,       setStep]       = React.useState(1);
  const [duration,   setDuration]   = React.useState(null);
  const [selDate,    setSelDate]    = React.useState(null);
  const [selSlot,    setSelSlot]    = React.useState(null);
  const [slots,      setSlots]      = React.useState([]);
  const [loadingSlots, setLoadingSlots] = React.useState(false);
  const [slotsErr,   setSlotsErr]   = React.useState(null);
  const [form,       setForm]       = React.useState({ name: '', email: '', note: '' });
  const [formErr,    setFormErr]    = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);
  const [submitErr,  setSubmitErr]  = React.useState(null);
  const [confirmed,  setConfirmed]  = React.useState(null);

  const API = (window.BOOKING_API_URL || '').replace(/\/$/, '');

  /* ── Helpers ── */
  const fmtISO = (d) => {
    if (!d) return '';
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
  };

  const fmtTime = (iso) => {
    if (!iso) return '';
    return new Date(iso).toLocaleTimeString('en-IN', {
      hour: 'numeric', minute: '2-digit', hour12: true, timeZone: 'Asia/Kolkata'
    });
  };

  const fmtDateLong = (d) => {
    if (!d) return '';
    return d.toLocaleDateString('en-IN', {
      weekday: 'long', day: 'numeric', month: 'long', year: 'numeric'
    });
  };

  /* ── Fetch slots when date or duration changes ── */
  React.useEffect(() => {
    if (!selDate || !duration) return;
    setLoadingSlots(true);
    setSlotsErr(null);
    setSelSlot(null);
    setSlots([]);

    fetch(`${API}/api/booking.php?action=slots&date=${fmtISO(selDate)}&duration=${duration}`)
      .then(r => { if (!r.ok) throw new Error('server'); return r.json(); })
      .then(data => { setSlots(data.slots || []); setLoadingSlots(false); })
      .catch(() => { setSlotsErr('Could not load available times. Please try again.'); setLoadingSlots(false); });
  }, [selDate, duration]);

  /* ── Handlers ── */
  const pickDuration = (d) => { setDuration(d); setSelSlot(null); setStep(2); };
  const pickDate     = (d) => { setSelDate(d); setSelSlot(null); };
  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const validate = () => {
    const e = {};
    if (!form.name.trim())        e.name  = 'Required';
    if (!form.email.includes('@')) e.email = 'Valid email required';
    return e;
  };

  const submitBooking = async (e) => {
    e.preventDefault();
    const errs = validate();
    setFormErr(errs);
    if (Object.keys(errs).length > 0) return;
    setSubmitting(true);
    setSubmitErr(null);
    try {
      const res  = await fetch(`${API}/api/booking.php`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: form.name.trim(), email: form.email.trim(), note: form.note.trim(), start: selSlot.start, end: selSlot.end, duration })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Booking failed');
      setConfirmed(data);
      setStep(4);
    } catch (err) {
      setSubmitErr(err.message || 'Something went wrong. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  /* ── Duration options ── */
  const DURATIONS = [
    { mins: 15, label: 'Quick Chat',   icon: '⚡' },
    { mins: 30, label: 'Consultation', icon: '☕' },
    { mins: 60, label: 'Full Meeting', icon: '📋' },
  ];

  /* ── Step labels ── */
  const STEPS = ['Duration', 'Date & Time', 'Your Details'];

  /* ── Confirmation screen ── */
  if (step === 4 && confirmed) {
    return (
      <div className="page">
        <div className="page-head">
          <div className="wrap">
            <h1>You&rsquo;re <span className="it">booked.</span></h1>
            <p className="deck">
              A calendar invite with the Google Meet link has been sent to your inbox. We look forward to speaking with you.
            </p>
          </div>
        </div>
        <section style={{ paddingTop: 60 }}>
          <div className="wrap">
            <Reveal className="book-confirm">
              <div className="book-confirm-check">
                <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
                  <circle cx="20" cy="20" r="20" fill="var(--accent)" />
                  <path d="M11 20l6.5 6.5L29 14" stroke="var(--accent-ink)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                <div>
                  <h2 style={{ fontSize: 28, margin: 0 }}>Meeting confirmed</h2>
                  <p style={{ color: 'var(--muted)', margin: '4px 0 0', fontSize: 15 }}>Check your inbox for the calendar invite.</p>
                </div>
              </div>

              <div className="book-confirm-details">
                {[
                  ['With',     'Satnam Singh · Harjog Solutions'],
                  ['Date',     fmtDateLong(selDate)],
                  ['Time',     `${fmtTime(selSlot && selSlot.start)} IST · ${duration} min`],
                  ['For',      `${form.name} · ${form.email}`],
                ].map(([label, val]) => (
                  <div className="book-confirm-row" key={label}>
                    <span className="book-confirm-label">{label}</span>
                    <span className="book-confirm-val">{val}</span>
                  </div>
                ))}
              </div>

              {confirmed.meetLink && (
                <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
                  <a href={confirmed.meetLink} target="_blank" rel="noopener"
                     className="btn btn-primary" style={{ display: 'inline-flex' }}>
                    Join Google Meet <Arrow size={13} />
                  </a>
                  <a href="contact.html" className="btn" style={{ display: 'inline-flex' }}>
                    Back to site
                  </a>
                </div>
              )}
            </Reveal>
          </div>
        </section>
      </div>
    );
  }

  return (
    <div className="page">
      <div className="page-head">
        <div className="wrap">
          <h1><TypeReveal>Book a <span className="it">meeting.</span></TypeReveal></h1>
          <p className="deck">
            Schedule time directly on Satnam&rsquo;s calendar. Every booking includes a Google Meet link sent to your inbox.
          </p>
        </div>
      </div>

      {/* ── Step indicator ── */}
      <div className="wrap">
        <div className="book-steps">
          {STEPS.map((s, i) => (
            <div key={s} className={`book-step${step === i + 1 ? ' active' : ''}${step > i + 1 ? ' done' : ''}`}>
              <span className="book-step-num">{step > i + 1 ? '✓' : i + 1}</span>
              <span className="book-step-label">{s}</span>
            </div>
          ))}
        </div>
      </div>

      {/* ── Step 1: Duration ── */}
      {step === 1 && (
        <section style={{ paddingTop: 48 }}>
          <div className="wrap">
            <p className="eyebrow" style={{ marginBottom: 36 }}>Choose meeting type</p>
            <div className="book-dur-grid">
              {DURATIONS.map((d, i) => (
                <Reveal key={d.mins} delay={i * 80} as="button"
                  className={`book-dur-card${duration === d.mins ? ' sel' : ''}`}
                  onClick={() => pickDuration(d.mins)}>
                  <span className="book-dur-icon">{d.icon}</span>
                  <span className="book-dur-mins">{d.mins}</span>
                  <span className="book-dur-unit">minutes</span>
                  <span className="book-dur-label">{d.label}</span>
                </Reveal>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* ── Step 2: Date & Time ── */}
      {step === 2 && (
        <section style={{ paddingTop: 48 }}>
          <div className="wrap">
            <div className="book-dt-layout">

              <div>
                <p className="eyebrow" style={{ marginBottom: 24 }}>Choose a date</p>
                <BookingCalendar date={selDate} onSelect={pickDate} />
              </div>

              <div className="book-slots-panel">
                {!selDate ? (
                  <div className="book-slots-empty">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>
                    <span>Select a date to see available times</span>
                  </div>
                ) : (
                  <>
                    <p className="eyebrow" style={{ marginBottom: 24 }}>{fmtDateLong(selDate)}</p>
                    {loadingSlots && <div className="book-slots-loading">Loading available times…</div>}
                    {slotsErr     && <div className="book-slots-err">{slotsErr}</div>}
                    {!loadingSlots && !slotsErr && slots.length === 0 && (
                      <div className="book-slots-empty">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
                        <span>No slots available on this day. Try another date.</span>
                      </div>
                    )}
                    {!loadingSlots && !slotsErr && slots.length > 0 && (
                      <div className="book-slots-grid">
                        {slots.map(s => (
                          <button key={s.start}
                            className={`book-slot${selSlot && selSlot.start === s.start ? ' sel' : ''}`}
                            onClick={() => setSelSlot(s)}>
                            {s.label}
                          </button>
                        ))}
                      </div>
                    )}
                  </>
                )}
              </div>
            </div>

            <div className="book-step-nav">
              <button className="btn" onClick={() => setStep(1)}>← Back</button>
              <button className="btn btn-primary" disabled={!selSlot} onClick={() => setStep(3)}>
                Continue <Arrow size={13} />
              </button>
            </div>
          </div>
        </section>
      )}

      {/* ── Step 3: Details ── */}
      {step === 3 && (
        <section style={{ paddingTop: 48 }}>
          <div className="wrap">
            <div className="book-form-layout">
              <form className="form" onSubmit={submitBooking} noValidate>
                <p className="eyebrow" style={{ marginBottom: 32 }}>Your details</p>

                <div className="field">
                  <label>
                    Full name
                    {formErr.name && <span style={{ color: 'var(--accent)', fontFamily: 'var(--f-sans)', textTransform: 'none', letterSpacing: 0, fontWeight: 400 }}> · {formErr.name}</span>}
                  </label>
                  <input type="text" value={form.name} onChange={update('name')} placeholder="Your full name" autoFocus />
                </div>

                <div className="field">
                  <label>
                    Email address
                    {formErr.email && <span style={{ color: 'var(--accent)', fontFamily: 'var(--f-sans)', textTransform: 'none', letterSpacing: 0, fontWeight: 400 }}> · {formErr.email}</span>}
                  </label>
                  <input type="email" value={form.email} onChange={update('email')} placeholder="you@company.com" />
                </div>

                <div className="field">
                  <label>
                    What would you like to discuss?
                    <span style={{ color: 'var(--muted)', fontFamily: 'var(--f-sans)', textTransform: 'none', letterSpacing: 0, fontWeight: 400 }}> (optional)</span>
                  </label>
                  <textarea value={form.note} onChange={update('note')} style={{ minHeight: 96 }}
                    placeholder="Brief context — the more you share, the more useful our call will be." />
                </div>

                {submitErr && (
                  <p style={{ fontFamily: 'var(--f-mono)', fontSize: 12, color: 'var(--accent)', margin: '0 0 8px' }}>
                    ⚠ {submitErr}
                  </p>
                )}

                <div className="book-step-nav">
                  <button type="button" className="btn" onClick={() => setStep(2)}>← Back</button>
                  <button type="submit" className="btn btn-primary" disabled={submitting}>
                    {submitting ? 'Booking…' : <>Confirm booking <Arrow size={13} /></>}
                  </button>
                </div>
              </form>

              <aside className="book-summary">
                <p className="eyebrow" style={{ marginBottom: 20 }}>Your booking</p>
                <dl className="book-summary-list">
                  <dt>Duration</dt>
                  <dd>{duration} minutes</dd>
                  <dt>Date</dt>
                  <dd>{fmtDateLong(selDate)}</dd>
                  <dt>Time</dt>
                  <dd>{fmtTime(selSlot && selSlot.start)} IST</dd>
                  <dt>With</dt>
                  <dd>
                    Satnam Singh
                    <br />
                    <span style={{ color: 'var(--muted)', fontSize: 13 }}>Harjog Solutions</span>
                  </dd>
                  <dt>Via</dt>
                  <dd>
                    Google Meet
                    <br />
                    <span style={{ color: 'var(--muted)', fontSize: 12 }}>Link sent on confirmation</span>
                  </dd>
                </dl>
              </aside>
            </div>
          </div>
        </section>
      )}
    </div>
  );
}

Object.assign(window, { BookingPage });
