/* Shared layout: TopBar, Header, Footer, MobileMenu, StickyWA */

/* CMS helper — reads from window.__CMS__.content if available */
const _cms = window.__CMS__?.content || {};
const _g   = (section, key, fallback) => _cms[section]?.[key] ?? fallback;

const NAV_ITEMS = (_cms.nav && _cms.nav.length ? _cms.nav : [
  { label: "דף הבית",            href: "index.html" },
  { label: "קטלוג מוצרים",       href: "catalog.html" },
  { label: "פתרונות לעסקים",      href: "catalog.html#business" },
  { label: "עבודות שלנו",         href: "portfolio.html" },
  { label: "אודות",              href: "about.html" },
  { label: "בלוג",               href: "blog.html" },
  { label: "צור קשר",            href: "contact.html" },
]);

/* ============================================================
   TOP UTILITY BAR
============================================================ */
function TopBar() {
  const phone     = _g('general', 'phone',     '03-6248480');
  const whatsapp  = _g('general', 'whatsapp',  '050-1234567');
  const hours     = _g('general', 'hours',     'ראשון - חמישי 08:00-17:00');
  const ctaText   = _g('topbar',  'ctaText',   'קבלו הצעת מחיר');
  const wa        = whatsapp.replace(/[^0-9]/g, '');
  return (
    <div className="topbar">
      <div className="container topbar-inner">
        <a href="contact.html" className="red-cta">{ctaText}</a>
        <a href={`https://wa.me/972${wa.replace(/^0/, '')}`} className="wa-btn" aria-label="WhatsApp" target="_blank" rel="noopener noreferrer">
          <Icon name="whatsapp" size={16} />
        </a>
        <a href={`tel:${phone}`} className="contact-item">
          <span className="ic"><Icon name="phone" size={14} /></span>
          <span>{phone}</span>
        </a>
        <span className="spacer" />
        <div className="top-meta">
          <span>{hours}</span>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   HEADER
============================================================ */
function Header({ current = "index.html", onMobileOpen }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={"header " + (scrolled ? "scrolled" : "")} data-screen-label="Header">
      <div className="container header-inner">
        <Logo />
        <nav className="nav">
          {NAV_ITEMS.map(item => (
            <a key={item.href} href={item.href} className={current === item.href ? "active" : ""}>
              {item.label}
            </a>
          ))}
        </nav>
        <button className="menu-toggle" onClick={onMobileOpen} aria-label="תפריט">
          <Icon name="menu" />
        </button>
      </div>
    </header>
  );
}

/* ============================================================
   FOOTER
============================================================ */
function Footer() {
  const phone    = _g('general', 'phone',       '03-6248480');
  const wa       = _g('general', 'whatsapp',    '050-1234567');
  const email    = _g('general', 'email',       'info@rubinflags.co.il');
  const address  = _g('general', 'address',     'האורגים 12, תל אביב');
  const desc     = _g('footer',  'description', 'מפעל ייצור ומיתוג ישראלי. דגלים, שילוט, טקסטיל ומוצרי פרסום עבור עיריות, חברות ומוסדות — ייצור בישראל מאז 2003.');
  const copy     = _g('footer',  'copyright',   '© 2026 כל הזכויות שמורות לחברת א. רובין דגלים בע״מ');
  const fbUrl    = _g('general', 'socialFb',    '#');
  const igUrl    = _g('general', 'socialIg',    '#');
  const liUrl    = _g('general', 'socialLinkedin', '#');
  const ytUrl    = _g('general', 'socialYt',    '#');

  return (
    <footer className="footer" data-screen-label="Footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <Logo />
            <p className="footer-desc">{desc}</p>
            <div className="footer-social">
              <a href={fbUrl} aria-label="פייסבוק"><Icon name="fb" size={16} /></a>
              <a href={igUrl} aria-label="אינסטגרם"><Icon name="ig" size={16} /></a>
              <a href={liUrl} aria-label="לינקדאין"><Icon name="linkedin" size={16} /></a>
              <a href={ytUrl} aria-label="יוטיוב"><Icon name="yt" size={16} /></a>
            </div>
          </div>
          <div className="footer-col">
            <h5>קטלוג מוצרים</h5>
            <ul>
              <li><a href="catalog.html">דגלים</a></li>
              <li><a href="catalog.html">דגלי חוף</a></li>
              <li><a href="catalog.html">רולאפים</a></li>
              <li><a href="catalog.html">חולצות מודפסות</a></li>
              <li><a href="catalog.html">שילוט</a></li>
              <li><a href="catalog.html">מוצרי פרסום</a></li>
              <li><a href="catalog.html">מיתוג אירועים</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>פתרונות לעסקים</h5>
            <ul>
              <li><a href="catalog.html">עיריות וגופים</a></li>
              <li><a href="catalog.html">חברות הייטק</a></li>
              <li><a href="catalog.html">מוסדות חינוך</a></li>
              <li><a href="catalog.html">אירועים גדולים</a></li>
              <li><a href="about.html">אודות</a></li>
              <li><a href="blog.html">בלוג</a></li>
              <li><a href="contact.html">צור קשר</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>יצירת קשר</h5>
            <ul>
              <li className="footer-contact-item">
                <span className="ic"><Icon name="phone" size={14} /></span>
                <span>{phone}</span>
              </li>
              <li className="footer-contact-item">
                <span className="ic"><Icon name="whatsapp" size={14} /></span>
                <span>{wa}</span>
              </li>
              <li className="footer-contact-item">
                <span className="ic"><Icon name="mail" size={14} /></span>
                <span>{email}</span>
              </li>
              <li className="footer-contact-item">
                <span className="ic"><Icon name="pin" size={14} /></span>
                <span>{address}</span>
              </li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">{copy}</div>
      </div>
    </footer>
  );
}

/* ============================================================
   MOBILE MENU
============================================================ */
function MobileMenu({ open, onClose }) {
  return (
    <div className={"mobile-menu " + (open ? "open" : "")}>
      <button className="mm-close" onClick={onClose} aria-label="סגור"><Icon name="x" /></button>
      <nav>
        {NAV_ITEMS.map(item => <a key={item.href} href={item.href} onClick={onClose}>{item.label}</a>)}
      </nav>
      <div className="mm-cta">
        <a href={`https://wa.me/972${(_g('general','whatsapp','0501234567')).replace(/[^0-9]/g,'').replace(/^0/,'')}`}
           className="btn btn-whatsapp btn-lg" target="_blank" rel="noopener noreferrer">
          <Icon name="whatsapp" size={18} /> וואטסאפ
        </a>
        <a href="contact.html" className="btn btn-primary btn-lg">קבלו הצעת מחיר</a>
      </div>
    </div>
  );
}

/* ============================================================
   STICKY WHATSAPP
============================================================ */
function StickyWhatsapp() {
  const wa = (_g('general', 'whatsapp', '050-1234567')).replace(/[^0-9]/g, '').replace(/^0/, '');
  return (
    <a href={`https://wa.me/972${wa}`} className="sticky-wa" aria-label="WhatsApp" target="_blank" rel="noopener noreferrer">
      <Icon name="whatsapp" size={24} />
    </a>
  );
}

/* ============================================================
   STICKY CATALOG ASIDE (floating, appears on scroll)
============================================================ */
const CAT_LIST = [
  { name: "דגלים",            Img: () => <Prod.Flags />,      href: "product.html" },
  { name: "דגלי חוף",         Img: () => <Prod.Beach />,      href: "catalog.html" },
  { name: "רולאפים",          Img: () => <Prod.Rollup />,     href: "catalog.html" },
  { name: "חולצות מודפסות",   Img: () => <Prod.TShirt />,     href: "catalog.html" },
  { name: "שילוט",            Img: () => <Prod.Sign />,       href: "catalog.html" },
  { name: "מפות שולחן",       Img: () => <Prod.Tablecloth />, href: "catalog.html" },
  { name: "מוצרי פרסום",      Img: () => <Prod.Promo />,      href: "catalog.html" },
  { name: "מיתוג אירועים",    Img: () => <Prod.Event />,      href: "catalog.html" },
];

function StickyAside() {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 700 && window.scrollY < (document.body.scrollHeight - 1200));
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <aside className={"sticky-aside " + (show ? "show" : "")}>
      <div className="sticky-aside-head">
        <div className="mini-logo">
          <BrandLogo size={38} />
          <div>
            <strong>{_g('general', 'companyName', 'א. רובין דגלים')}</strong>
            <small>{_g('general', 'companyTagline', 'ייצור ומיתוג')}</small>
          </div>
        </div>
        <div className="mini-cta">
          <a href="contact.html" className="btn btn-primary">קבלו הצעת מחיר</a>
          <a href="catalog.html" className="btn btn-blue">צפו בקטלוג</a>
        </div>
      </div>
      <div className="sticky-aside-cats">
        <div className="sticky-aside-title">קטלוג המוצרים שלנו</div>
        {CAT_LIST.slice(0, 4).map(c => (
          <a key={c.name} href={c.href} className="aside-cat">
            <span className="mini-thumb"><c.Img /></span>
            <span className="l">
              <strong>{c.name}</strong>
              <small>לפרטים נוספים</small>
            </span>
          </a>
        ))}
        <a href="catalog.html" className="btn btn-outline btn-sm" style={{ width: '100%', marginTop: 8 }}>לכל הקטגוריות</a>
      </div>
    </aside>
  );
}

/* Logo — uses CMS logo if set */
const Logo = () => {
  const logoUrl     = _g('general', 'logoUrl', null);
  const companyName = _g('general', 'companyName', 'א. רובין דגלים');
  const tagline     = _g('general', 'companyTagline', 'מוצרי פרסום ודגלים');
  return (
    <a href="index.html" className="logo">
      <span className="logo-mark">
        {logoUrl
          ? <img src={logoUrl} alt={companyName} style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
          : <BrandLogo size={44} />}
      </span>
      <span className="logo-text">
        <strong>{companyName}</strong>
        <small>{tagline}</small>
      </span>
    </a>
  );
};

Object.assign(window, { TopBar, Header, Footer, MobileMenu, StickyWhatsapp, StickyAside, Logo, NAV_ITEMS, CAT_LIST });
