/* CatalogPage — the real 2020 company catalog, browsable as a book.
   UX: 3D page-turn, drag/swipe (RTL), tap-to-zoom overlay, progress, prefetch, remembered page. */
const BOOK_PAGES = [
  { img: 'assets/catalog/catalog-01.png', label: 'שער' },
  { img: 'assets/catalog/catalog-02.png', label: 'תוכן + סדרה A' },
  { img: 'assets/catalog/catalog-03.png', label: 'סדרות B · NS' },
  { img: 'assets/catalog/catalog-04.png', label: 'סדרות RS · EN' },
  { img: 'assets/catalog/catalog-05.png', label: 'סדרות D · E' },
  { img: 'assets/catalog/catalog-06.png', label: 'סדרות M · BK' },
  { img: 'assets/catalog/catalog-07.png', label: 'סדרות W · KEY' },
  { img: 'assets/catalog/catalog-08.png', label: 'SUPRIME + טבלת השוואה' },
];
const BOOK_LAST = BOOK_PAGES.length - 1;
const clampBookPage = (n) => Math.max(0, Math.min(BOOK_LAST, isNaN(n) ? 0 : n));

function CatalogPage() {
  const { SectionHeader, Button, Badge } = window.DS;
  const [page, setPage] = React.useState(() => clampBookPage(parseInt(localStorage.getItem('shalom-catalog-page') || '0', 10)));
  const [zoom, setZoom] = React.useState(false);
  const [zoomPct, setZoomPct] = React.useState(140); // vw
  const dirRef = React.useRef(1);
  const wrapRef = React.useRef(null);
  const zoomRef = React.useRef(null);
  const drag = React.useRef({ on: false, x0: 0, dx: 0 });

  const go = (n) => {
    const t = clampBookPage(n);
    setPage((p) => { if (t !== p) dirRef.current = t > p ? 1 : -1; return t; });
  };

  React.useEffect(() => { localStorage.setItem('shalom-catalog-page', String(page)); }, [page]);

  // Prefetch every spread once so page turns are instant
  React.useEffect(() => { BOOK_PAGES.forEach((p) => { const im = new Image(); im.src = p.img; }); }, []);

  // Keyboard: arrows turn pages (RTL book — left is forward), Esc closes zoom
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowRight') go(page + 1);
      if (e.key === 'ArrowLeft') go(page - 1);
      if (e.key === 'Escape') setZoom(false);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [page]);

  // 3D page-turn on change
  React.useEffect(() => {
    if (!window.gsap || !wrapRef.current) return;
    const d = dirRef.current;
    gsap.fromTo(wrapRef.current,
      { x: d * 76, rotateY: d * 10, autoAlpha: .2 },
      { x: 0, rotateY: 0, autoAlpha: 1, duration: .6, ease: 'expo.out', clearProps: 'transform,opacity,visibility' });
  }, [page]);

  // Drag / swipe — next page pulls in from the right
  const onDown = (e) => {
    drag.current = { on: true, x0: e.clientX, dx: 0 };
    wrapRef.current.classList.add('dragging');
    if (wrapRef.current.setPointerCapture) wrapRef.current.setPointerCapture(e.pointerId);
  };
  const onMove = (e) => {
    if (!drag.current.on) return;
    let dx = e.clientX - drag.current.x0;
    if ((dx < 0 && page === BOOK_LAST) || (dx > 0 && page === 0)) dx *= .25; // resist at the covers
    dx = Math.max(-170, Math.min(170, dx));
    drag.current.dx = dx;
    wrapRef.current.style.transform = 'translateX(' + (dx * .55) + 'px) rotateY(' + (dx * -.03) + 'deg)';
  };
  const onUp = () => {
    if (!drag.current.on) return;
    const dx = drag.current.dx;
    drag.current.on = false;
    wrapRef.current.classList.remove('dragging');
    wrapRef.current.style.transform = '';
    if (dx < -64 && page < BOOK_LAST) go(page + 1);
    else if (dx > 64 && page > 0) go(page - 1);
    else if (Math.abs(dx) < 6) setZoom(true); // a tap = magnify
  };

  // Zoom overlay: lock body scroll, center horizontally
  React.useEffect(() => {
    if (!zoom) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const el = zoomRef.current;
    if (el) {
      const max = el.scrollWidth - el.clientWidth;
      el.scrollLeft = max / 2;
      if (Math.abs(el.scrollLeft) < 1) el.scrollLeft = -max / 2; // RTL scroll coordinates
    }
    return () => { document.body.style.overflow = prev; };
  }, [zoom, zoomPct]);

  const cur = BOOK_PAGES[page];

  const zoomOverlay = zoom ? ReactDOM.createPortal(
    <div className="book-zoom" ref={zoomRef} onClick={(e) => { if (e.target === e.currentTarget) setZoom(false); }}>
      <div className="book-zoom-bar" onClick={(e) => e.stopPropagation()}>
        <button className="book-zoom-btn" onClick={() => setZoomPct((v) => Math.min(220, v + 30))} aria-label="הגדלה"><window.LIcon name="zoom-in" size={19} /></button>
        <button className="book-zoom-btn" onClick={() => setZoomPct((v) => Math.max(90, v - 30))} aria-label="הקטנה"><window.LIcon name="zoom-out" size={19} /></button>
        <button className="book-zoom-btn" onClick={() => setZoom(false)} aria-label="סגירה"><window.LIcon name="x" size={19} /></button>
      </div>
      <img src={cur.img} alt={'קטלוג כספות — ' + cur.label + ' (מוגדל)'} style={{ width: zoomPct + 'vw' }} />
    </div>,
    document.body
  ) : null;

  return (
    <main data-screen-label="Catalog">
      <section className="page-head">
        <div className="bg"><img src="assets/hero-vault.jpg" alt="דלת כספת פלדה כבדה — קטלוג הכספות של כספות השלום" fetchpriority="high" decoding="async" /></div>
        <div className="container page-head-inner">
          <nav className="crumb" aria-label="פירורי לחם"><a href="index.html">ראשי</a><span>/</span><span>קטלוג כספות</span></nav>
          <SectionHeader as="h1" tone="dark" kicker="מכירה + התקנה + אחריות" title="קטלוג כספות"
            description="דפדפו בקטלוג המלא — סדרות תוצרת ישראל, כספות כבדות בתקן אירופאי, כספות קיר, מפתחות ובתי מלון. המחיר נסגר מולי — בלי הפתעות." />
        </div>
      </section>

      <section className="section" data-screen-label="Catalog / Book">
        <div className="container">
          <div className="book-stage" data-reveal>
            <div className="book-frame">
              <button className="book-arrow book-arrow--prev" onClick={() => go(page - 1)} disabled={page === 0} aria-label="העמוד הקודם">
                <window.LIcon name="chevron-left" size={22} />
              </button>
              <div className="book-page-wrap" ref={wrapRef}
                onPointerDown={onDown} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}>
                <img id="book-page-img" src={cur.img} alt={'קטלוג כספות — ' + cur.label} draggable={false} decoding="async" />
                <span className="book-zoom-chip"><window.LIcon name="zoom-in" size={13} /> לחיצה מגדילה</span>
              </div>
              <button className="book-arrow book-arrow--next" onClick={() => go(page + 1)} disabled={page === BOOK_LAST} aria-label="העמוד הבא">
                <window.LIcon name="chevron-right" size={22} />
              </button>
            </div>
            <div className="book-progress" aria-hidden="true"><i style={{ width: ((page + 1) / BOOK_PAGES.length * 100) + '%' }}></i></div>
            <p className="book-count">{cur.label} · עמוד {page + 1} מתוך {BOOK_PAGES.length}</p>
            <p className="book-hint">גררו לדפדוף · חיצי המקלדת עובדים · לחיצה על העמוד מגדילה</p>
            <div className="book-thumbs" role="tablist" aria-label="עמודי הקטלוג">
              {BOOK_PAGES.map((p, i) => (
                <button key={i} className={'book-thumb' + (i === page ? ' on' : '')} onClick={() => go(i)} role="tab" aria-selected={i === page} title={p.label}>
                  <img src={p.img} alt={'עמוד קטלוג — ' + p.label} loading="lazy" />
                </button>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, flexWrap: 'wrap', marginTop: 34 }} data-reveal>
            <Badge variant="soft">מחיר לפי הצעה</Badge>
            <Button variant="primary" size="lg" href="contact.html" icon={<window.LIcon name="chevron-left" size={16} />}>מצאתם דגם? בקשו הצעה</Button>
            <Button variant="whatsapp" size="lg" href="https://wa.me/972543312367" target="_blank" icon={<img src="https://cdn.simpleicons.org/whatsapp/white" alt="" width="16" height="16" />}>שלחו לי את שם הדגם בוואטסאפ</Button>
          </div>
          <p style={{ marginTop: 22, textAlign: 'center', fontSize: 13.5, color: 'var(--text-muted)' }}>* כל כספת נמכרת עם התקנה מקצועית ועיגון לפי תקן. דגמים ומלאי משתנים — דברו איתי להתאמה מדויקת.</p>
        </div>
      </section>

      {zoomOverlay}
    </main>
  );
}
window.CatalogPage = CatalogPage;
