/* Оконный Гид — overlays: callback / measure / messenger modals + lightbox.
   Listens to window 'okg:open' and 'okg:lightbox' events fired by sections. */
const { useState: useStateO, useEffect: useEffectO } = React;

function Backdrop({ onClose, children, maxW = 460 }) {
  useEffectO(() => {
    const onKey = (e) => { if (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; };
  }, []);
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(18,18,18,.62)', backdropFilter: 'blur(3px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, animation: 'okgFade .2s ease' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: '100%', maxWidth: maxW, background: '#fff', borderRadius: 'var(--r-xl)', padding: 'clamp(24px,4vw,34px)', boxShadow: 'var(--shadow-lg)', position: 'relative', animation: 'okgPop .24s var(--ease)' }}>
        {children}
        <button onClick={onClose} aria-label="Закрыть" style={{ position: 'absolute', top: 16, right: 16, width: 38, height: 38, border: 'none', background: 'var(--surface-fill)', borderRadius: '50%', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-strong)' }}>
          <Icon name="close" size={20} />
        </button>
      </div>
    </div>
  );
}

function FormModal({ type, note, onClose }) {
  const [sent, setSent] = useStateO(false);
  const cfg = {
    callback: { title: 'Заказать обратный звонок', sub: 'Перезвоним в течение 15 минут в рабочее время и ответим на вопросы.', cta: 'Заказать звонок', icon: 'phone' },
    measure: { title: 'Вызвать замерщика', sub: 'Бесплатный замер с выездом по Дмитрову и району, в том числе за город.', cta: 'Записаться на замер', icon: 'ruler' },
  }[type] || {};
  return (
    <Backdrop onClose={onClose}>
      {sent ? (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 14, padding: '14px 6px' }}>
          <span style={{ width: 60, height: 60, borderRadius: '50%', background: 'var(--okg-pine-100)', color: 'var(--okg-pine-600)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={32} /></span>
          <h3 style={{ margin: 0, fontSize: 22, fontWeight: 800, color: 'var(--text-strong)' }}>Спасибо! Перезвоним в рабочее время</h3>
          <p style={{ margin: 0, fontSize: 15, lineHeight: 1.55, color: 'var(--text-muted)' }}>Заявка принята. Менеджер свяжется с вами и согласует детали.</p>
          <Button onClick={onClose} variant="outline" style={{ marginTop: 6 }}>Закрыть</Button>
        </div>
      ) : (
        <React.Fragment>
          <span style={{ width: 48, height: 48, borderRadius: 'var(--r-md)', background: 'var(--okg-terra-100)', color: 'var(--okg-terra-600)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}><Icon name={cfg.icon} size={24} /></span>
          <h3 style={{ margin: '0 0 6px', fontSize: 23, fontWeight: 800, color: 'var(--text-strong)', letterSpacing: '-.01em' }}>{cfg.title}</h3>
          <p style={{ margin: '0 0 20px', fontSize: 14.5, lineHeight: 1.5, color: 'var(--text-muted)' }}>{cfg.sub}</p>
          <form onSubmit={(e) => { e.preventDefault(); okgSendLead(e.currentTarget, Object.assign({ source: cfg.title }, note ? { calc: note } : null)); setSent(true); }} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Field label="Ваше имя" name="name" placeholder="Иван" required />
            <Field label="Телефон" name="phone" type="tel" placeholder="+7 (___) ___-__-__" required />
            {type === 'measure' && <Field label="Адрес объекта" name="addr" placeholder="Населённый пункт, улица" required />}
            <Button type="submit" size="lg" fullWidth icon={cfg.icon}>{cfg.cta}</Button>
            <Consent />
          </form>
        </React.Fragment>
      )}
    </Backdrop>
  );
}

function MessengerModal({ onClose }) {
  // Только подтверждённые каналы связи. Ссылки на WhatsApp / Telegram / VK
  // были заглушками (t.me без имени, VK со старым названием, WhatsApp на
  // городском номере) — вели в никуда и теряли заявки. Добавить обратно,
  // когда заказчик пришлёт реальные адреса.
  const opts = [
    { icon: 'max', t: 'MAX', d: 'Написать в MAX', href: window.MAX_URL, bg: 'var(--okg-terra-100)', fg: 'var(--okg-terra-600)' },
    { icon: 'phone', t: 'Позвонить', d: window.PHONE, href: 'tel:' + window.PHONE_TEL, bg: '#e9edf5', fg: '#3a5a8c' },
    { icon: 'mail', t: 'E-mail', d: 'oknavkotedj@mail.ru', href: 'mailto:oknavkotedj@mail.ru', bg: '#eef0f2', fg: 'var(--mk-graphite-700)' },
  ];
  return (
    <Backdrop onClose={onClose}>
      <h3 style={{ margin: '0 0 6px', fontSize: 23, fontWeight: 800, color: 'var(--text-strong)', letterSpacing: '-.01em' }}>Написать в мессенджер</h3>
      <p style={{ margin: '0 0 20px', fontSize: 14.5, lineHeight: 1.5, color: 'var(--text-muted)' }}>Ответим в рабочее время. Выберите удобный способ связи.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {opts.map((o) => (
          <a key={o.t} href={o.href} target="_blank" rel="noopener" style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 16, border: '1px solid var(--border-hairline)', borderRadius: 'var(--r-lg)', transition: 'border-color var(--dur), transform var(--dur)' }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--text-strong)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border-hairline)'; e.currentTarget.style.transform = 'none'; }}>
            <span style={{ width: 46, height: 46, flex: 'none', borderRadius: 'var(--r-md)', background: o.bg, color: o.fg, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={o.icon} size={24} /></span>
            <div>
              <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text-strong)' }}>{o.t}</div>
              <div style={{ fontSize: 13.5, color: 'var(--text-muted)' }}>{o.d}</div>
            </div>
            <Icon name="arrowR" size={18} style={{ marginLeft: 'auto', color: 'var(--text-faint)' }} />
          </a>
        ))}
      </div>
    </Backdrop>
  );
}

function Lightbox({ list, index, onClose }) {
  const [i, setI] = useStateO(index);
  useEffectO(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') setI((v) => (v + 1) % list.length);
      if (e.key === 'ArrowLeft') setI((v) => (v - 1 + list.length) % list.length);
    };
    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; };
  }, [list.length]);
  const go = (d, e) => { e.stopPropagation(); setI((v) => (v + d + list.length) % list.length); };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(12,12,12,.92)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 'clamp(16px,4vw,48px)', animation: 'okgFade .2s ease' }}>
      <button onClick={onClose} aria-label="Закрыть" style={{ position: 'absolute', top: 20, right: 20, width: 46, height: 46, border: 'none', background: 'rgba(255,255,255,.12)', borderRadius: '50%', cursor: 'pointer', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="close" size={24} /></button>
      <button onClick={(e) => go(-1, e)} aria-label="Назад" style={{ position: 'absolute', left: 'clamp(8px,2vw,28px)', top: '50%', transform: 'translateY(-50%)', width: 52, height: 52, border: 'none', background: 'rgba(255,255,255,.12)', borderRadius: '50%', cursor: 'pointer', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevL" size={26} /></button>
      <button onClick={(e) => go(1, e)} aria-label="Вперёд" style={{ position: 'absolute', right: 'clamp(8px,2vw,28px)', top: '50%', transform: 'translateY(-50%)', width: 52, height: 52, border: 'none', background: 'rgba(255,255,255,.12)', borderRadius: '50%', cursor: 'pointer', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevR" size={26} /></button>
      <img onClick={(e) => e.stopPropagation()} src={list[i].src} alt={list[i].cap} style={{ maxWidth: '90vw', maxHeight: '78vh', objectFit: 'contain', borderRadius: 'var(--r-md)', boxShadow: '0 20px 60px rgba(0,0,0,.5)' }} />
      <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 14, color: '#fff' }}>
        <span style={{ fontSize: 15 }}>{list[i].cap}</span>
        <span style={{ fontSize: 13, color: 'rgba(255,255,255,.5)' }}>{i + 1} / {list.length}</span>
      </div>
    </div>
  );
}

function Overlays() {
  const [modal, setModal] = useStateO(null);
  const [lb, setLb] = useStateO(null);
  useEffectO(() => {
    // Locked to the terracotta theme — clear any previously saved theme.
    try { localStorage.removeItem('okg-theme'); } catch (e) {}
    document.body.removeAttribute('data-theme');
    const onOpen = (e) => setModal({ type: e.detail.type, note: e.detail.note });
    const onLb = (e) => setLb(e.detail);
    window.addEventListener('okg:open', onOpen);
    window.addEventListener('okg:lightbox', onLb);
    return () => { window.removeEventListener('okg:open', onOpen); window.removeEventListener('okg:lightbox', onLb); };
  }, []);
  return (
    <React.Fragment>
      {modal && (modal.type === 'callback' || modal.type === 'measure') && <FormModal type={modal.type} note={modal.note} onClose={() => setModal(null)} />}
      {modal && modal.type === 'messenger' && <MessengerModal onClose={() => setModal(null)} />}
      {lb && <Lightbox list={lb.list} index={lb.index} onClose={() => setLb(null)} />}
    </React.Fragment>
  );
}

Object.assign(window, { Overlays });
