// appointment.jsx — multi-step private appointment booking + lookbook lightbox

const { useState, useEffect, useMemo, useRef } = React;

// ─── APPOINTMENT MODAL ───────────────────────────────────────────────────────
const STEPS = ['Atelier', 'Occasion', 'Date', 'Details', 'Confirm'];

function AppointmentModal({ open, onClose }) {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    atelier: '',
    occasion: '',
    date: null,            // { y, m, d }
    name: '',
    email: '',
    phone: '',
    message: '',
  });
  const [submitted, setSubmitted] = useState(false);
  const scrollRef = useRef(null);

  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
      // reset on close after small delay (so closing transitions feel right)
      const t = setTimeout(() => {
        setStep(0);
        setSubmitted(false);
      }, 400);
      return () => clearTimeout(t);
    }
  }, [open]);

  useEffect(() => {
    // ESC closes
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [step]);

  if (!open) return null;

  const canNext = (() => {
    if (step === 0) return !!data.atelier;
    if (step === 1) return !!data.occasion;
    if (step === 2) return !!data.date;
    if (step === 3) return data.name.trim() && /.+@.+\..+/.test(data.email);
    return true;
  })();

  const next = () => setStep((s) => Math.min(s + 1, STEPS.length - 1));
  const back = () => setStep((s) => Math.max(s - 1, 0));

  const formatDate = (d) => {
    if (!d) return '';
    const date = new Date(d.y, d.m, d.d);
    return date.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
  };

  const submit = () => {
    setSubmitted(true);
    next();
    // open mailto in new tab as a backup courtesy — non-blocking
    try {
      const body = [
        `Name: ${data.name}`,
        `Email: ${data.email}`,
        `Phone: ${data.phone}`,
        ``,
        `Atelier: ${data.atelier}`,
        `Occasion: ${data.occasion}`,
        `Preferred date: ${formatDate(data.date)}`,
        ``,
        `Message:`,
        data.message || '—',
      ].join('\n');
      const subject = `Private appointment — ${data.atelier} · ${data.occasion}`;
      const href = `mailto:lamiaabinader@hotmail.com?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
      // store on confirm button for user to copy/open
      window.__lan_mailto = href;
    } catch (e) {}
  };

  return (
    <div style={overlayStyle} role="dialog" aria-modal="true" aria-label="Book a Private Appointment">
      <div style={overlayBackdrop} onClick={onClose} />
      <div style={modalShell}>
        <button type="button" onClick={onClose} aria-label="Close" style={closeBtnStyle}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.04em' }}>Close</span>
          <span style={{ marginLeft: 10, fontSize: 18, lineHeight: 1 }}>×</span>
        </button>

        <div className="appt-card" ref={scrollRef} style={{ minHeight: 'min(720px, 92vh)', maxHeight: '92vh', overflowY: 'auto' }}>
          {/* progress */}
          <div className="appt-progress" aria-hidden="true">
            {STEPS.map((s, i) => (
              <div key={s} className={`step ${i < step ? 'done' : ''} ${i === step ? 'current' : ''}`} />
            ))}
          </div>
          <div className="appt-step-meta">
            <span>Step {Math.min(step + 1, STEPS.length)} / {STEPS.length}</span>
            <span>{STEPS[step]}</span>
          </div>

          {/* step body */}
          <div style={{ display: 'grid', gap: 28, flex: 1 }}>
            {step === 0 && <StepAtelier data={data} setData={setData} />}
            {step === 1 && <StepOccasion data={data} setData={setData} />}
            {step === 2 && <StepDate data={data} setData={setData} />}
            {step === 3 && <StepDetails data={data} setData={setData} />}
            {step === 4 && <StepConfirm data={data} formatDate={formatDate} submitted={submitted} />}
          </div>

          {/* nav */}
          {step < 4 && (
            <div className="appt-nav">
              <button
                type="button"
                onClick={back}
                disabled={step === 0}
                className="label"
                style={{ opacity: step === 0 ? 0.3 : 0.7, padding: '10px 0' }}
              >
                ← Back
              </button>
              <button
                type="button"
                className="pill pill-solid"
                onClick={step === 3 ? submit : next}
                disabled={!canNext}
                style={{ opacity: canNext ? 1 : 0.35 }}
              >
                <span>{step === 3 ? 'Send Request' : 'Continue'}</span>
                <span className="arrow">→</span>
              </button>
            </div>
          )}

          {step === 4 && (
            <div className="appt-nav">
              <button type="button" className="label" onClick={onClose} style={{ opacity: 0.7 }}>
                ← Close
              </button>
              <a
                className="pill pill-solid"
                href={window.__lan_mailto || '#'}
                onClick={(e) => { if (!window.__lan_mailto) e.preventDefault(); }}
              >
                <span>Open in Mail Client</span>
                <span className="arrow">↗</span>
              </a>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

const overlayStyle = {
  position: 'fixed', inset: 0, zIndex: 100,
  display: 'grid', placeItems: 'center',
  padding: 'clamp(12px, 4vw, 40px)',
};
const overlayBackdrop = {
  position: 'absolute', inset: 0,
  background: 'color-mix(in oklab, var(--ink) 75%, transparent)',
  backdropFilter: 'blur(8px)',
  animation: 'fadeIn 300ms ease',
};
const modalShell = {
  position: 'relative',
  width: 'min(1100px, 100%)',
  display: 'grid',
  animation: 'modalIn 500ms cubic-bezier(.2,.7,.2,1)',
};
const closeBtnStyle = {
  position: 'absolute', top: -36, right: 0,
  display: 'inline-flex', alignItems: 'center',
  color: 'rgba(255,255,255,0.9)',
  fontFamily: 'var(--sans)', fontSize: 10.5, letterSpacing: '0.22em', textTransform: 'uppercase',
  cursor: 'default',
};

// inject modal keyframes once
if (!document.getElementById('__appt_kfs')) {
  const s = document.createElement('style');
  s.id = '__appt_kfs';
  s.textContent = `
    @keyframes fadeIn { from{opacity:0} to{opacity:1} }
    @keyframes modalIn { from{opacity:0; transform: translateY(18px)} to{opacity:1; transform:none} }
    .appt-card { animation: fadeIn 400ms ease 80ms both; }
  `;
  document.head.appendChild(s);
}

// ─── STEP 1 — ATELIER ────────────────────────────────────────────────────────
const ATELIERS = [
  { id: 'Dubai', t: 'Dubai', s: 'd3 — Dubai Design District. Bridal &amp; evening fittings.', i: 'i' },
  { id: 'Beirut', t: 'Beirut', s: 'Jisr El Basha, Mkalles. The original maison.', i: 'ii' },
];
function StepAtelier({ data, setData }) {
  return (
    <>
      <h3 className="appt-q">Where would you like to be <em>seen</em>?</h3>
      <p className="appt-q-sub">Choose the atelier nearest you. Travel between Beirut and Dubai is possible on request.</p>
      <div className="opt-grid two">
        {ATELIERS.map((a) => (
          <button
            key={a.id}
            type="button"
            onClick={() => setData((d) => ({ ...d, atelier: a.id }))}
            className={`opt-card ${data.atelier === a.id ? 'is-selected' : ''}`}
          >
            <span className="opt-i">Atelier {a.i}</span>
            <span className="opt-t serif">{a.t}</span>
            <span className="opt-s" dangerouslySetInnerHTML={{ __html: a.s }} />
          </button>
        ))}
      </div>
    </>
  );
}

// ─── STEP 2 — OCCASION ───────────────────────────────────────────────────────
const OCCASIONS = [
  { id: 'Bridal', t: 'Bridal', s: 'Wedding gown, civil dress, post-ceremony look.' },
  { id: 'Evening', t: 'Evening', s: 'Gala, opera, première, state ceremony.' },
  { id: 'Other', t: 'Other', s: 'Mother of the bride, debutante, private commission.' },
];
function StepOccasion({ data, setData }) {
  return (
    <>
      <h3 className="appt-q">What is the <em>occasion</em>?</h3>
      <p className="appt-q-sub">The atelier shapes the appointment around the commission. You can change this at any time.</p>
      <div className="opt-grid three">
        {OCCASIONS.map((o, idx) => (
          <button
            key={o.id}
            type="button"
            onClick={() => setData((d) => ({ ...d, occasion: o.id }))}
            className={`opt-card ${data.occasion === o.id ? 'is-selected' : ''}`}
          >
            <span className="opt-i">N° {String(idx + 1).padStart(2, '0')}</span>
            <span className="opt-t serif">{o.t}</span>
            <span className="opt-s">{o.s}</span>
          </button>
        ))}
      </div>
    </>
  );
}

// ─── STEP 3 — DATE ───────────────────────────────────────────────────────────
function StepDate({ data, setData }) {
  const today = new Date(); today.setHours(0,0,0,0);
  const [view, setView] = useState(() => ({ y: today.getFullYear(), m: today.getMonth() }));

  const monthName = useMemo(() => {
    return new Date(view.y, view.m, 1).toLocaleDateString('en-GB', { month: 'long', year: 'numeric' });
  }, [view]);

  const cells = useMemo(() => {
    const first = new Date(view.y, view.m, 1);
    const lastDay = new Date(view.y, view.m + 1, 0).getDate();
    // start grid on Mon
    const dow = (first.getDay() + 6) % 7;
    const arr = [];
    for (let i = 0; i < dow; i++) arr.push(null);
    for (let d = 1; d <= lastDay; d++) arr.push(d);
    return arr;
  }, [view]);

  const prev = () => setView((v) => {
    const nm = v.m - 1;
    return nm < 0 ? { y: v.y - 1, m: 11 } : { y: v.y, m: nm };
  });
  const next = () => setView((v) => {
    const nm = v.m + 1;
    return nm > 11 ? { y: v.y + 1, m: 0 } : { y: v.y, m: nm };
  });

  const isPast = (d) => {
    const dt = new Date(view.y, view.m, d);
    return dt < today;
  };
  const sel = data.date;
  const isSelected = (d) => sel && sel.y === view.y && sel.m === view.m && sel.d === d;

  return (
    <>
      <h3 className="appt-q">A preferred <em>date</em>.</h3>
      <p className="appt-q-sub">The atelier will confirm a precise time after your request is received.</p>

      <div className="month-bar">
        <button type="button" className="month-nav-btn" onClick={prev} aria-label="Previous month">‹</button>
        <span className="mlbl">{monthName}</span>
        <button type="button" className="month-nav-btn" onClick={next} aria-label="Next month">›</button>
      </div>

      <div className="date-grid">
        {['Mo','Tu','We','Th','Fr','Sa','Su'].map((d) => <div key={d} className="dow">{d}</div>)}
        {cells.map((d, i) => {
          if (!d) return <div key={`e${i}`} className="date-cell is-empty" />;
          const past = isPast(d);
          const sel = isSelected(d);
          return (
            <button
              key={d}
              type="button"
              className={`date-cell ${past ? 'is-past' : ''} ${sel ? 'is-selected' : ''}`}
              onClick={() => !past && setData((dt) => ({ ...dt, date: { y: view.y, m: view.m, d } }))}
            >
              {d}
            </button>
          );
        })}
      </div>

      {data.date && (
        <p className="micro" style={{ color: 'var(--ink-mute)' }}>
          Requested · {new Date(data.date.y, data.date.m, data.date.d).toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
        </p>
      )}
    </>
  );
}

// ─── STEP 4 — DETAILS ────────────────────────────────────────────────────────
function StepDetails({ data, setData }) {
  const upd = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.value }));
  return (
    <>
      <h3 className="appt-q">Your <em>details</em>.</h3>
      <p className="appt-q-sub">Shared in confidence with the atelier. We respond personally to every enquiry.</p>

      <div style={{ display: 'grid', gap: 22 }}>
        <div className="field-row">
          <div className="field">
            <label>Full name</label>
            <input type="text" value={data.name} onChange={upd('name')} placeholder="Your name" />
          </div>
          <div className="field">
            <label>Email</label>
            <input type="email" value={data.email} onChange={upd('email')} placeholder="you@example.com" />
          </div>
        </div>
        <div className="field">
          <label>Phone (with country code)</label>
          <input type="tel" value={data.phone} onChange={upd('phone')} placeholder="+971 / +961 / +" />
        </div>
        <div className="field">
          <label>A note, if you wish</label>
          <textarea
            rows={3}
            value={data.message}
            onChange={upd('message')}
            placeholder="Wedding date, dress codes, references, anything we should know…"
          />
        </div>
      </div>
    </>
  );
}

// ─── STEP 5 — CONFIRM ────────────────────────────────────────────────────────
function StepConfirm({ data, formatDate }) {
  return (
    <div className="confirm">
      <div className="micro" style={{ color: 'var(--ink-mute)' }}>Request received</div>
      <h3>Merci — <em>nous reviendrons</em>.</h3>
      <p style={{ color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.6, margin: 0, maxWidth: '56ch' }}>
        Your request has been sent to the atelier. A member of the maison will contact you at <em style={{ fontFamily: 'var(--serif)' }}>{data.email || 'your email'}</em> to confirm time and details, typically within two working days.
      </p>
      <div className="summary">
        <div className="row"><span className="k">Atelier</span><span className="v">{data.atelier}</span></div>
        <div className="row"><span className="k">Occasion</span><span className="v">{data.occasion}</span></div>
        <div className="row"><span className="k">Requested</span><span className="v">{formatDate(data.date)}</span></div>
        <div className="row"><span className="k">Name</span><span className="v">{data.name}</span></div>
        {data.phone && <div className="row"><span className="k">Phone</span><span className="v">{data.phone}</span></div>}
      </div>
      <p className="micro" style={{ color: 'var(--ink-mute)' }}>
        All appointments are private — by invitation. Price on request.
      </p>
    </div>
  );
}

// ─── LOOKBOOK LIGHTBOX ───────────────────────────────────────────────────────
function LookLightbox({ look, onClose, onPrev, onNext }) {
  useEffect(() => {
    if (!look) return;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') onPrev();
      if (e.key === 'ArrowRight') onNext();
    };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [look, onClose, onPrev, onNext]);

  if (!look) return null;
  return (
    <div style={{ position:'fixed', inset:0, zIndex:90, display:'grid', gridTemplateColumns:'1fr', placeItems:'stretch', background:'rgba(0,0,0,0.86)', backdropFilter:'blur(6px)', animation:'fadeIn 350ms ease' }}>
      <div style={{ position:'relative', display:'grid', gridTemplateColumns:'1fr', placeItems:'center', padding:'80px clamp(20px,5vw,80px) 60px' }}>
        <button type="button" onClick={onClose} aria-label="Close" style={{ position:'absolute', top:24, right:24, color:'rgba(255,255,255,0.9)', cursor:'default' }} className="label">Close ×</button>
        <button type="button" onClick={onPrev} aria-label="Previous" style={{ position:'absolute', left:24, top:'50%', transform:'translateY(-50%)', color:'rgba(255,255,255,0.85)', cursor:'default' }} className="label">‹ Prev</button>
        <button type="button" onClick={onNext} aria-label="Next" style={{ position:'absolute', right:24, top:'50%', transform:'translateY(-50%)', color:'rgba(255,255,255,0.85)', cursor:'default' }} className="label">Next ›</button>

        <div style={{ display:'grid', gridTemplateColumns:'auto', gap:18, placeItems:'center', maxHeight:'100%', maxWidth:'100%' }}>
          <img src={look.src} alt={look.name} style={{ maxHeight:'72vh', maxWidth:'100%', objectFit:'contain', boxShadow:'0 30px 60px -20px rgba(0,0,0,0.6)' }} />
          <div style={{ color:'rgba(255,255,255,0.92)', textAlign:'center', display:'grid', gap:6 }}>
            <div className="label" style={{ opacity:0.7 }}>{look.col} · N° {look.n}</div>
            <div className="serif-it" style={{ fontSize:30 }}>{look.name}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AppointmentModal, LookLightbox });
