/* Category listing page — products within a category (uses CMS data when available) */

/* CMS data */
const _cmsProducts   = window.__CMS__?.products   || [];
const _cmsCategories = window.__CMS__?.categories || [];

/* Fallback category list */
const CAT_LINKS_DEFAULT = [
  { name: "דגלים",            href: "category.html?c=flags",   count: 24, active: true },
  { name: "מעמדי דגלים",       href: "category.html?c=stands",  count: 18 },
  { name: "דגלי חוף",         href: "category.html?c=beach",   count: 12 },
  { name: "רולאפים",          href: "category.html?c=rollup",  count: 14 },
  { name: "חולצות מודפסות",   href: "category.html?c=tshirt",  count: 32 },
  { name: "שילוט",            href: "category.html?c=sign",    count: 21 },
  { name: "מפות שולחן",       href: "category.html?c=table",   count: 8 },
  { name: "מוצרי פרסום",      href: "category.html?c=promo",   count: 45 },
  { name: "מיתוג אירועים",    href: "category.html?c=event",   count: 16 },
];

const CAT_LINKS = _cmsCategories.length ? _cmsCategories : CAT_LINKS_DEFAULT;

/* Fallback products */
const PRODUCTS_DEFAULT = [
  { id: "1", code: "רובין 304", desc: "מעמד עץ גדול לשני דגלונים\nדגם מתנופף או תלוי על חוט כולל כיפה", svgType: "StandWoodTwoFlags",       badge: null },
  { id: "2", code: "רובין 303", desc: "מעמד עץ גדול לדגלון בודד\nדגם לתלייה עם חוט כולל כיפה",         svgType: "StandWoodPennantFringe",  badge: "חדש" },
  { id: "3", code: "רובין 302", desc: "מעמד עץ לשלושה דגלונים\nדגם מתנופף",                             svgType: "StandWoodThreeFlags",     badge: null },
  { id: "4", code: "רובין 300", desc: "מעמד עץ קטן לדגלון בודד\nדגם מתנופף",                            svgType: "StandWoodSingleStripes",  badge: null },
  { id: "5", code: "רובין 308", desc: "מעמד שולחני מניקל יוקרתי\nלשני דגלונים",                         svgType: "StandChromeTwo",          badge: "פופולרי" },
  { id: "6", code: "רובין 307", desc: "מעמד שולחני מניקל יוקרתי\nלדגלון בודד",                          svgType: "StandChromeSingle",       badge: null },
  { id: "7", code: "רובין 306", desc: "מעמד עץ לשלושה דגלונים\nדגם מתנופף עם חוט",                      svgType: "StandWoodThreeEmpty",     badge: null },
  { id: "8", code: "רובין 305", desc: "מעמד עץ לשלושה דגלונים\nכולל כיפה",                              svgType: "StandWoodTwoFlagsB",      badge: null },
  { id: "9", code: "רובין 310", desc: "מעמד מניקל סלים, גובה משתנה",                                     svgType: "StandChromeSlim",         badge: null },
  { id:"10", code: "רובין 311", desc: "מעמד עץ פרימיום לשלושה דגלונים\nכיפות זהב",                       svgType: "StandWoodLarge3Strip",    badge: "מומלץ" },
  { id:"11", code: "רובין 312", desc: "מעמד עץ גדול לשני דגלונים\nכיפות מוזהבות",                        svgType: "StandWoodTwoFlags",       badge: null },
  { id:"12", code: "רובין 313", desc: "מעמד שולחני מניקל ליחיד\nגובה 30 ס\"מ",                           svgType: "StandChromeSingle",       badge: null },
];

/* Resolve SVG component from svgType string */
function ProductImg({ svgType, imageUrl, code }) {
  if (imageUrl) {
    return <img src={imageUrl} alt={code} style={{ width: '82%', height: '82%', objectFit: 'contain' }} />;
  }
  const Comp = Products[svgType];
  if (Comp) return <Comp />;
  return <div style={{ width: 60, height: 60, background: 'var(--bg-2)', borderRadius: 8 }} />;
}

function CategoryPage() {
  const [mobile, setMobile] = React.useState(false);
  const [sort, setSort]     = React.useState("פופולריות");
  const [page, setPage]     = React.useState(1);
  useReveal();

  const products = _cmsProducts.length ? _cmsProducts : PRODUCTS_DEFAULT;
  const total    = products.length;

  return (
    <React.Fragment>
      <TopBar />
      <Header current="catalog.html" onMobileOpen={() => setMobile(true)} />
      <MobileMenu open={mobile} onClose={() => setMobile(false)} />
      <main>
        <section className="page-hero">
          <div className="container">
            <div className="breadcrumb">
              <a href="index.html">דף הבית</a>
              <span className="sep">›</span>
              <a href="catalog.html">קטלוג מוצרים</a>
              <span className="sep">›</span>
              <span>דגלים שולחניים ומעמדי דגלונים</span>
            </div>
            <h1>דגלים שולחניים ומעמדי דגלונים</h1>
            <p>סדרת רובין — מעמדי עץ ומניקל לדגלונים שולחניים. ייצור פנימי, בכל גודל, ובהתאמה אישית לפי דרישת הלקוח.</p>
          </div>
        </section>

        <section className="section">
          <div className="container">
            <div className="cat-page-grid">
              <aside className="cat-sidebar">
                <h4>קטגוריות</h4>
                {CAT_LINKS.map(c => (
                  <a key={c.id || c.name} href={c.href} className={"cat-link " + (c.active ? "active" : "")}>
                    <span>{c.name}</span>
                    <span className="num">{c.count}</span>
                  </a>
                ))}
                <hr />
                <div className="sidebar-cta">
                  <div className="help-block">
                    <strong>צריכים עזרה?</strong>
                    <p>מנהל לקוח יחזור אליכם תוך שעה עם הצעת מחיר מותאמת.</p>
                    <a href="contact.html" className="btn btn-primary btn-sm">קבלו הצעת מחיר</a>
                  </div>
                </div>
              </aside>

              <div>
                <div className="cat-toolbar">
                  <div className="results-count">
                    מציג <strong>1-{Math.min(12, total)}</strong> מתוך <strong>{total}</strong> מוצרים
                  </div>
                  <div className="sort-group">
                    <span style={{ color: 'var(--text-3)', fontSize: 13 }}>מיון:</span>
                    <select value={sort} onChange={e => setSort(e.target.value)}>
                      <option>פופולריות</option>
                      <option>מוצרים חדשים</option>
                      <option>שם א-ת</option>
                      <option>שם ת-א</option>
                    </select>
                  </div>
                </div>

                <div className="product-grid">
                  {products.slice(0, 12).map((p, i) => (
                    <a key={p.id || p.code} href={`product.html?id=${p.id || ''}`} className="product-card reveal" style={{ transitionDelay: `${i * 30}ms` }}>
                      <div className="pc-img">
                        {p.badge && <span className={"pc-badge " + (p.badge === "חדש" ? "" : "muted")}>{p.badge}</span>}
                        <span className="pc-quickview" title="צפייה מהירה"><Icon name="chevron" size={14} /></span>
                        <ProductImg svgType={p.svgType} imageUrl={p.imageUrl} code={p.code} />
                      </div>
                      <div className="pc-meta">
                        <div className="pc-code">{p.code}</div>
                        <div className="pc-desc">
                          {(p.desc || '').split('\n').map((line, j, arr) => (
                            <React.Fragment key={j}>{line}{j < arr.length - 1 && <br />}</React.Fragment>
                          ))}
                        </div>
                        <div className="pc-cta">
                          <span className="small-btn">פרטים</span>
                          <span className="small-btn red">הצעת מחיר</span>
                        </div>
                      </div>
                    </a>
                  ))}
                </div>

                <div className="pagination">
                  <button disabled>›</button>
                  <button className={page === 1 ? "active" : ""} onClick={() => setPage(1)}>1</button>
                  {total > 12 && <button className={page === 2 ? "active" : ""} onClick={() => setPage(2)}>2</button>}
                  <button>‹</button>
                </div>
              </div>
            </div>
          </div>
        </section>

        <FinalCTA />
      </main>
      <Footer />
      <StickyWhatsapp />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<CategoryPage />);
