// Facette — Modals (Book, Skin Quiz, Lightbox)

const { BRANCHES: B_DATA, THERAPISTS, QUIZ_STEPS, recommend, SIGNATURES, TREATMENT_CATEGORIES } = window.FacetteData;

const ALL_TREATMENTS = TREATMENT_CATEGORIES.flatMap((c) => c.items);

// ──────────────────────────────────────────────────────────
// Generic modal scrim
// ──────────────────────────────────────────────────────────
function Modal({ onClose, children, wide }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" style={ wide ? { maxWidth: 1000 } : null } onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        {children}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Lightbox
// ──────────────────────────────────────────────────────────
function Lightbox({ src, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div className="lightbox-scrim" onClick={onClose}>
      <img src={src} className="lightbox-img" alt="" />
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Booking modal
// ──────────────────────────────────────────────────────────
function BookModal({ branch, treatment, onClose, onBranchChange }) {
  const b = B_DATA[branch];
  const [step, setStep] = React.useState(treatment ? 1 : 0);
  // Resolve treatment to full record if needed
  const resolvedTreatment = React.useMemo(() => {
    if (!treatment) return null;
    const found = ALL_TREATMENTS.find((t) => t.name === treatment.name || t.slug === treatment.slug);
    return found || treatment;
  }, [treatment]);
  const [pickedTreatment, setPickedTreatment] = React.useState(resolvedTreatment);
  const [therapist, setTherapist] = React.useState(null);
  const [date, setDate] = React.useState(null);
  const [time, setTime] = React.useState(null);

  const eligibleTherapists = THERAPISTS.filter((t) => t.branches.includes(branch) && t.role !== 'GP & Aesthetics');

  // Build a fake date set (next 7 days)
  const dates = React.useMemo(() => {
    const arr = [];
    const today = new Date('2026-05-22');
    for (let i = 0; i < 7; i++) {
      const d = new Date(today);
      d.setDate(today.getDate() + i);
      arr.push({
        iso: d.toISOString().slice(0, 10),
        label: d.toLocaleDateString('en-GB', { weekday: 'short' }),
        day: d.getDate(),
        month: d.toLocaleDateString('en-GB', { month: 'short' }),
      });
    }
    return arr;
  }, []);

  const times = ['10:00', '11:30', '13:00', '14:30', '16:00', '17:30', '19:00'];
  // Make a couple slots "booked" based on date hash
  const unavailable = (d, t) => {
    const seed = (d.charCodeAt(d.length - 1) + t.charCodeAt(0)) % 7;
    return seed === 0 || seed === 3;
  };

  return (
    <Modal onClose={onClose} wide>
      <div className="book">
        <BookSide branch={branch} b={b} treatment={pickedTreatment} step={step} />
        <div className="book-body">
          {step === 0 && (
            <PickTreatment
              onPick={(t) => { setPickedTreatment(t); setStep(1); }}
              branch={branch}
              onBranchChange={onBranchChange}
            />
          )}
          {step === 1 && (
            <PickTherapist
              therapists={eligibleTherapists}
              selected={therapist}
              onSelect={setTherapist}
              onNext={() => setStep(2)}
              onBack={() => setStep(0)}
            />
          )}
          {step === 2 && (
            <PickTime
              dates={dates}
              times={times}
              date={date} setDate={setDate}
              time={time} setTime={setTime}
              unavailable={unavailable}
              onBack={() => setStep(1)}
              onNext={() => setStep(3)}
            />
          )}
          {step === 3 && (
            <Confirm
              branch={branch}
              treatment={pickedTreatment}
              therapist={therapist}
              date={dates.find((d) => d.iso === date)}
              time={time}
              onBack={() => setStep(2)}
              onConfirm={() => setStep(4)}
            />
          )}
          {step === 4 && (
            <Success
              branch={branch}
              treatment={pickedTreatment}
              date={dates.find((d) => d.iso === date)}
              time={time}
              therapist={therapist}
              onClose={onClose}
            />
          )}
        </div>
      </div>
    </Modal>
  );
}

function BookSide({ branch, b, treatment, step }) {
  return (
    <div className="book-side">
      <div className="bs-bg"></div>
      <div style={{ position: 'relative' }}>
        <div className="eyebrow" style={{ color: 'var(--gold-soft)' }}>
          <span className="dot" style={{ background: 'var(--gold-soft)' }}></span>Booking · {b.short}
        </div>
        <h3>Book your<br/>facial.</h3>
        <p style={{ fontSize: 13, lineHeight: 1.6, color: 'rgba(239, 228, 214, 0.7)', marginTop: 14 }}>
          Four steps. About 90 seconds. Cancellation up to 24 hours before your slot.
        </p>
      </div>
      <div style={{ position: 'relative', marginTop: 32 }}>
        <ProgressDots step={step} total={4} />
      </div>
      {treatment && (
        <div className="bs-treat" style={{ position: 'relative' }}>
          <div className="eyebrow" style={{ color: 'rgba(239, 228, 214, 0.55)' }}>You picked</div>
          <div className="bst-name">{treatment.name}</div>
          <div className="bst-meta">
            <span>{treatment.duration}</span>
            {!treatment.tbc && <span>· {(treatment.price ?? treatment.priceFrom).toLocaleString()} AED</span>}
          </div>
        </div>
      )}
    </div>
  );
}

function ProgressDots({ step, total }) {
  const labels = ['Treatment', 'Therapist', 'Date & Time', 'Confirm'];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {labels.map((l, i) => (
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 22, height: 22, borderRadius: 999,
            border: `1px solid ${i <= step ? 'var(--gold-soft)' : 'rgba(239, 228, 214, 0.25)'}`,
            background: i < step ? 'var(--gold-soft)' : 'transparent',
            color: i < step ? 'var(--ink)' : i === step ? 'var(--gold-soft)' : 'rgba(239, 228, 214, 0.4)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 11, fontWeight: 600,
          }}>{i < step ? '✓' : i + 1}</div>
          <div style={{
            fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
            color: i === step ? '#EFE4D6' : 'rgba(239, 228, 214, 0.55)',
            fontWeight: i === step ? 600 : 500,
          }}>{l}</div>
        </div>
      ))}
    </div>
  );
}

function PickTreatment({ onPick, branch, onBranchChange }) {
  const [cat, setCat] = React.useState(TREATMENT_CATEGORIES[0].id);
  const current = TREATMENT_CATEGORIES.find((c) => c.id === cat);
  return (
    <React.Fragment>
      <h4>Pick a facial</h4>
      <p className="b-sub">Filter by category. You can change this later.</p>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 18 }}>
        {TREATMENT_CATEGORIES.map((c) => (
          <button
            key={c.id}
            onClick={() => setCat(c.id)}
            style={{
              padding: '7px 14px',
              fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase',
              fontWeight: 500,
              background: cat === c.id ? 'var(--ink)' : 'var(--bg-warm)',
              color: cat === c.id ? 'var(--bg)' : 'var(--ink-2)',
              borderRadius: 999,
            }}>
            {c.label}
          </button>
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 0, borderTop: '1px solid var(--rule)' }}>
        {current.items.map((it, i) => (
          <button key={i} onClick={() => onPick(it)} style={{
            padding: '14px 4px',
            borderBottom: '1px solid var(--rule)',
            background: 'transparent', cursor: 'pointer',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
            textAlign: 'left',
          }} onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-warm)'}
             onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
            <div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 19, lineHeight: 1.1 }}>{it.name}</div>
              <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-3)', marginTop: 4 }}>
                {it.duration}
              </div>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 400, color: 'var(--ink)' }}>
              {it.tbc ? <span style={{ fontFamily: 'var(--font-sans)', fontSize: 11, letterSpacing: '0.16em', color: 'var(--ink-3)' }}>TBC</span> :
              <>{(it.price ?? it.priceFrom).toLocaleString()}<span style={{ fontFamily: 'var(--font-sans)', fontSize: 11, color: 'var(--ink-3)', marginLeft: 4 }}>AED</span></>}
            </div>
          </button>
        ))}
      </div>
    </React.Fragment>
  );
}

function PickTherapist({ therapists, selected, onSelect, onNext, onBack }) {
  return (
    <React.Fragment>
      <h4>Pick a therapist</h4>
      <p className="b-sub">Or leave it to us — we will match by concern.</p>
      <div className="book-therapists">
        <button className={`book-therapist ${selected === '__any' ? 'selected' : ''}`} onClick={() => onSelect('__any')}>
          <div className="bt-av">★</div>
          <div className="bt-info">
            <div className="bt-name">Any therapist</div>
            <div className="bt-role">Match by concern</div>
          </div>
        </button>
        {therapists.map((t) => (
          <button
            key={t.name}
            className={`book-therapist ${selected && selected.name === t.name ? 'selected' : ''}`}
            onClick={() => onSelect(t)}>
            <div className="bt-av">{t.initial}</div>
            <div className="bt-info">
              <div className="bt-name">{t.name}</div>
              <div className="bt-role">{t.role}</div>
            </div>
          </button>
        ))}
      </div>
      <div className="quiz-actions">
        <button className="btn-ghost" onClick={onBack}>← Treatment</button>
        <button className="btn btn-primary btn-sm" onClick={onNext} disabled={!selected}
          style={{ opacity: selected ? 1 : 0.4, pointerEvents: selected ? 'auto' : 'none' }}>
          Continue →
        </button>
      </div>
    </React.Fragment>
  );
}

function PickTime({ dates, times, date, setDate, time, setTime, unavailable, onBack, onNext }) {
  return (
    <React.Fragment>
      <h4>Pick a date</h4>
      <p className="b-sub">Live availability — confirmed when you submit.</p>
      <div className="book-grid">
        {dates.map((d) => (
          <button
            key={d.iso}
            className={date === d.iso ? 'selected' : ''}
            onClick={() => { setDate(d.iso); setTime(null); }}
            style={{ flexDirection: 'column', gap: 4, display: 'flex' }}>
            <div style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.7 }}>{d.label}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 400 }}>{d.day}</div>
            <div style={{ fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.6 }}>{d.month}</div>
          </button>
        ))}
      </div>
      {date && (
        <React.Fragment>
          <h4 style={{ marginTop: 28 }}>Pick a time</h4>
          <p className="b-sub">7 slots shown. Tap a faded slot to be waitlisted.</p>
          <div className="book-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
            {times.map((t) => {
              const off = unavailable(date, t);
              return (
                <button
                  key={t}
                  className={`${time === t ? 'selected' : ''} ${off ? 'disabled' : ''}`}
                  onClick={() => { if (!off) setTime(t); }}>
                  {t}
                </button>
              );
            })}
          </div>
        </React.Fragment>
      )}
      <div className="quiz-actions">
        <button className="btn-ghost" onClick={onBack}>← Therapist</button>
        <button className="btn btn-primary btn-sm" onClick={onNext} disabled={!date || !time}
          style={{ opacity: (date && time) ? 1 : 0.4, pointerEvents: (date && time) ? 'auto' : 'none' }}>
          Review →
        </button>
      </div>
    </React.Fragment>
  );
}

function Confirm({ branch, treatment, therapist, date, time, onBack, onConfirm }) {
  const b = B_DATA[branch];
  const therapistName = therapist === '__any' ? 'Any available therapist' : therapist?.name;
  const total = treatment?.price ?? treatment?.priceFrom ?? '—';
  return (
    <React.Fragment>
      <h4>Review your booking</h4>
      <p className="b-sub">Last look before we hold the slot.</p>
      <div className="book-confirm">
        <div className="bc-row"><div className="bc-l">Branch</div><div className="bc-r">Facette · {b.short}</div></div>
        <div className="bc-row"><div className="bc-l">Treatment</div><div className="bc-r">{treatment?.name}</div></div>
        <div className="bc-row"><div className="bc-l">With</div><div className="bc-r">{therapistName}</div></div>
        <div className="bc-row"><div className="bc-l">When</div><div className="bc-r">{date?.label}, {date?.day} {date?.month} · {time}</div></div>
        <div className="bc-row"><div className="bc-l">Duration</div><div className="bc-r">{treatment?.duration}</div></div>
        <div className="bc-row bc-total"><div className="bc-l">Total</div><div className="bc-r">{typeof total === 'number' ? `${total.toLocaleString()} AED` : 'On request'}</div></div>
      </div>
      <div className="quiz-actions">
        <button className="btn-ghost" onClick={onBack}>← Date</button>
        <button className="btn btn-primary btn-sm" onClick={onConfirm}>Confirm booking</button>
      </div>
    </React.Fragment>
  );
}

function Success({ branch, treatment, date, time, therapist, onClose }) {
  const b = B_DATA[branch];
  return (
    <div className="book-success">
      <div className="bs-check">✓</div>
      <h3>You are booked.</h3>
      <p style={{ fontSize: 14, color: 'var(--ink-2)', maxWidth: '34ch', margin: '0 auto 24px' }}>
        We have sent a confirmation to your inbox. Show up five minutes early — Phia at reception has your name.
      </p>
      <div className="book-confirm" style={{ textAlign: 'left', maxWidth: 360, margin: '0 auto' }}>
        <div className="bc-row"><div className="bc-l">{treatment?.name}</div><div className="bc-r">{date?.label}, {date?.day} {date?.month} · {time}</div></div>
        <div className="bc-row"><div className="bc-l">{b.short}</div><div className="bc-r">{therapist === '__any' ? 'Therapist TBA' : therapist?.name}</div></div>
      </div>
      <button className="btn btn-primary" style={{ marginTop: 24 }} onClick={onClose}>Done</button>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Skin Quiz modal
// ──────────────────────────────────────────────────────────
function QuizModal({ onClose, onBook }) {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState([]);

  const total = QUIZ_STEPS.length;
  const onSelect = (val) => {
    const next = [...answers];
    next[step] = val;
    setAnswers(next);
  };
  const onNext = () => {
    if (step < total) setStep(step + 1);
  };
  const onBack = () => {
    if (step > 0) setStep(step - 1);
  };

  const done = step === total;
  const rec = done ? recommend(answers) : null;
  const recTreatment = rec ? ALL_TREATMENTS.find((t) => t.slug === rec.slug) : null;

  return (
    <Modal onClose={onClose} wide>
      <div className="quiz" style={{ display: 'flex', flexDirection: 'row' }}>
        <div className="quiz-side">
          <Img src="media/section-take-the-quiz.webp" alt="Skin quiz" />
        </div>
        <div className="quiz-body">
          <div className="quiz-prog">
            {Array.from({ length: total }).map((_, i) => (
              <div key={i} className={`qp ${i <= step ? 'done' : ''}`}></div>
            ))}
          </div>
          {!done && (
            <React.Fragment>
              <div className="eyebrow" style={{ marginBottom: 8 }}>Step {step + 1} of {total}</div>
              <h3>{QUIZ_STEPS[step].q}</h3>
              <p className="q-sub">{QUIZ_STEPS[step].sub}</p>
              <div className="quiz-options">
                {QUIZ_STEPS[step].options.map((o) => (
                  <button
                    key={o.val}
                    className={`quiz-option ${answers[step] === o.val ? 'selected' : ''}`}
                    onClick={() => onSelect(o.val)}>
                    <span>{o.label}</span>
                    <span className="qo-radio"></span>
                  </button>
                ))}
              </div>
              <div className="quiz-actions">
                <button className="btn-ghost" onClick={step === 0 ? onClose : onBack}>
                  {step === 0 ? 'Cancel' : '← Back'}
                </button>
                <button className="btn btn-primary btn-sm" onClick={onNext}
                  disabled={!answers[step]}
                  style={{ opacity: answers[step] ? 1 : 0.4, pointerEvents: answers[step] ? 'auto' : 'none' }}>
                  {step === total - 1 ? 'See my facial →' : 'Next →'}
                </button>
              </div>
            </React.Fragment>
          )}
          {done && recTreatment && (
            <div className="quiz-result">
              <div className="eyebrow" style={{ marginBottom: 8 }}>Based on your answers, we recommend</div>
              <h3 style={{ marginTop: 0 }}>{recTreatment.name}</h3>
              <div className="qr-rec">
                <div className="rec-eb">Why this</div>
                <div style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--ink)' }}>{rec.reason}</div>
              </div>
              <div style={{ display: 'flex', gap: 12, marginTop: 24, justifyContent: 'flex-end' }}>
                <button className="btn-ghost" onClick={() => { setStep(0); setAnswers([]); }}>Retake</button>
                <button className="btn btn-primary btn-sm" onClick={() => onBook(recTreatment)}>
                  Book {recTreatment.name} →
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
}

window.BookModal = BookModal;
window.QuizModal = QuizModal;
window.Lightbox = Lightbox;
