// Header.jsx — Oblak i Sunce UI Kit
// Announcement bar + sticky nav + mega menu.
// Sve stavke su PRAVI linkovi: kategorije/potkategorije -> category.html, brendovi -> brand-detail.html,
// ikonice -> search/wishlist/account/cart stranice. Struktura kategorija prati bekend (seed.ts CATEGORY_RULES).

const T = window.OBS_TOKENS;

// Header se koristi i sa root stranice (index.html) i iz pages/ — prefiks izjednačava putanje.
// Apsolutne putanje — rade i na starim (/pages/x.html) i na čistim (/proizvod/…) URL-ovima.
const navUrl = (page) => '/pages/' + page;
// Čisti (SEO) URL-ovi za nav:
const catUrl = (...slugs) => '/' + slugs.filter(Boolean).join('/');
const brandUrl = (slug) => '/brend/' + slug;

// Boje mega-menija (cikliraju po glavnim kategorijama)
const CAT_COLORS = [
  { color: "#F5DDD1", hover: "#D4918A" }, { color: "#E3EDE0", hover: "#7BA87B" },
  { color: "#E8D5BA", hover: "#C27B6B" }, { color: "#F0E3F0", hover: "#D4918A" },
  { color: "#D6EAF4", hover: "#6BA3C7" }, { color: "#F0E6C8", hover: "#D4A843" },
  { color: "#E7E0F0", hover: "#9B8BC7" }, { color: "#DCEEE8", hover: "#5FA890" },
];
// Redoslijed glavnih kategorija u traci (ostalo se ne prikazuje u glavnom meniju — dostupno preko „Sve").
const NAV_ORDER = ["odjeca","obuca","igracke-i-edukacija","oprema-za-bebe","ishrana","aksesoari","kucni-tekstil-i-dekor","ljeto-i-plaza","sport-i-napolju","njega-i-higijena"];
const navLabel = (name) => name.split(' i ')[0].trim();

function Header({ cartCount = 0, onCartOpen }) {
  const [megaMenuOpen, setMegaMenuOpen] = React.useState(null);
  const [scrolled, setScrolled] = React.useState(false);
  const [announcementVisible, setAnnouncementVisible] = React.useState(true);
  const [hoveredSubcat, setHoveredSubcat] = React.useState(null);
  const [hoveredBrand, setHoveredBrand] = React.useState(null);

  // Prava lista želja — broj se osvježava na svaku promjenu
  const [wishVersion, setWishVersion] = React.useState(0);
  React.useEffect(() => {
    const bump = () => setWishVersion(v => v + 1);
    window.addEventListener('obs-wishlist-changed', bump);
    return () => window.removeEventListener('obs-wishlist-changed', bump);
  }, []);
  const wishCount = window.OBS_WISHLIST ? window.OBS_WISHLIST.count() : 0;

  // Meni iz stvarnog kataloga (glavne kategorije + potkategorije + top brendovi).
  const [allCats, setAllCats] = React.useState([]);
  const [brandsTop, setBrandsTop] = React.useState([]);
  React.useEffect(() => {
    if (!window.OBS_API) return;
    window.OBS_API.getCategories().then(setAllCats).catch(() => {});
    window.OBS_API.getBrands().then(bs => setBrandsTop([...bs].sort((a, b) => (b._count?.products || 0) - (a._count?.products || 0)).slice(0, 8))).catch(() => {});
  }, []);
  const topCats = allCats.filter(c => !c.parentId && c.slug !== 'ostalo')
    .sort((a, b) => { const ia = NAV_ORDER.indexOf(a.slug), ib = NAV_ORDER.indexOf(b.slug); return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib); })
    .slice(0, 8)
    .map((c) => {
      const st = (window.OBS_CAT_STYLE ? window.OBS_CAT_STYLE(c.name) : { tint: '#F3EDE3', accent: T.terracotta });
      return { ...c, color: st.tint, hover: st.accent, children: allCats.filter(ch => ch.parentId === c.id) };
    });

  // Announcement traka iz CMS-a (admin: Sadržaj -> Početna strana) — fallback dok se ne učita
  const [announcementItems, setAnnouncementItems] = React.useState([
    "☁ Besplatna dostava za narudžbe preko 50€", "☀ Premium brendovi za bebe i djecu", "📍 City Kvart, Podgorica",
  ]);
  React.useEffect(() => {
    if (window.OBS_API && window.OBS_API.getContent) {
      window.OBS_API.getContent().then(c => { if (c.announcement?.items?.length) setAnnouncementItems(c.announcement.items); });
    }
  }, []);

  // Na mobilnom se announcement stavke rotiraju (jedna po jedna, ne stanu sve u red)
  const [annIdx, setAnnIdx] = React.useState(0);
  React.useEffect(() => {
    if (announcementItems.length < 2) return;
    const id = setInterval(() => setAnnIdx(i => (i + 1) % announcementItems.length), 3500);
    return () => clearInterval(id);
  }, [announcementItems.length]);

  React.useEffect(() => {
    const el = document.getElementById('obs-scroll-container') || window;
    const onScroll = () => setScrolled((el.scrollTop || window.scrollY) > 60);
    el.addEventListener('scroll', onScroll);
    return () => el.removeEventListener('scroll', onScroll);
  }, []);

  const goCart = onCartOpen || (() => { window.location.href = navUrl('cart.html'); });

  // --- Mobilni: hamburger + drawer (višenivo) + donja traka ---
  const isMobile = window.OBS_useIsMobile ? window.OBS_useIsMobile(900) : false;
  // Cookie saglasnost — prikazuje se dok kupac ne prihvati (čuva se u localStorage).
  const [cookieOk, setCookieOk] = React.useState(() => { try { return !!localStorage.getItem('obs_cookie_consent'); } catch { return true; } });
  const acceptCookies = () => { try { localStorage.setItem('obs_cookie_consent', '1'); } catch {} setCookieOk(true); };
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [navStack, setNavStack] = React.useState([]); // stek kategorija za "next next" navigaciju
  const [mSearch, setMSearch] = React.useState('');

  // Djeca trenutnog nivoa: prazan stek = glavne kategorije, inače djeca posljednjeg u steku.
  const drawerParent = navStack[navStack.length - 1] || null;
  const drawerItems = drawerParent
    ? allCats.filter(ch => ch.parentId === drawerParent.id).map(c => ({ ...c, children: allCats.filter(x => x.parentId === c.id) }))
    : topCats;

  React.useEffect(() => { if (!drawerOpen) { setNavStack([]); setMSearch(''); } }, [drawerOpen]);
  // Zaključaj skrol pozadine dok je drawer otvoren
  React.useEffect(() => { document.body.style.overflow = drawerOpen ? 'hidden' : ''; return () => { document.body.style.overflow = ''; }; }, [drawerOpen]);
  // Prostor za donju traku da ne prekriva sadržaj
  React.useEffect(() => {
    const sc = document.getElementById('obs-scroll-container');
    const pad = isMobile ? '68px' : '';
    document.body.style.paddingBottom = pad;
    if (sc) sc.style.paddingBottom = pad;
    return () => { document.body.style.paddingBottom = ''; if (sc) sc.style.paddingBottom = ''; };
  }, [isMobile]);

  const submitMSearch = (e) => { e.preventDefault(); const q = mSearch.trim(); if (q) window.location.href = navUrl('search.html?q=' + encodeURIComponent(q)); };

  return (
    <div onMouseLeave={() => setMegaMenuOpen(null)} style={{ position: 'sticky', top: 0, zIndex: 150 }}>
      {/* Announcement — sakriva se na skrol nadole i na ✕ (glatka max-height animacija) */}
      <div style={{ maxHeight: (announcementVisible && !scrolled) ? 46 : 0, overflow: 'hidden', transition: 'max-height 0.45s cubic-bezier(0.16,1,0.3,1)' }}>
        <div style={{ background: `linear-gradient(90deg, ${T.terracottaDark}, ${T.terracotta}, ${T.terracottaDark})`, color: 'white', padding: isMobile ? '8px 36px' : '9px 40px', fontSize: 11, letterSpacing: 0.5, display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 28, position: 'relative', textAlign: 'center' }}>
          {isMobile ? (
            <span key={annIdx} style={{ animation: 'fadeInUp 0.5s ease', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>{announcementItems[annIdx % announcementItems.length]}</span>
          ) : announcementItems.map((item, i) => (
            <React.Fragment key={i}>
              {i > 0 && <span style={{ opacity: 0.3 }}>|</span>}
              <span>{item}</span>
            </React.Fragment>
          ))}
          <button onClick={() => setAnnouncementVisible(false)} style={{ position: 'absolute', right: 12, background: 'none', border: 'none', color: 'rgba(255,255,255,0.6)', cursor: 'pointer', fontSize: 13 }}>✕</button>
        </div>
      </div>

      {/* Main Nav — bijela podloga sa suptilnim oblak+sunce motivom */}
      <div style={{ position: 'relative', overflow: 'hidden', background: scrolled ? 'rgba(255,255,255,0.96)' : 'rgba(255,255,255,0.88)', backdropFilter: 'blur(20px)', boxShadow: scrolled ? '0 6px 24px rgba(45,41,38,0.07)' : 'none', transition: 'all 0.35s ease' }}>
        {/* Motiv: topli sjaj izlaska sunca + tanke zrake + nježan oblak (jedva vidljiv, brend identitet) */}
        <div aria-hidden="true" style={{ position: 'absolute', inset: 0, zIndex: 0, pointerEvents: 'none', background: 'radial-gradient(120px 120px at calc(100% - 90px) 30%, rgba(232,184,77,0.16), rgba(232,184,77,0) 70%)' }}>
          <svg viewBox="0 0 420 140" preserveAspectRatio="xMaxYMid slice" style={{ position: 'absolute', right: 0, top: 0, height: '100%', width: 460 }}>
            {/* sunce */}
            <g stroke="#D4A843" strokeWidth="1.5" strokeLinecap="round" fill="none" opacity="0.22">
              <circle cx="360" cy="52" r="15" />
              <line x1="360" y1="22" x2="360" y2="31" /><line x1="360" y1="73" x2="360" y2="82" />
              <line x1="330" y1="52" x2="339" y2="52" /><line x1="381" y1="52" x2="390" y2="52" />
              <line x1="339" y1="31" x2="345" y2="37" /><line x1="375" y1="67" x2="381" y2="73" />
              <line x1="339" y1="73" x2="345" y2="67" /><line x1="375" y1="37" x2="381" y2="31" />
            </g>
            {/* oblak */}
            <path d="M250 82 a17 17 0 0 1 33 -6 a13 13 0 0 1 24 4 a15 15 0 0 1 -7 29 h-42 a16 16 0 0 1 -8 -27 z" fill="none" stroke="#C27B6B" strokeWidth="1.5" opacity="0.16" />
          </svg>
        </div>
        {/* Utility bar — sakriva se na skrol nadole i uvijek na mobilnom (ide u drawer) */}
        <div style={{ position: 'relative', zIndex: 1, maxHeight: (isMobile || scrolled) ? 0 : 40, opacity: (isMobile || scrolled) ? 0 : 1, overflow: 'hidden', pointerEvents: (isMobile || scrolled) ? 'none' : 'auto', transition: 'max-height 0.4s cubic-bezier(0.16,1,0.3,1), opacity 0.3s ease' }}>
          <div style={{ maxWidth: 1400, margin: '0 auto', padding: '6px 48px', display: 'flex', justifyContent: 'space-between', fontSize: 11, color: T.textLight, borderBottom: '1px solid rgba(45,41,38,0.04)' }}>
            <div style={{ display: 'flex', gap: 20 }}>
              <a href="tel:+38267230537" style={{ color: T.textLight, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6 }}>{window.OBS_ICON('phone', { size: 13 })} +382 67 230 537</a>
              <a href="mailto:info@oblakisunce.me" style={{ color: T.textLight, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6 }}>{window.OBS_ICON('mail', { size: 13 })} info@oblakisunce.me</a>
            </div>
            <div style={{ display: 'flex', gap: 16 }}>
              <a href={navUrl('kontakt.html')} style={{ color: T.textLight, textDecoration: 'none' }}>Kontakt</a>
              <span style={{ opacity: 0.3 }}>·</span>
              <a href={navUrl('o-nama.html')} style={{ color: T.textLight, textDecoration: 'none' }}>O nama</a>
              <span style={{ opacity: 0.3 }}>·</span>
              <a href={navUrl('blog.html')} style={{ color: T.textLight, textDecoration: 'none' }}>Blog</a>
            </div>
          </div>
        </div>

        <div style={{ position: 'relative', zIndex: 1, maxWidth: 1400, margin: '0 auto', padding: isMobile ? '0 14px' : '0 48px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: isMobile ? 58 : (scrolled ? 60 : 70), transition: 'height 0.3s' }}>
          {isMobile ? (<>
            {/* Mobilni: hamburger — logo (centar) — korpa */}
            <button onClick={() => setDrawerOpen(true)} aria-label="Meni" style={{ width: 42, height: 42, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 4, background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
              <span style={{ width: 22, height: 2, background: T.textDark, borderRadius: 2 }} />
              <span style={{ width: 22, height: 2, background: T.textDark, borderRadius: 2 }} />
              <span style={{ width: 16, height: 2, background: T.textDark, borderRadius: 2 }} />
            </button>
            <a href="/" style={{ position: 'absolute', left: '50%', transform: 'translateX(-50%)', display: 'flex', alignItems: 'center', textDecoration: 'none' }}>
              <img src={window.OBS_LOGO} alt="Oblak i Sunce" style={{ height: 34, objectFit: 'contain' }} />
            </a>
            <button onClick={goCart} aria-label="Korpa" style={{ width: 42, height: 42, borderRadius: '50%', background: 'none', border: 'none', cursor: 'pointer', position: 'relative', color: T.textDark, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              {window.OBS_ICON('bag', { size: 22 })}
              {cartCount > 0 && <span style={{ position: 'absolute', top: 2, right: 0, minWidth: 16, height: 16, padding: '0 3px', borderRadius: 8, background: T.terracotta, color: 'white', fontSize: 9, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{cartCount}</span>}
            </button>
          </>) : (<>
          {/* Logo */}
          <a href="/" style={{ display: 'flex', alignItems: 'center', textDecoration: 'none' }}>
            <img src={window.OBS_LOGO} alt="Oblak i Sunce" style={{ height: scrolled ? 36 : 44, transition: 'height 0.3s', objectFit: 'contain' }} />
          </a>

          {/* Nav Items */}
          <nav style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
            {topCats.map((cat, i) => (
              <a key={cat.id} href={navUrl(`category.html?cat=${encodeURIComponent(cat.slug)}`)} onMouseEnter={() => setMegaMenuOpen(i)}
                style={{ fontFamily: "'Outfit', sans-serif", fontSize: 11.5, fontWeight: 500, letterSpacing: '0.1em', textTransform: 'uppercase', color: megaMenuOpen === i ? T.terracotta : T.textDark, cursor: 'pointer', padding: '6px 0 20px', textDecoration: 'none', transition: 'color 0.3s', position: 'relative' }}>
                {navLabel(cat.name)}
                <span style={{ position: 'absolute', bottom: 12, left: '50%', transform: 'translateX(-50%)', width: megaMenuOpen === i ? '100%' : 0, height: 2, background: T.terracotta, borderRadius: 2, transition: 'width 0.35s cubic-bezier(0.16,1,0.3,1)', display: 'block' }} />
              </a>
            ))}
            <a href={navUrl('brands.html')} onMouseEnter={() => setMegaMenuOpen(null)}
              style={{ fontFamily: "'Outfit', sans-serif", fontSize: 11.5, fontWeight: 500, letterSpacing: '0.1em', textTransform: 'uppercase', color: T.terracotta, cursor: 'pointer', textDecoration: 'none', padding: '6px 0 20px', position: 'relative' }}>
              Brendovi
            </a>
          </nav>

          {/* Actions */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <a href={navUrl('search.html')} title="Pretraga" style={{ width: 40, height: 40, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', textDecoration: 'none', color: T.textDark }}>{window.OBS_ICON('search', { size: 19 })}</a>
            <a href={navUrl('wishlist.html')} title="Lista želja" style={{ width: 40, height: 40, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', textDecoration: 'none', position: 'relative', color: T.textDark }}>
              {window.OBS_ICON('heart', { size: 19 })}
              {wishCount > 0 && <span style={{ position: 'absolute', top: 4, right: 2, width: 15, height: 15, borderRadius: '50%', background: T.terracotta, color: 'white', fontSize: 8, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{wishCount}</span>}
            </a>
            <a href={navUrl('account.html')} title="Moj nalog" style={{ width: 40, height: 40, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', textDecoration: 'none', color: T.textDark }}>{window.OBS_ICON('user', { size: 19 })}</a>
            <button onClick={goCart} title="Korpa" style={{ height: 40, borderRadius: 40, background: T.terracotta, border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 7, padding: '0 16px 0 13px', color: 'white' }}>
              {window.OBS_ICON('bag', { size: 17 })}
              <span style={{ color: 'white', fontSize: 11, fontWeight: 600, fontFamily: "'Outfit', sans-serif" }}>{cartCount}</span>
            </button>
          </div>
          </>)}
        </div>
        {/* Tanka gradijent linija na dnu — brend akcent (terakota → nebo) */}
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 2, zIndex: 2, background: 'linear-gradient(90deg, transparent, rgba(194,123,107,0.45), rgba(107,163,199,0.40), rgba(232,184,77,0.40), transparent)' }} />
      </div>

      {/* Mega Menu — samo desktop (na mobilnom je drawer) */}
      {!isMobile && megaMenuOpen !== null && topCats[megaMenuOpen] && (() => {
        const active = topCats[megaMenuOpen];
        return (
        <div style={{ position: 'absolute', top: '100%', left: 0, right: 0, background: 'white', borderBottom: '1px solid rgba(45,41,38,0.06)', boxShadow: '0 24px 64px rgba(0,0,0,0.08)', paddingTop: 40, paddingBottom: 36, animation: 'slideDown 0.3s cubic-bezier(0.16,1,0.3,1)' }}>
          <div style={{ maxWidth: 1400, margin: '0 auto', padding: '0 48px', display: 'grid', gridTemplateColumns: '1fr 1fr 280px', gap: 48 }}>
            <div>
              <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 600, marginBottom: 18, color: T.textDark }}>{active.name}</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 24px' }}>
                {active.children.length === 0 && <span style={{ fontSize: 13, color: T.textLight }}>Pogledaj sve →</span>}
                {active.children.map((sub, i) => (
                  <a key={sub.id} href={navUrl(`category.html?cat=${encodeURIComponent(sub.slug)}`)}
                    onMouseEnter={() => setHoveredSubcat(i)} onMouseLeave={() => setHoveredSubcat(null)}
                    style={{ display: 'block', width: '100%', textAlign: 'left', padding: '7px 0', fontFamily: "'Outfit', sans-serif", fontSize: 14, color: hoveredSubcat === i ? active.hover : T.textMid, textDecoration: 'none', cursor: 'pointer', transition: 'all 0.2s', paddingLeft: hoveredSubcat === i ? 6 : 0 }}>{sub.name}</a>
                ))}
              </div>
            </div>
            <div>
              <h4 style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.15em', textTransform: 'uppercase', color: T.textLight, marginBottom: 14 }}>Naši brendovi</h4>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {brandsTop.map((b, i) => (
                  <a key={b.id} href={navUrl(`brand-detail.html?id=${b.slug}`)} onMouseEnter={() => setHoveredBrand(i)} onMouseLeave={() => setHoveredBrand(null)}
                    style={{ padding: '5px 13px', borderRadius: 20, border: `1px solid ${hoveredBrand === i ? active.hover : 'rgba(45,41,38,0.08)'}`, fontSize: 12, fontWeight: 500, cursor: 'pointer', textDecoration: 'none', transition: 'all 0.25s', background: hoveredBrand === i ? active.hover : 'white', color: hoveredBrand === i ? 'white' : T.textDark }}>{b.name}</a>
                ))}
              </div>
            </div>
            <a href={navUrl(`category.html?cat=${encodeURIComponent(active.slug)}`)}
              style={{ borderRadius: 20, background: `linear-gradient(145deg, ${active.color}, ${active.color}CC)`, padding: 28, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative', overflow: 'hidden', textDecoration: 'none' }}>
              <div>
                <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 600, lineHeight: 1.2, marginBottom: 6, color: T.textDark }}>{active.name}</h3>
                <p style={{ fontFamily: "'Outfit', sans-serif", fontSize: 12.5, color: T.textMid }}>Pogledajte kompletnu ponudu iz ove kategorije.</p>
              </div>
              <span style={{ alignSelf: 'flex-start', padding: '9px 22px', borderRadius: 30, background: active.hover, color: 'white', fontSize: 12, fontWeight: 600, fontFamily: "'Outfit', sans-serif", marginTop: 16 }}>Pogledaj →</span>
            </a>
          </div>
        </div>
        );
      })()}

      {/* ===== MOBILNI DRAWER (hamburger meni, višenivo „next next") ===== */}
      {isMobile && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 300, pointerEvents: drawerOpen ? 'auto' : 'none' }}>
          {/* zatamnjenje */}
          <div onClick={() => setDrawerOpen(false)} style={{ position: 'absolute', inset: 0, background: 'rgba(45,41,38,0.5)', opacity: drawerOpen ? 1 : 0, transition: 'opacity 0.3s ease' }} />
          {/* panel */}
          <div style={{ position: 'absolute', top: 0, left: 0, bottom: 0, width: '86%', maxWidth: 380, background: 'white', boxShadow: '4px 0 40px rgba(0,0,0,0.18)', transform: drawerOpen ? 'translateX(0)' : 'translateX(-100%)', transition: 'transform 0.32s cubic-bezier(0.16,1,0.3,1)', display: 'flex', flexDirection: 'column' }}>
            {/* zaglavlje drawera */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: '1px solid rgba(45,41,38,0.07)', minHeight: 58 }}>
              {navStack.length > 0 ? (
                <button onClick={() => setNavStack(navStack.slice(0, -1))} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 15, color: T.textDark, display: 'flex', alignItems: 'center', gap: 6, fontFamily: "'Outfit', sans-serif", fontWeight: 600, padding: 0 }}>
                  <span style={{ fontSize: 20 }}>‹</span> Nazad
                </button>
              ) : (
                <img src={window.OBS_LOGO} alt="Oblak i Sunce" style={{ height: 30, objectFit: 'contain' }} />
              )}
              <button onClick={() => setDrawerOpen(false)} aria-label="Zatvori" style={{ marginLeft: 'auto', width: 34, height: 34, borderRadius: '50%', background: T.cream || '#F3EDE3', border: 'none', cursor: 'pointer', fontSize: 15, color: T.textDark }}>✕</button>
            </div>

            {/* pretraga (samo na root nivou) */}
            {navStack.length === 0 && (
              <form onSubmit={submitMSearch} style={{ padding: '12px 16px', borderBottom: '1px solid rgba(45,41,38,0.06)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: T.cream || '#F3EDE3', borderRadius: 24, padding: '9px 14px', color: T.textMid }}>
                  {window.OBS_ICON('search', { size: 16 })}
                  <input value={mSearch} onChange={e => setMSearch(e.target.value)} placeholder="Pretraži proizvode…" style={{ flex: 1, border: 'none', background: 'none', outline: 'none', fontSize: 14, fontFamily: "'Outfit', sans-serif", color: T.textDark }} />
                </div>
              </form>
            )}

            {/* naslov trenutnog nivoa */}
            {navStack.length > 0 && (
              <a href={navUrl(`category.html?cat=${encodeURIComponent(drawerParent.slug)}`)} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', textDecoration: 'none', background: (window.OBS_CAT_STYLE ? window.OBS_CAT_STYLE(navStack[0].name).tint : '#F3EDE3') }}>
                <span style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 21, fontWeight: 600, color: T.textDark }}>{drawerParent.name}</span>
                <span style={{ fontSize: 12, fontWeight: 600, color: (window.OBS_CAT_STYLE ? window.OBS_CAT_STYLE(navStack[0].name).accent : T.terracotta), fontFamily: "'Outfit', sans-serif" }}>Prikaži sve →</span>
              </a>
            )}

            {/* lista stavki */}
            <div style={{ flex: 1, overflowY: 'auto', WebkitOverflowScrolling: 'touch' }}>
              {drawerItems.map((item) => {
                const hasKids = item.children && item.children.length > 0;
                const topName = navStack.length ? navStack[0].name : item.name;
                const st = window.OBS_CAT_STYLE ? window.OBS_CAT_STYLE(topName) : { accent: T.terracotta };
                const commonStyle = { display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '15px 18px', borderBottom: '1px solid rgba(45,41,38,0.05)', background: 'none', border: 'none', borderBottomWidth: 1, borderBottomStyle: 'solid', borderBottomColor: 'rgba(45,41,38,0.05)', cursor: 'pointer', textAlign: 'left', textDecoration: 'none', fontFamily: "'Outfit', sans-serif", fontSize: 15, color: T.textDark };
                const dot = <span style={{ width: 9, height: 9, borderRadius: '50%', background: st.accent, flexShrink: 0 }} />;
                return hasKids ? (
                  <button key={item.id} onClick={() => setNavStack([...navStack, item])} style={commonStyle}>
                    {navStack.length === 0 && dot}
                    <span style={{ flex: 1 }}>{item.name}</span>
                    <span style={{ fontSize: 20, color: T.textLight }}>›</span>
                  </button>
                ) : (
                  <a key={item.id} href={navUrl(`category.html?cat=${encodeURIComponent(item.slug)}`)} style={commonStyle}>
                    {navStack.length === 0 && dot}
                    <span style={{ flex: 1 }}>{item.name}</span>
                  </a>
                );
              })}

              {/* dodatni linkovi — samo na root nivou */}
              {navStack.length === 0 && (
                <div style={{ padding: '8px 0 24px' }}>
                  <a href={navUrl('brands.html')} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '15px 18px', textDecoration: 'none', fontFamily: "'Outfit', sans-serif", fontSize: 15, fontWeight: 600, color: T.terracotta, borderBottom: '1px solid rgba(45,41,38,0.05)' }}>
                    {window.OBS_ICON('tag', { size: 18 })} Svi brendovi
                  </a>
                  <div style={{ padding: '16px 18px 4px', fontSize: 10, letterSpacing: '0.15em', textTransform: 'uppercase', color: T.textLight, fontWeight: 600 }}>Informacije</div>
                  {[['o-nama.html', 'O nama'], ['kontakt.html', 'Kontakt'], ['blog.html', 'Blog']].map(([href, label]) => (
                    <a key={href} href={navUrl(href)} style={{ display: 'block', padding: '12px 18px', textDecoration: 'none', fontFamily: "'Outfit', sans-serif", fontSize: 14.5, color: T.textMid }}>{label}</a>
                  ))}
                  <div style={{ display: 'flex', gap: 10, padding: '14px 18px 0' }}>
                    <a href={navUrl('account.html')} style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, padding: '11px', borderRadius: 12, background: T.textDark, color: 'white', textDecoration: 'none', fontFamily: "'Outfit', sans-serif", fontSize: 13, fontWeight: 600 }}>{window.OBS_ICON('user', { size: 16 })} Moj nalog</a>
                    <a href={navUrl('wishlist.html')} style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, padding: '11px', borderRadius: 12, background: T.cream || '#F3EDE3', color: T.textDark, textDecoration: 'none', fontFamily: "'Outfit', sans-serif", fontSize: 13, fontWeight: 600 }}>{window.OBS_ICON('heart', { size: 16 })} Lista želja{wishCount > 0 ? ` (${wishCount})` : ''}</a>
                  </div>
                  <div style={{ padding: '18px', fontSize: 11.5, color: T.textLight, lineHeight: 1.6, display: 'flex', flexDirection: 'column', gap: 6 }}>
                    <a href="tel:+38267230537" style={{ color: T.textLight, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 7 }}>{window.OBS_ICON('phone', { size: 14 })} +382 67 230 537</a>
                    📍 City Kvart, Podgorica
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ===== MOBILNA DONJA TRAKA (sticky bottom nav) ===== */}
      {isMobile && (
        <div style={{ position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 200, background: 'rgba(255,255,255,0.97)', backdropFilter: 'blur(16px)', borderTop: '1px solid rgba(45,41,38,0.08)', boxShadow: '0 -4px 20px rgba(45,41,38,0.06)', display: 'flex', paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}>
          {(() => {
            const Item = ({ href, onClick, icon, label, badge, primary }) => {
              const inner = (<>
                <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1, color: primary ? T.terracotta : T.textDark }}>
                  {window.OBS_ICON(icon, { size: 23, stroke: primary ? 1.9 : 1.7 })}
                  {badge > 0 && <span style={{ position: 'absolute', top: -6, right: -10, minWidth: 15, height: 15, padding: '0 3px', borderRadius: 8, background: T.terracotta, color: 'white', fontSize: 8.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{badge}</span>}
                </div>
                <span style={{ fontSize: 9.5, fontFamily: "'Outfit', sans-serif", fontWeight: 500, color: T.textMid, letterSpacing: '0.02em' }}>{label}</span>
              </>);
              const base = { flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '9px 0 8px', background: 'none', border: 'none', cursor: 'pointer', textDecoration: 'none' };
              return onClick ? <button onClick={onClick} style={base}>{inner}</button> : <a href={href} style={base}>{inner}</a>;
            };
            return (<>
              <Item href="/" icon="home" label="Početna" />
              <Item href={navUrl('search.html')} icon="search" label="Pretraga" />
              <Item onClick={goCart} icon="bag" label="Korpa" badge={cartCount} primary />
              <Item href={navUrl('wishlist.html')} icon="heart" label="Želje" badge={wishCount} />
              <Item href={navUrl('account.html')} icon="user" label="Nalog" />
            </>);
          })()}
        </div>
      )}
      {/* ===== COOKIE SAGLASNOST ===== */}
      {!cookieOk && (
        <div style={{ position: 'fixed', left: isMobile ? 12 : 20, right: isMobile ? 12 : 'auto', bottom: isMobile ? 80 : 20, zIndex: 250, maxWidth: 380, background: 'white', borderRadius: 16, padding: '16px 18px', boxShadow: '0 12px 40px rgba(45,41,38,0.18)', border: '1px solid rgba(45,41,38,0.06)', animation: 'fadeInUp 0.4s ease' }}>
          <div style={{ fontFamily: "'Outfit', sans-serif", fontSize: 12.5, color: T.textMid, lineHeight: 1.6, marginBottom: 12 }}>
            🍪 Koristimo kolačiće da bismo poboljšali vaše iskustvo kupovine. Nastavkom pregleda prihvatate njihovu upotrebu. Više u <a href={navUrl('legal.html?page=politika-kolacica')} style={{ color: T.terracotta, fontWeight: 600 }}>Politici kolačića</a>.
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={acceptCookies} style={{ flex: 1, padding: '10px', borderRadius: 10, background: T.terracotta, color: 'white', border: 'none', cursor: 'pointer', fontFamily: "'Outfit', sans-serif", fontSize: 13, fontWeight: 600 }}>Prihvatam</button>
            <a href={navUrl('legal.html?page=politika-kolacica')} style={{ padding: '10px 14px', borderRadius: 10, background: T.cream || '#F3EDE3', color: T.textDark, textDecoration: 'none', fontFamily: "'Outfit', sans-serif", fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center' }}>Saznaj više</a>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Header });
