/* SiteChrome — nav, footer, icons, shared helpers. Exposed on window. */
const DS = window.DesignSystem_4c515b;

/** Lucide icon safe for React (icon replaces inner node only). */
function LIcon({ name, size = 18, style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current || !window.lucide) return;
    ref.current.innerHTML = '<i data-lucide="' + name + '"></i>';
    window.lucide.createIcons();
  }, [name]);
  return <span className="licon" ref={ref} style={{ fontSize: size, ...style }}></span>;
}

const NAV_LINKS = [
  { href: 'index.html', label: 'ראשי' },
  { href: 'catalog.html', label: 'קטלוג כספות' },
  { href: 'service.html', label: 'פריצה שקטה' },
  { href: 'course.html', label: 'קורס הכשרה' },
  { href: 'blog.html', label: 'מדריכים' },
  { href: 'contact.html', label: 'צור קשר' },
];

/* אינדקס המדריכים — משמש את BlogPage ואת "עוד מדריכים" בסוף כל פוסט */
const BLOG_INDEX = [
  { file: 'blog-price-guide.html', photo: 'shalom-open-safe.jpg', tag: 'מחירים', date: 'יולי 2026', mins: 5,
    title: 'כמה עולה פריצת כספת בישראל?',
    excerpt: 'טווחי מחירים אמיתיים לפי סוג כספת, מה באמת קובע את המחיר — ואיך לא ליפול על "פורץ מ-150 שקל" שמתייקר בשטח.' },
  { file: 'blog-gun-safe-2025.html', photo: 'work-keypad-install.jpg', tag: 'חוק ותקנים', date: 'יולי 2026', mins: 6,
    title: 'כספת נשק לפי הדרישות החדשות — מה חובה ב-2026?',
    excerpt: '4 מ"מ פלדה, דלת כפולה, 4 בריחים ועיגון דו-כיווני — הנחיות האגף לרישוי כלי ירייה מיולי 2025, והאם הכספת שלכם עוד חוקית.' },
  { file: 'blog-locked-safe.html', photo: 'work-lock-bypass.jpg', tag: 'חירום', date: 'יולי 2026', mins: 4,
    title: 'הכספת לא נפתחת? 5 בדיקות לפני שמזמינים טכנאי',
    excerpt: 'סוללה, נעילת עונשין, מפתח גיבוי — הבדיקות שפותרות חצי מהמקרים בחינם, ומה אסור לעשות כדי לא להפוך תקלה קטנה לנזק יקר.' },
];

function SiteNav() {
  const isHome = window.PAGE === 'home';
  React.useEffect(() => {
    const nav = document.getElementById('siteNav');
    const onScroll = () => nav && nav.classList.toggle('scrolled', window.scrollY > 40 || !isHome);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={'site-nav' + (isHome ? ' on-light' : '')} id="siteNav">
      <div className="nav-inner">
        <a className="nav-brand" href="index.html">
          <img src="assets/logo-shield.jpg" alt="הלוגו של כספות השלום — מגן זהב ואדום" />
          <span><b>כספות השלום</b><small>לשקט ולביטחון שלך</small></span>
        </a>
        <a className="nav-phone" href="tel:0543312367" dir="ltr"><LIcon name="phone" size={16} /> 054-331-2367</a>
      </div>
    </header>
  );
}

function SiteFooter() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
              <img src="assets/logo-shield.jpg" alt="" loading="lazy" style={{ width: 54, height: 54, objectFit: 'cover', borderRadius: 3, boxShadow: '0 0 0 1.5px rgba(233,185,74,.5)' }} />
              <div>
                <b style={{ color: '#fff', fontFamily: 'var(--font-display)', fontSize: 19, display: 'block' }}>כספות השלום</b>
                <small style={{ color: 'var(--maroon-500)', fontWeight: 600 }}>לשקט ולביטחון שלך</small>
              </div>
            </div>
            <p style={{ fontSize: 15, lineHeight: 1.7, maxWidth: '38ch' }}>
              מעל עשור שאני פותח, מתקין ומשדרג כספות — לבתים, לעסקים ולגופים הרגישים ביותר במשק. אמין, דיסקרטי ובעל סיווג ביטחוני גבוה.
            </p>
            <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
              <DS.IconButton label="וואטסאפ" href="https://wa.me/972543312367" target="_blank"><img src="https://cdn.simpleicons.org/whatsapp/191A1E" alt="" loading="lazy" /></DS.IconButton>
              <DS.IconButton label="אינסטגרם" href="https://www.instagram.com/safe_master_craker" target="_blank"><img src="https://cdn.simpleicons.org/instagram/191A1E" alt="" loading="lazy" /></DS.IconButton>
              <DS.IconButton label="פייסבוק" href="https://www.facebook.com/profile.php?id=100063610718289" target="_blank"><img src="https://cdn.simpleicons.org/facebook/191A1E" alt="" loading="lazy" /></DS.IconButton>
            </div>
          </div>
          <div>
            <h5>ניווט</h5>
            {NAV_LINKS.map((l) => <a key={l.href} href={l.href}>{l.label}</a>)}
          </div>
          <div>
            <h5>שירותים</h5>
            <a href="service.html">פריצה שקטה</a>
            <a href="catalog.html">התקנת כספות</a>
            <a href="catalog.html">מכירת כספות</a>
            <a href="contact.html">שדרוג מנגנוני נעילה</a>
          </div>
          <div>
            <h5>אזורי שירות</h5>
            <a href="city-ashkelon.html">פורץ כספות באשקלון</a>
            <a href="city-ashdod.html">פורץ כספות באשדוד</a>
            <a href="city-beer-sheva.html">פורץ כספות בבאר שבע</a>
            <a href="city-tel-aviv.html">פורץ כספות בתל אביב</a>
            <a href="city-jerusalem.html">פורץ כספות בירושלים</a>
            <a href="city-haifa.html">פורץ כספות בחיפה</a>
          </div>
          <div>
            <h5>יצירת קשר</h5>
            <a href="tel:0543312367" dir="ltr" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 20, color: 'var(--maroon-500)', textAlign: 'right' }}>054-331-2367</a>
            <a href="mailto:shalomsafes@gmail.com">shalomsafes@gmail.com</a>
            <a href="contact.html">אשקלון · שירות בכל הארץ</a>
            <p style={{ fontSize: 13.5, marginTop: 10, color: 'rgba(255,255,255,.45)' }}>זמין בכל הארץ · מענה מהיר בוואטסאפ</p>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 כספות השלום. כל הזכויות שמורות.</span>
          <nav aria-label="קישורים משפטיים" style={{ display: 'flex', gap: 16, flexWrap: 'wrap', justifyContent: 'center' }}>
            <a href="terms.html">תקנון</a>
            <a href="privacy.html">מדיניות פרטיות</a>
            <a href="accessibility.html">הצהרת נגישות</a>
            <a href="#" onClick={(e) => { e.preventDefault(); window.dispatchEvent(new Event('hs-cookies-open')); }}>הגדרות עוגיות</a>
          </nav>
          <span>עסק אישי · סיווג ביטחוני גבוה</span>
        </div>
      </div>
    </footer>
  );
}

/* ---- Accessibility widget ---- */
const A11Y_KEY = 'shalom-a11y';
const A11Y_OPTS = [
  { id: 'fontlg', label: 'טקסט מוגדל' },
  { id: 'contrast', label: 'ניגודיות גבוהה' },
  { id: 'links', label: 'הדגשת קישורים' },
  { id: 'noanim', label: 'עצירת אנימציות' },
  { id: 'readable', label: 'גופן קריא' },
];
function A11yWidget() {
  const [open, setOpen] = React.useState(false);
  const [flags, setFlags] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(A11Y_KEY)) || {}; } catch (e) { return {}; }
  });
  React.useEffect(() => {
    const root = document.documentElement;
    A11Y_OPTS.forEach((o) => root.classList.toggle('a11y-' + o.id, !!flags[o.id]));
    localStorage.setItem(A11Y_KEY, JSON.stringify(flags));
    // "עצירת אנימציות" מכבה גם את אפקטי ה-GSAP (טרנספורמים אינליין ש-CSS לבד לא עוצר)
    if (flags.noanim && window.gsap && window.ScrollTrigger) {
      ScrollTrigger.getAll().forEach((t) => t.kill());
      document.querySelectorAll('[data-reveal]').forEach((el) => { el.style.opacity = '1'; el.style.visibility = 'visible'; el.style.transform = 'none'; });
    }
  }, [flags]);
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);
  const toggle = (id) => setFlags((f) => ({ ...f, [id]: !f[id] }));
  return (
    <React.Fragment>
      <button className="a11y-fab" onClick={() => setOpen(!open)} aria-expanded={open} aria-haspopup="dialog" aria-label="תפריט נגישות" title="נגישות">
        <LIcon name="accessibility" size={24} />
      </button>
      {open && (
        <div className="a11y-panel" role="dialog" aria-label="הגדרות נגישות">
          <b className="a11y-title">נגישות</b>
          {A11Y_OPTS.map((o) => (
            <button key={o.id} className={'a11y-opt' + (flags[o.id] ? ' on' : '')} aria-pressed={!!flags[o.id]} onClick={() => toggle(o.id)}>
              <span>{o.label}</span><i aria-hidden="true"></i>
            </button>
          ))}
          <button className="a11y-opt a11y-reset" onClick={() => setFlags({})}>איפוס הגדרות</button>
          <a className="a11y-link" href="accessibility.html" onClick={() => setOpen(false)}>הצהרת נגישות</a>
        </div>
      )}
    </React.Fragment>
  );
}

/* ---- Cookie consent ---- */
const CONSENT_KEY = 'shalom-cookie-consent';
function CookieConsent() {
  const [choice, setChoice] = React.useState(() => {
    try { return localStorage.getItem(CONSENT_KEY); } catch (e) { return 'essential'; }
  });
  React.useEffect(() => {
    const reopen = () => setChoice(null);
    window.addEventListener('hs-cookies-open', reopen);
    return () => window.removeEventListener('hs-cookies-open', reopen);
  }, []);
  if (choice) return null;
  const decide = (v) => {
    try { localStorage.setItem(CONSENT_KEY, v); } catch (e) {}
    window.hsConsent = v;
    setChoice(v);
  };
  return (
    <div className="cookie-bar" role="dialog" aria-label="הודעת עוגיות" aria-live="polite">
      <p className="cookie-text">
        האתר משתמש באחסון מקומי לשמירת העדפות (כגון הגדרות נגישות) ובעוגיות של צדדים שלישיים בתכנים מוטמעים. פרטים ב<a href="privacy.html">מדיניות הפרטיות</a>.
      </p>
      <div className="cookie-actions">
        <button type="button" className="cookie-btn cookie-btn--ok" onClick={() => decide('all')}>מאשר/ת</button>
        <button type="button" className="cookie-btn cookie-btn--min" onClick={() => decide('essential')}>הכרחי בלבד</button>
      </div>
    </div>
  );
}

/* ---- Shared GSAP helpers ---- */
/* Elements fade in via GSAP when they scroll into view. GSAP's rAF ticker / ScrollTrigger
   have proven unreliable as the SOLE path to visibility more than once in this app (same
   class of bug as the old splash timeline stall: a tween gets created but never ticks,
   e.g. on a throttled/backgrounded tab) — so every revealed element also gets a deadline
   check that force-shows it via gsap.set() (synchronous, not tween-dependent) if its
   tween hasn't completed in time. Nothing can end up permanently stuck invisible. */
const HS_PENDING_REVEALS = new Set();
function hsSweepPendingReveals() {
  HS_PENDING_REVEALS.forEach((el) => {
    if (!el.isConnected) { HS_PENDING_REVEALS.delete(el); return; }
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight && r.bottom > 0) {
      if (getComputedStyle(el).opacity !== '1') gsap.set(el, { autoAlpha: 1, y: 0 });
      HS_PENDING_REVEALS.delete(el);
    }
  });
}
let hsSweepAttached = false;
function initReveals(scope) {
  const els = (scope || document).querySelectorAll('[data-reveal]');
  const reducedMotion = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  if (!window.gsap || reducedMotion) {
    // No animation engine, or the user asked the OS for reduced motion — show content plainly.
    els.forEach((el) => { el.dataset.hsRevealed = '1'; el.style.opacity = '1'; el.style.visibility = 'visible'; el.style.transform = 'none'; });
    return;
  }
  if (!hsSweepAttached) {
    hsSweepAttached = true;
    window.addEventListener('scroll', hsSweepPendingReveals, { passive: true });
    window.addEventListener('resize', hsSweepPendingReveals);
    // Deadline sweeps independent of any user scroll/resize — catches a stalled tween
    // on an "already in view at load" element, which never fires either of those events.
    setTimeout(hsSweepPendingReveals, 1500);
    setTimeout(hsSweepPendingReveals, 3500);
  }
  els.forEach((el) => {
    if (el.dataset.hsRevealed) return;
    el.dataset.hsRevealed = '1';
    const delay = parseFloat(el.dataset.revealDelay || 0);
    const rect = el.getBoundingClientRect();
    const alreadyInView = rect.top < window.innerHeight * 0.86 && rect.bottom > 0;
    if (alreadyInView) {
      // Deterministic — don't gamble on ScrollTrigger's initial-state evaluation.
      gsap.fromTo(el, { autoAlpha: 0, y: 54 }, { autoAlpha: 1, y: 0, duration: 1.05, ease: 'expo.out', delay });
    } else {
      gsap.fromTo(el, { autoAlpha: 0, y: 54 }, {
        autoAlpha: 1, y: 0, duration: 1.05, ease: 'expo.out', delay,
        scrollTrigger: { trigger: el, start: 'top 86%', once: true },
      });
    }
    // Every element (both branches) is a backstop candidate — the sweep only force-shows
    // ones that are actually in view (or already past-due below the fold check), so this
    // never spoils a legitimate not-yet-scrolled-to reveal.
    HS_PENDING_REVEALS.add(el);
  });
  hsSweepPendingReveals();
}
function initCounters(scope) {
  if (!window.gsap) return;
  (scope || document).querySelectorAll('[data-hs-count]').forEach((el) => {
    const raw = String(el.dataset.hsCount).replace(/,/g, '');
    const target = parseFloat(raw);
    if (isNaN(target)) return;
    const obj = { v: 0 };
    gsap.to(obj, {
      v: target, duration: 1.8, ease: 'power2.out',
      scrollTrigger: { trigger: el, start: 'top 88%', once: true },
      onUpdate: () => { el.textContent = Math.round(obj.v).toLocaleString('he-IL'); },
    });
  });
}

Object.assign(window, { DS, LIcon, SiteNav, SiteFooter, NAV_LINKS, BLOG_INDEX, A11yWidget, CookieConsent, initReveals, initCounters });
