/* lk-lightbox.jsx — общий просмотр фото и видео во весь экран для кабинета клиента и всех кабинетов сотрудников
   (спека docs/superpowers/specs/2026-10-28-lk-design-scale-design.md, раздел 3.3; вынесен из client-v2-app.jsx без изменений поведения).
   window.LKLightbox({ items: [{ url, kind?: 'image'|'video'|'pdf', name?, work?, date? }], at, onClose }):
   стрелки, счётчик, ←/→/Esc, свайп; Esc закрывает только просмотр, окно под ним остаётся. Стили — lk-lightbox.css. */
(function () {
  'use strict';
  const PATHS = { left: 'M15 5l-7 7 7 7', right: 'M9 5l7 7-7 7', x: 'M6 6l12 12M18 6L6 18' };
  const Ico = ({ n, s = 18 }) => (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d={PATHS[n]} /></svg>);

  function LKLightbox({ items, at, onClose }) {
    const [i, setI] = React.useState(at || 0);
    const n = items.length;
    const go = (d) => setI((x) => (x + d + n) % n);
    React.useEffect(() => {
      const k = (e) => {
        if (e.key === 'Escape') { e.stopPropagation(); onClose(); }
        else if (e.key === 'ArrowRight') go(1);
        else if (e.key === 'ArrowLeft') go(-1);
      };
      window.addEventListener('keydown', k, true); return () => window.removeEventListener('keydown', k, true);
    }, [n]);
    const sx = React.useRef(null);
    /* список может сжаться, пока просмотр открыт (задачу приняли) — держим индекс в пределах */
    React.useEffect(() => { if (n && i > n - 1) setI(n - 1); }, [n, i]);
    const it = items[Math.min(i, Math.max(n - 1, 0))] || {};
    return (
      <div className="lk-big" role="dialog" aria-modal="true" aria-label="Просмотр" onClick={onClose}
        onTouchStart={(e) => { sx.current = e.touches[0].clientX; }}
        onTouchEnd={(e) => { if (sx.current == null) return; const dx = e.changedTouches[0].clientX - sx.current; sx.current = null; if (Math.abs(dx) > 40) go(dx < 0 ? 1 : -1); }}>
        <figure onClick={(e) => e.stopPropagation()}>
          {it.kind === 'video' ? <video src={it.url} controls autoPlay />
            : it.kind === 'pdf' ? <iframe src={it.url} title={it.name || 'Документ'} />
            : <img src={it.url} alt={it.name || ''} />}
          <figcaption><span>{it.work || it.name || ''}{it.date ? ' · ' + it.date : ''}</span>{n > 1 && <span className="num">{i + 1} из {n}</span>}</figcaption>
        </figure>
        {n > 1 && <button type="button" className="nav prev" aria-label="Предыдущее" onClick={(e) => { e.stopPropagation(); go(-1); }}><Ico n="left" s={22} /></button>}
        {n > 1 && <button type="button" className="nav next" aria-label="Следующее" onClick={(e) => { e.stopPropagation(); go(1); }}><Ico n="right" s={22} /></button>}
        <button type="button" className="nav cls" aria-label="Закрыть" onClick={onClose}><Ico n="x" /></button>
      </div>);
  }

  window.LKLightbox = LKLightbox;
})();
