// modals.jsx — Register Interest (multi-step), Brochure Gate, Private Viewing.
// Loaded after sections.jsx.

const { useState: useState_m, useEffect: useEffect_m, useMemo: useMemo_m } = React;

// Modal shell ───────────────────────────────────────────────────────────────
function Modal({ open, onClose, children, size }) {
  useEffect_m(() => {
    if (!open) return;
    const onKey = (e) => e.key === 'Escape' && onClose();
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose} role="dialog" aria-modal="true">
      <div className={'modal ' + (size === 'lg' ? 'modal-lg' : '')} onClick={(e) => e.stopPropagation()}>
        {children}
      </div>
    </div>
  );
}

function ModalHead({ eyebrow, title, sub, onClose }) {
  return (
    <div className="modal-head">
      <div>
        <Eyebrow>{eyebrow}</Eyebrow>
        <h3>{title}</h3>
        {sub && <p className="sub">{sub}</p>}
      </div>
      <button className="modal-close" onClick={onClose} aria-label="Close">
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
          <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" strokeWidth="1" />
        </svg>
      </button>
    </div>
  );
}

function SuccessScreen({ title, body, cta, onClose }) {
  return (
    <div className="success-screen">
      <div className="seal" aria-hidden="true">
        <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
          <path d="M5 14 L12 21 L23 8" stroke="currentColor" strokeWidth="1.6" />
        </svg>
      </div>
      <Eyebrow>Confirmed</Eyebrow>
      <h3>{title}</h3>
      <p>{body}</p>
      {cta && <button className="btn btn-outline" style={{ marginTop: 32 }} onClick={onClose}>{cta}</button>}
    </div>
  );
}

// Register Interest — multi-step ────────────────────────────────────────────
function RegisterModal({ open, onClose, project, copy }) {
  const F = copy.forms.register;
  const [step, setStep] = useState_m(0);
  const [done, setDone] = useState_m(false);
  const [form, setForm] = useState_m({
    fname: '', lname: '', email: '', phone: '', country: '', lang: copy._lang === 'en' ? 'English' : (copy._lang === 'ar' ? 'العربية' : copy._lang === 'ru' ? 'Русский' : '中文'),
    intent: '', timing: '', budget: '', rooms: '', contact: '', notes: '', project: project.name,
  });
  useEffect_m(() => { if (open) { setStep(0); setDone(false); } }, [open]);
  if (!open) return null;
  const u = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const sel = (k, val) => setForm({ ...form, [k]: val });

  const s1Valid = form.fname && form.lname && form.email;
  const s2Valid = form.intent && form.timing;
  const submit = () => setDone(true);

  return (
    <Modal open={open} onClose={onClose} size="lg">
      {done ? (
        <div className="modal-body">
          <SuccessScreen title={F.successTitle} body={F.successBody} cta={F.successCta} onClose={onClose} />
        </div>
      ) : (
        <>
          <ModalHead eyebrow={project.name} title={F.title} sub={F.sub} onClose={onClose} />
          <div className="modal-body">
            <div className="stepper" aria-hidden="true">
              {[0,1,2].map((i) => <div key={i} className={'step ' + (i < step ? 'done' : i === step ? 'active' : '')}></div>)}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 10.5, letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--muted)' }}>
              <span style={{ color: step === 0 ? 'var(--text)' : 'var(--muted)' }}>01 · {F.s1}</span>
              <span style={{ color: step === 1 ? 'var(--text)' : 'var(--muted)' }}>02 · {F.s2}</span>
              <span style={{ color: step === 2 ? 'var(--text)' : 'var(--muted)' }}>03 · {F.s3}</span>
            </div>
            <div style={{ marginTop: 32 }}>
              {step === 0 && (
                <>
                  <div className="field-inline">
                    <div className="field"><label>{F.fname}</label><input value={form.fname} onChange={u('fname')} placeholder="—" /></div>
                    <div className="field"><label>{F.lname}</label><input value={form.lname} onChange={u('lname')} placeholder="—" /></div>
                  </div>
                  <div className="field-inline" style={{ marginTop: 24 }}>
                    <div className="field"><label>{F.email}</label><input type="email" value={form.email} onChange={u('email')} placeholder="name@email.com" /></div>
                    <div className="field"><label>{F.phone}</label><input value={form.phone} onChange={u('phone')} placeholder="+971 …" /></div>
                  </div>
                  <div className="field-inline" style={{ marginTop: 24 }}>
                    <div className="field"><label>{F.country}</label><input value={form.country} onChange={u('country')} placeholder="—" /></div>
                    <div className="field">
                      <label>{F.lang}</label>
                      <select value={form.lang} onChange={u('lang')}>
                        <option>English</option><option>العربية</option><option>Русский</option><option>中文</option>
                      </select>
                    </div>
                  </div>
                </>
              )}
              {step === 1 && (
                <>
                  <SelectField label={F.intent} options={F.intentOpts} value={form.intent} onChange={(v) => sel('intent', v)} />
                  <SelectField label={F.timing} options={F.timingOpts} value={form.timing} onChange={(v) => sel('timing', v)} />
                  <SelectField label={F.budget} options={F.budgetOpts} value={form.budget} onChange={(v) => sel('budget', v)} />
                </>
              )}
              {step === 2 && (
                <>
                  <SelectField label={F.rooms} options={F.roomsOpts} value={form.rooms} onChange={(v) => sel('rooms', v)} />
                  <SelectField label={F.contact} options={F.contactOpts} value={form.contact} onChange={(v) => sel('contact', v)} />
                  <div className="field" style={{ marginTop: 24 }}>
                    <label>{F.notes}</label>
                    <textarea rows="3" value={form.notes} onChange={u('notes')} placeholder="—" style={{ resize: 'vertical', padding: '14px 0' }} />
                  </div>
                  <label style={{ marginTop: 24, display: 'flex', alignItems: 'flex-start', gap: 12, fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.6, cursor: 'pointer' }}>
                    <input type="checkbox" defaultChecked style={{ marginTop: 3, width: 14, height: 14 }} />
                    <span>{F.consent}</span>
                  </label>
                </>
              )}
            </div>
          </div>
          <div className="modal-foot">
            <span className="small">All enquiries handled by the AHS sales gallery at City Walk · {project.name}</span>
            <div style={{ display: 'flex', gap: 12 }}>
              {step > 0 && <button className="btn btn-outline" onClick={() => setStep(step - 1)}>{F.back}</button>}
              {step < 2 && (
                <button className="btn btn-primary" disabled={(step === 0 && !s1Valid) || (step === 1 && !s2Valid)}
                  style={(step === 0 && !s1Valid) || (step === 1 && !s2Valid) ? { opacity: 0.4, cursor: 'not-allowed' } : {}}
                  onClick={() => setStep(step + 1)}>{F.next}</button>
              )}
              {step === 2 && <button className="btn btn-accent" onClick={submit}>{F.submit}</button>}
            </div>
          </div>
        </>
      )}
    </Modal>
  );
}

function SelectField({ label, options, value, onChange }) {
  return (
    <div className="field" style={{ marginTop: 24 }}>
      <label>{label}</label>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 8 }}>
        {options.map((o) => (
          <button
            type="button"
            key={o}
            onClick={() => onChange(o)}
            style={{
              padding: '10px 16px',
              border: '1px solid var(--border)',
              background: value === o ? 'var(--text)' : 'transparent',
              color: value === o ? 'var(--bg)' : 'var(--text)',
              fontSize: 12.5,
              letterSpacing: '0.04em',
              transition: 'all 180ms ease',
            }}
          >{o}</button>
        ))}
      </div>
    </div>
  );
}

// Brochure Gate ──────────────────────────────────────────────────────────────
function BrochureModal({ open, onClose, project, copy }) {
  const F = copy.forms.brochure;
  const [done, setDone] = useState_m(false);
  const [form, setForm] = useState_m({ fname: '', email: '', phone: '' });
  useEffect_m(() => { if (open) { setDone(false); setForm({ fname: '', email: '', phone: '' }); } }, [open]);
  if (!open) return null;
  const u = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  return (
    <Modal open={open} onClose={onClose}>
      {done ? (
        <div className="modal-body">
          <SuccessScreen title={F.successTitle} body={F.successBody} cta="Close" onClose={onClose} />
          <div style={{ marginTop: 24, padding: 24, background: 'var(--surface)', display: 'flex', alignItems: 'center', gap: 18, border: '1px solid var(--border)' }}>
            <div style={{ width: 64, height: 80, background: 'linear-gradient(135deg, #2A2A2D 0%, #1A1A1D 100%)', display: 'grid', placeItems: 'center', color: 'var(--accent)', fontFamily: 'var(--serif)', fontSize: 12, letterSpacing: '0.18em' }}>PDF</div>
            <div style={{ flex: 1 }}>
              <div className="label-sm" style={{ color: 'var(--muted)' }}>{project.name}</div>
              <div style={{ fontFamily: 'var(--serif)', fontSize: 22, marginTop: 4 }}>Residences Brochure · 2026</div>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>48 pp · 12 MB · Email-gated</div>
            </div>
          </div>
        </div>
      ) : (
        <>
          <ModalHead eyebrow={project.name} title={F.title} sub={F.sub} onClose={onClose} />
          <div className="modal-body">
            <div className="field"><label>{F.fname}</label><input value={form.fname} onChange={u('fname')} placeholder="—" /></div>
            <div className="field"><label>{F.email}</label><input type="email" value={form.email} onChange={u('email')} placeholder="name@email.com" /></div>
            <div className="field"><label>{F.phone}</label><input value={form.phone} onChange={u('phone')} placeholder="+971 …" /></div>
            <label style={{ marginTop: 8, display: 'flex', alignItems: 'flex-start', gap: 12, fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.6, cursor: 'pointer' }}>
              <input type="checkbox" defaultChecked style={{ marginTop: 3, width: 14, height: 14 }} />
              <span>{F.consent}</span>
            </label>
            <div style={{ marginTop: 24, padding: 18, background: 'var(--surface)', border: '1px solid var(--border)', display: 'flex', gap: 16, alignItems: 'center' }}>
              <div style={{ width: 48, height: 60, background: 'linear-gradient(135deg, #2A2A2D 0%, #1A1A1D 100%)', display: 'grid', placeItems: 'center', color: 'var(--accent)', fontFamily: 'var(--serif)', fontSize: 11, letterSpacing: '0.16em' }}>PDF</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 18 }}>{project.name} Residences</div>
                <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>48 pp · 12 MB · Floor concepts · Material palette · Partner credits</div>
              </div>
            </div>
          </div>
          <div className="modal-foot">
            <span className="small">No prices headlined. POA / by enquiry.</span>
            <button className="btn btn-accent" disabled={!form.fname || !form.email}
              style={(!form.fname || !form.email) ? { opacity: 0.4, cursor: 'not-allowed' } : {}}
              onClick={() => setDone(true)}>{F.submit}</button>
          </div>
        </>
      )}
    </Modal>
  );
}

// Private Viewing — date + time picker ──────────────────────────────────────
function buildMonth(refDate) {
  const y = refDate.getFullYear(), m = refDate.getMonth();
  const first = new Date(y, m, 1);
  const startOffset = first.getDay(); // Sun = 0
  const daysInMonth = new Date(y, m + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < startOffset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(y, m, d));
  while (cells.length % 7 !== 0) cells.push(null);
  return cells;
}

function ViewingModal({ open, onClose, project, copy }) {
  const F = copy.forms.viewing;
  const [done, setDone] = useState_m(false);
  const today = useMemo_m(() => { const t = new Date(); t.setHours(0,0,0,0); return t; }, []);
  const [refDate, setRefDate] = useState_m(today);
  const [picked, setPicked] = useState_m(null);
  const [time, setTime] = useState_m(null);
  const [mode, setMode] = useState_m(F.modeOpts[0]);
  const [form, setForm] = useState_m({ fname: '', email: '', phone: '', notes: '' });
  useEffect_m(() => { if (open) { setDone(false); setPicked(null); setTime(null); setForm({ fname: '', email: '', phone: '', notes: '' }); } }, [open]);
  if (!open) return null;
  const u = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const cells = buildMonth(refDate);
  const monthLabel = refDate.toLocaleString(copy._lang === 'ar' ? 'ar' : copy._lang === 'ru' ? 'ru' : copy._lang === 'zh' ? 'zh' : 'en', { month: 'long', year: 'numeric' });
  const dayNames = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  const slots = ['10:00','11:30','14:00','15:30','17:00','18:30'];

  return (
    <Modal open={open} onClose={onClose} size="lg">
      {done ? (
        <div className="modal-body">
          <SuccessScreen title={F.successTitle} body={F.successBody} cta="Close" onClose={onClose} />
          <div style={{ marginTop: 24, padding: 24, background: 'var(--surface)', border: '1px solid var(--border)' }}>
            <div className="label-sm" style={{ color: 'var(--muted)' }}>{mode}</div>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 24, marginTop: 8 }}>
              {picked && picked.toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric' })} · {time}
            </div>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>{project.name} · City Walk, Building 5, Unit 2</div>
          </div>
        </div>
      ) : (
        <>
          <ModalHead eyebrow={project.name} title={F.title} sub={F.sub} onClose={onClose} />
          <div className="modal-body">
            <SelectField label={F.mode} options={F.modeOpts} value={mode} onChange={setMode} />
            <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 0.8fr', gap: 32, marginTop: 32 }} className="viewing-grid">
              <div>
                <label style={{ fontSize: 10.5, letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--muted)', fontWeight: 500 }}>{F.date}</label>
                <div style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <button type="button" onClick={() => setRefDate(new Date(refDate.getFullYear(), refDate.getMonth() - 1, 1))}
                    style={{ padding: '6px 10px', border: '1px solid var(--border)' }}>‹</button>
                  <span style={{ fontFamily: 'var(--serif)', fontSize: 20 }}>{monthLabel}</span>
                  <button type="button" onClick={() => setRefDate(new Date(refDate.getFullYear(), refDate.getMonth() + 1, 1))}
                    style={{ padding: '6px 10px', border: '1px solid var(--border)' }}>›</button>
                </div>
                <div className="cal" style={{ marginTop: 16 }}>
                  {dayNames.map((d) => <div className="head" key={d}>{d}</div>)}
                  {cells.map((c, i) => c === null ? <div key={i}></div> : (
                    <button
                      key={i}
                      disabled={c < today}
                      className={
                        (picked && c.getTime() === picked.getTime() ? 'selected ' : '') +
                        (c.getTime() === today.getTime() ? 'today' : '')
                      }
                      onClick={() => setPicked(c)}
                    >{c.getDate()}</button>
                  ))}
                </div>
              </div>
              <div>
                <label style={{ fontSize: 10.5, letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--muted)', fontWeight: 500 }}>{F.time}</label>
                {picked ? (
                  <div className="timeslots">
                    {slots.map((s) => (
                      <button key={s} className={time === s ? 'selected' : ''} onClick={() => setTime(s)}>{s}</button>
                    ))}
                  </div>
                ) : (
                  <p style={{ fontSize: 13, color: 'var(--muted)', marginTop: 12, lineHeight: 1.6 }}>Select a date to see available times. Our concierge keeps two daily slots in reserve for international viewings.</p>
                )}
                <hr className="hairline" style={{ margin: '24px 0' }} />
                <div className="field"><label>{F.fname}</label><input value={form.fname} onChange={u('fname')} placeholder="—" /></div>
                <div className="field" style={{ marginTop: 18 }}><label>{F.email}</label><input value={form.email} onChange={u('email')} placeholder="name@email.com" /></div>
                <div className="field" style={{ marginTop: 18 }}><label>{F.phone}</label><input value={form.phone} onChange={u('phone')} placeholder="+971 …" /></div>
              </div>
            </div>
            <div className="field" style={{ marginTop: 24 }}>
              <label>{F.notes}</label>
              <textarea rows="2" value={form.notes} onChange={u('notes')} placeholder="—" style={{ resize: 'vertical', padding: '14px 0' }} />
            </div>
          </div>
          <div className="modal-foot">
            <span className="small">{picked && time ? `${picked.toLocaleDateString('en', { weekday: 'long', month: 'short', day: 'numeric' })} · ${time} · ${mode}` : 'Select date and time to continue.'}</span>
            <button className="btn btn-accent" disabled={!picked || !time || !form.fname || !form.email}
              style={(!picked || !time || !form.fname || !form.email) ? { opacity: 0.4, cursor: 'not-allowed' } : {}}
              onClick={() => setDone(true)}>{F.submit}</button>
          </div>
        </>
      )}
    </Modal>
  );
}

// Lightbox ──────────────────────────────────────────────────────────────────
function Lightbox({ items, idx, onClose, onPrev, onNext }) {
  useEffect_m(() => {
    if (idx === null) return;
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') onPrev();
      if (e.key === 'ArrowRight') onNext();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [idx, onClose, onPrev, onNext]);
  if (idx === null) return null;
  const item = items[idx];
  return (
    <div className="lb-backdrop" onClick={onClose}>
      <img className="lb-img" src={item.img} alt={item.label} onClick={(e) => e.stopPropagation()} />
      <button className="lb-close" onClick={onClose} aria-label="Close">
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 1L13 13M13 1L1 13" stroke="currentColor" /></svg>
      </button>
      <button className="lb-nav prev" onClick={(e) => { e.stopPropagation(); onPrev(); }} aria-label="Previous">‹</button>
      <button className="lb-nav next" onClick={(e) => { e.stopPropagation(); onNext(); }} aria-label="Next">›</button>
      <div className="lb-meta">{idx + 1} / {items.length} · {item.label}</div>
    </div>
  );
}

Object.assign(window, { Modal, ModalHead, RegisterModal, BrochureModal, ViewingModal, Lightbox, SelectField, SuccessScreen });
