/* SharedSections — סקשנים מדף הבית לשימוש חוזר בכל העמודים (ערים וכו').
   כל קומפוננטה עצמאית ומחזיקה את ה-state שלה. נטען אחרי SiteChrome.jsx. */

/* ---- וידאו מדף הבית (hero) ---- */
function HeroVideoCard({ delay = '.18' }) {
  /* Direct Range-streamable URL (Vercel serves byte ranges) — iOS WebKit is unreliable with
     blob: video sources and paints nothing without a poster, so the blob-fetch loader is gone.
     Root-relative path so the clip resolves identically from / and from nested routes. */
  return (
    <div className="hero-video-card" data-reveal data-reveal-delay={delay}>
      <div className="hero-video-frame">
        <video controls loop playsInline preload="metadata"
          src="/assets/video/hero-field.mp4"
          poster="/assets/video/hero-field-poster.jpg"
          aria-label="שלום בעבודה — פתיחת כספת בשטח"></video>
      </div>
    </div>
  );
}

/* ---- רצועת התעודות (כולל זום) ---- */
const SHARED_CERTS = [
  { img: 'assets/certs/cert-id-card.png', short: 'תעודת טכנאי מוסמך', label: 'תעודת טכנאי כספות מוסמך — א. סמואל בע״מ, סוכני S&G ו‑MAUER בישראל' },
  { img: 'assets/certs/cert-safetech-en.png', short: 'Safe Technician · S&G', label: 'Safe Technician — הסמכת S&G: התקנה ומניפולציה של מנעולי סדרה 6700 (Level 1+2)' },
  { img: 'assets/certs/cert-level-a-he.png', short: 'טכנאי כספות שלב א׳', label: 'טכנאי כספות שלב א׳ — מנעולי S&G, KABA, SECURAM ו‑MAUER' },
];

function CertsBand({ title, lead }) {
  const [open, setOpen] = React.useState(false);
  const [idx, setIdx] = React.useState(0);

  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = prev; window.removeEventListener('keydown', onKey); };
  }, [open]);

  return (
    <section className="certs-band" data-screen-label="Shared / Certifications">
      <div className="container">
        <div className="certs-seo" data-reveal>
          <h2>{title || 'טכנאי כספות מוסמך בפריסה ארצית — פריצה, תיקון, התקנה ומכירה'}</h2>
          <p>{lead || 'כספות השלום — עסק שעוסק בכספות בלבד: פריצת כספות ללא נזק, פתיחת כספת נעולה, החלפת קוד ומנעול, תיקון כספות ומכירת כספות לבית ולעסק — כולל כספת לנשק בתקן משטרה. שירות מהיר באשקלון, אשדוד, באר שבע ובכל הדרום — ומגיעים לכל הארץ, גם היום. '}<a href="tel:0543312367" dir="ltr">054-331-2367</a></p>
        </div>
        <div className="certs-cards" data-reveal>
          {[1, 0, 2].map((ci) => {
            const c = SHARED_CERTS[ci];
            return (
              <figure className={'cert-card ' + (ci === 0 ? 'cert-card--center' : 'cert-card--side')} key={ci} role="button" tabIndex={0}
                onClick={() => { setIdx(ci); setOpen(true); }}
                onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setIdx(ci); setOpen(true); } }}>
                <img src={c.img} alt={c.label} loading="lazy" />
                <figcaption>{c.short}</figcaption>
              </figure>
            );
          })}
        </div>
      </div>
      {open && ReactDOM.createPortal(
        <div className="certs-zoom" onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}>
          <div className="book-zoom-bar">
            <button className="book-zoom-btn" onClick={() => setOpen(false)} aria-label="סגירה"><window.LIcon name="x" size={19} /></button>
          </div>
          <img className="certs-main" src={SHARED_CERTS[idx].img} alt={SHARED_CERTS[idx].label} loading="lazy" decoding="async" />
          <p className="certs-caption">{SHARED_CERTS[idx].label}</p>
          <div className="certs-thumbs">
            {SHARED_CERTS.map((c, i) => (
              <button key={i} className={i === idx ? 'on' : ''} onClick={() => setIdx(i)} aria-label={c.label}>
                <img src={c.img} alt="" loading="lazy" decoding="async" />
              </button>
            ))}
          </div>
        </div>,
        document.body
      )}
    </section>
  );
}

/* ---- חוגת השירותים הכהה ---- */
const SHARED_SERVICES = [
  { icon: 'lock-open', title: 'פריצה שקטה', description: 'פריצת כספות ללא נזק — שכחתם קוד או אבד המפתח? פתיחת כספת נעולה 24/7 בכל הארץ.' },
  { icon: 'package', title: 'התקנה ומכירה', description: 'מכירת כספות והתקנת כספות לבית ולעסק — כולל עיגון לקיר ולרצפה לפי תקן, מאשקלון ועד כל הארץ.' },
  { icon: 'cog', title: 'שדרוג מנגנונים', description: 'החלפת קוד ומנעול לכספת — קומבינציות MP, מנעולי מפתח, דיגיטליים וביומטריים כגון KABA.' },
  { icon: 'wrench', title: 'תיקון ושיפוץ', description: 'תיקון כספות ושיפוץ — פתיחה אחרי סוללה שנגמרה, החלפת מנגנון, סתימת קידוחים וצביעה.' },
  { icon: 'shield-check', title: 'כספות בתקן', description: 'כספת לנשק בתקן משטרת ישראל, כספת נרקוטיקה לפי נוהל 150 ודרישות חברות הביטוח.' },
];

function ServicesDial({ title, description, anchorFirst }) {
  const { SectionHeader } = window.DS;
  const [active, setActive] = React.useState(0);
  const services = SHARED_SERVICES;
  const count = services.length;
  const prev = () => setActive((i) => (i - 1 + count) % count);
  const next = () => setActive((i) => (i + 1) % count);
  const cur = services[active];

  return (
    <section className="section sec-dark svc2-section" data-screen-label="Shared / Services dial">
      <div className="container">
        <div data-reveal>
          <SectionHeader tone="dark" align="center"
            title={title || <React.Fragment>שירותים <span style={{ color: 'var(--maroon-500)' }}>מקצועיים</span> ואמינים</React.Fragment>}
            description={description || 'מהבית הפרטי ועד המשרד הרגיש ביותר — פתרון מלא לכל כספת.'} />
        </div>
      </div>
      <div className="svc2-stage" data-reveal>
        <button className="svc2-tap svc2-tap--next" onClick={next} aria-label="השירות הבא"></button>
        <button className="svc2-tap svc2-tap--prev" onClick={prev} aria-label="השירות הקודם"></button>
        <div className="svc2-dome">
          <img className="svc2-dome-dial" src="assets/photos/safe-dial.png" alt="" aria-hidden="true" loading="lazy" decoding="async" style={{ transform: `rotate(${active * 72}deg)` }} />
          <div className="svc2-dome-overlay"></div>
          <div className="svc2-dome-content" key={active}>
            <span className="svc2-num">{active + 1}</span>
            <h3 className="svc2-title">{cur.title}</h3>
            <p className="svc2-desc">{cur.description}</p>
          </div>
        </div>
        {services.map((s, i) => {
          let rel = i - active;
          if (rel > count / 2) rel -= count;
          if (rel < -count / 2) rel += count;
          const angleDeg = rel * 32;
          const rad = angleDeg * Math.PI / 180;
          const sin = Math.sin(rad).toFixed(4);
          const cos = Math.cos(rad).toFixed(4);
          return (
            <button key={i} className={'svc2-node' + (rel === 0 ? ' is-active' : '')}
              {...(anchorFirst && i === 0 ? { 'data-comment-anchor': '601bd9638a-button-198-15' } : {})}
              style={{
                left: `calc(50% + (${sin} * var(--svc2-r)))`,
                top: `calc(var(--svc2-r) - (${cos} * var(--svc2-r)))`,
                transform: `translate(-50%, -50%) rotate(${angleDeg}deg)`,
                zIndex: rel === 0 ? 4 : 3,
              }}
              onClick={() => setActive(i)}>
              <span className="svc2-node-icon"><window.LIcon name={s.icon} size={rel === 0 ? 18 : 14} /></span>
              <span className="svc2-node-label">{s.title}</span>
            </button>
          );
        })}
      </div>
      <div className="svc2-dots">
        {services.map((_, i) => (
          <button key={i} className={'svc2-dot' + (i === active ? ' is-on' : '')} onClick={() => setActive(i)} aria-label={'שירות ' + (i + 1)}></button>
        ))}
      </div>
    </section>
  );
}

/* ---- שליחת ליד לאימייל (FormSubmit — ללא שרת) ---- */
const LEAD_EMAIL = 'shalomsafes@gmail.com';
async function sendLead(fields) {
  const res = await fetch('https://formsubmit.co/ajax/' + LEAD_EMAIL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
    body: JSON.stringify({ _subject: 'ליד חדש מהאתר — כספות השלום', _template: 'table', _captcha: 'false', ...fields }),
  });
  if (!res.ok) throw new Error('send failed');
  return res.json();
}
window.sendLead = sendLead;

/* ---- רצועת טופס לידים ---- */
function LeadFormBand() {
  const { Button, Input } = window.DS;
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(false);
  const submit = (e) => {
    e.preventDefault();
    if (busy) return;
    const fd = new FormData(e.target);
    setBusy(true); setErr(false);
    sendLead({ 'שם': fd.get('name') || '', 'טלפון': fd.get('phone') || '', 'מקור': 'טופס מהיר — ' + document.title })
      .then(() => {
        setSent(true);
        if (window.gsap) {
          requestAnimationFrame(() => {
            gsap.fromTo('#lead-sent-ok', { autoAlpha: 0, scale: .8, y: 20 }, { autoAlpha: 1, scale: 1, y: 0, duration: .8, ease: 'back.out(1.7)' });
          });
        }
      })
      .catch(() => setErr(true))
      .finally(() => setBusy(false));
  };
  return (
    <section className="hero-form-band" data-screen-label="Shared / Lead form">
      <div className="hero-flow hero-flow--standalone">
        {!sent ? (
          <form onSubmit={submit} className="hero-lead-form hero-lead-form--bar" data-reveal data-reveal-delay=".08">
            <div className="hero-formbar-label">
              <h3>השאירו פרטים ואחזור אליכם</h3>
              <p>מענה מהיר — בדרך כלל תוך פחות משעה.</p>
            </div>
            <div className="hero-lead-fields hero-lead-fields--inline">
              <Input label="שם מלא" name="name" placeholder="ישראל ישראלי" required />
              <Input label="טלפון" name="phone" type="tel" placeholder="050-000-0000" required inputMode="tel" />
            </div>
            <div className="hero-cta-stack">
              <Button type="submit" size="lg" variant="primary" block disabled={busy} icon={<window.LIcon name="mouse-pointer" size={16} />}>{busy ? 'שולח…' : 'שליחה'}</Button>
              <span className="hero-cta-or">או</span>
              <Button variant="whatsapp" size="lg" block href="https://wa.me/972543312367" target="_blank" icon={<img src="https://cdn.simpleicons.org/whatsapp/white" alt="" width="16" height="16" />}>שלחו לי הודעה בוואטסאפ</Button>
            </div>
            {err && <p className="form-privacy-note" style={{ color: '#FFB4B4' }}>השליחה נכשלה — נסו שוב או התקשרו: <a href="tel:0543312367" dir="ltr">054-331-2367</a></p>}
            <p className="form-privacy-note">הפרטים ישמשו לחזרה אליכם בלבד ולא יועברו לצד שלישי. מסירתם אינה חובה על פי דין. <a href="privacy.html">מדיניות פרטיות</a></p>
          </form>
        ) : (
          <div id="lead-sent-ok" className="hero-lead-sent hero-lead-sent--bar">
            <div className="hero-lead-sent-icon"><window.LIcon name="check" size={26} style={{ color: '#fff' }} /></div>
            <div>
              <h3>הפרטים אצלי.</h3>
              <p>אחזור אליכם בהקדם — בדרך כלל תוך פחות משעה בשעות הפעילות.</p>
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

/* ---- רצועת CTA כהה ---- */
function CTABand({ title }) {
  const { Button } = window.DS;
  return (
    <section className="section sec-dark cta-band" data-screen-label="Shared / CTA">
      <div className="container" data-reveal>
        <h2 style={{ color: '#fff', marginTop: 0 }}>{title || 'כספות השלום - טכנאי כספות מוסמך ומקצועי במחירים הכי טובים'}</h2>
        <a className="cta-phone" href="tel:0543312367" dir="ltr">054-331-<b>2367</b></a>
        <div style={{ display: 'flex', gap: 14, justifyContent: 'center', flexWrap: 'wrap' }}>
          <Button variant="whatsapp" size="lg" href="https://wa.me/972543312367" target="_blank" icon={<img src="https://cdn.simpleicons.org/whatsapp/white" alt="" width="18" height="18" />}>הודעה לשלום</Button>
          <Button variant="primary" size="lg" href="contact.html">קבלו הצעה</Button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { HeroVideoCard, CertsBand, ServicesDial, LeadFormBand, CTABand });
