/* SUPERMEDIA storefront — Home */
function HeroCarousel({ slides, onNav, interval = 5500 }) {
  const { useState: uS, useEffect: uE } = React;
  const isMobile = useIsMobile();
  const [idx, setIdx] = uS(0);
  const [hover, setHover] = uS(false);
  const n = slides.length;
  uE(() => {
    if (n <= 1 || hover) return;
    const t = setInterval(() => setIdx(i => (i + 1) % n), interval);
    return () => clearInterval(t);
  }, [n, hover, interval]);
  const go = (d, e) => { if (e) e.stopPropagation(); setIdx(i => (i + d + n) % n); };
  const arrow = (side) => ({
    position: 'absolute', top: '50%', [side]: 12, transform: `translateY(-50%) translateX(${hover ? '0' : side === 'left' ? '-8px' : '8px'})`,
    width: 44, height: 44, borderRadius: '50%', border: 'none', cursor: 'pointer', zIndex: 3,
    background: 'rgba(255,255,255,.82)', backdropFilter: 'blur(6px)', color: 'var(--sm-text)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--sm-shadow-md)',
    opacity: hover ? 1 : 0, pointerEvents: hover ? 'auto' : 'none', transition: 'opacity .25s ease, transform .25s ease, background .15s',
  });
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      <div style={{ position: 'relative', borderRadius: isMobile ? '0 0 var(--sm-radius-xl) var(--sm-radius-xl)' : 'var(--sm-radius-xl)', overflow: 'hidden', boxShadow: isMobile ? 'none' : 'var(--sm-shadow-sm)', aspectRatio: isMobile ? '16 / 11' : '3 / 2' }}>
        {slides.map((sl, i) => (
          <a key={i} onClick={() => onNav(sl.nav)} style={{ position: 'absolute', inset: 0, cursor: 'pointer', opacity: i === idx ? 1 : 0, pointerEvents: i === idx ? 'auto' : 'none', transition: 'opacity .55s ease' }}>
            <img src={sl.img} alt={sl.alt} style={{ display: 'block', width: '100%', height: '100%', objectFit: 'cover' }} />
          </a>
        ))}
        {n > 1 && (
          <React.Fragment>
            <button onClick={e => go(-1, e)} aria-label="Prethodni baner" style={arrow('left')}
              onMouseEnter={e => e.currentTarget.style.background = '#fff'} onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,.82)'}>{I('chevron-left', 24)}</button>
            <button onClick={e => go(1, e)} aria-label="Sledeći baner" style={arrow('right')}
              onMouseEnter={e => e.currentTarget.style.background = '#fff'} onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,.82)'}>{I('chevron-right', 24)}</button>
          </React.Fragment>
        )}
      </div>
      {n > 1 && (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8, marginTop: 14 }}>
          {slides.map((_, i) => (
            <button key={i} onClick={() => setIdx(i)} aria-label={'Baner ' + (i + 1)} style={{
              height: 7, width: i === idx ? 26 : 7, borderRadius: 'var(--sm-radius-pill)', border: 'none', padding: 0, cursor: 'pointer',
              background: i === idx ? 'var(--sm-primary)' : 'var(--sm-purple-100)', transition: 'width .3s ease, background .3s ease',
            }}></button>
          ))}
        </div>
      )}
    </div>
  );
}

function Home({ onNav, onAdd, onWish, wishlist, openProduct }) {
  const { CATEGORIES, BRANDS, PRODUCTS, A } = SM_DATA;
  const isMobile = useIsMobile();
  const bn = SM_DATA.BANNERS || {};
  // link banera (iz admina/starog sajta) -> navigacija UNUTAR novog sajta (nikad spoljašnji stari sajt)
  const resolveBannerNav = (link, fb) => {
    if (!link) return fb;
    const pth = String(link).replace(/^https?:\/\/(www\.)?[^/]+/i, '').replace(/^\/+/, '').replace(/\.html?($|[?#]).*/i, '').toLowerCase();
    if (!pth || pth === 'index') return { view: 'home' };
    const segs = pth.split(/[\/?#&=]+/).filter(Boolean);
    const cats = (CATEGORIES || []).map(c => c.slug);
    for (const s of segs) if (cats.indexOf(s) >= 0) return { view: 'category', slug: s };
    const brs = [...new Set((PRODUCTS || []).map(p => String(p.brand || '').toLowerCase()).filter(x => x.length >= 3))];
    for (const s of segs) for (const b of brs) if (s.indexOf(b) >= 0) return { view: 'category', brand: b.toUpperCase() };
    return fb;
  };
  // baneri iz admina za dati slot -> ako postoje koristi njih (link -> interna navigacija), inače fallback (dizajn slike)
  const adminSlides = (slot, fb) => {
    const s = bn[slot];
    if (!s || !s.length) return fb;
    const defNav = (fb[0] && fb[0].nav) || { view: 'category', slug: null };
    return s.map(x => ({ img: x.url, alt: '', nav: resolveBannerNav(x.link, defNav) }));
  };
  const wide = { maxWidth: 1440, margin: '0 auto', padding: isMobile ? '0 14px' : '0 24px' };
  const best = PRODUCTS.slice(0, 4);
  const recos = PRODUCTS.slice(4, 8);

  return (
    <div style={{ paddingBottom: 8 }}>
      <div style={{ ...wide, paddingTop: isMobile ? 0 : 24 }}>
        {/* hero: banner carousels (single, edge-to-edge "coming out of the header" on mobile) */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))', gap: 20, margin: isMobile ? '0 -4px' : 0 }}>
          <HeroCarousel onNav={onNav} slides={adminSlides('baner-levo', [
            { img: A + '/banners/beko-kuhinja.png', alt: 'Bela tehnika', nav: { view: 'category', slug: 'bela-tehnika' } },
            { img: A + '/promo-home-equipment.png', alt: 'Novi dom', nav: { view: 'category', slug: 'bela-tehnika' } },
          ])} />
          {!isMobile && <HeroCarousel onNav={onNav} slides={adminSlides('baner-desno', [
            { img: A + '/banners/honor-600.png', alt: 'HONOR 600 Series', nav: { view: 'category', slug: 'telefoni' } },
            { img: A + '/promo-beauty.png', alt: 'Lepota i zdravlje', nav: { view: 'category', slug: 'lepota' } },
          ])} />}
        </div>

        {/* category grid */}
        <h3 style={{ fontSize: isMobile ? 21 : 28, fontWeight: 600, margin: isMobile ? '28px 0 14px' : '40px 0 18px' }}>Kupuj po kategorijama</h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: isMobile ? 12 : 16 }}>
          {CATEGORIES.map(c => <CategoryTile key={c.slug} title={c.title} image={c.img} cover={c.cover} imgStyle={c.imgStyle} color={c.color} height={isMobile ? 138 : 180} onClick={() => onNav({ view: 'cathub', slug: c.slug })} />)}
        </div>

        {/* benefits band */}
        <div style={{ marginTop: 32 }}><HomeBenefits onNav={onNav} /></div>

        {/* best sellers */}
        <Section title="Najprodavaniji proizvodi" onAll={() => onNav({ view: 'category', slug: null })}>
          <Row products={best} {...{ onAdd, onWish, wishlist, openProduct }} />
        </Section>

        {/* B2B promo band — brutal scroll-driven planet scene */}
        <div style={{ marginTop: 44 }}>
          <B2BPlanetBanner onNav={onNav} />
        </div>

        {/* SUPER recommendation */}
        <Section title="Po SUPER preporuci!" onAll={() => onNav({ view: 'category', slug: null })}>
          <Row products={recos} {...{ onAdd, onWish, wishlist, openProduct }} />
        </Section>

        {/* three lifestyle promo banners */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20, marginTop: 44 }}>
          {[
            { img: 'banners/promo-lepota.jpg', alt: 'Ritual lepote', accent: 'var(--sm-primary)', nav: { view: 'page', key: 'lifestyle-lepota' } },
            { img: 'banners/promo-novidom.jpg', alt: 'Novi dom', accent: '#3f7d4f', nav: { view: 'page', key: 'lifestyle-novidom' } },
            { img: 'banners/promo-sport.jpg', alt: 'Sport i avantura', accent: '#3f6b86', nav: { view: 'page', key: 'lifestyle-sport' } },
          ].map(b => (
            <a key={b.img} onClick={() => onNav(b.nav)} style={{ position: 'relative', display: 'block', borderRadius: 'var(--sm-radius-xl)', overflow: 'hidden', cursor: 'pointer', boxShadow: 'var(--sm-shadow-md)' }}>
              <img src={A + '/' + b.img} alt={b.alt} style={{ display: 'block', width: '100%', height: 'auto' }} />
              <span style={{ position: 'absolute', right: 18, bottom: 16, display: 'inline-flex', alignItems: 'center', gap: 6, height: 34, padding: '0 14px', borderRadius: 'var(--sm-radius-pill)', background: '#fff', color: b.accent, fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 13, boxShadow: 'var(--sm-shadow-md)', transition: 'transform .18s, box-shadow .18s' }}
                onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = 'var(--sm-shadow-lg)'; }}
                onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'var(--sm-shadow-md)'; }}>Istraži ponudu {I('arrow-right', 15)}</span>
            </a>
          ))}
        </div>

        {/* brands — auto-scrolling logo marquee */}
        <h3 style={{ fontSize: 28, fontWeight: 600, margin: '44px 0 18px' }}>Istraži različite brendove</h3>
        <BrandMarquee onNav={onNav} />
      </div>
    </div>
  );
}

function Section({ title, onAll, children }) {
  return (
    <div style={{ marginTop: 44 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18 }}>
        <h3 style={{ fontSize: 28, fontWeight: 600, margin: 0 }}>{title}</h3>
        <a onClick={onAll} style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 15, color: 'var(--sm-primary)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>Pogledaj sve {I('arrow-right', 16)}</a>
      </div>
      {children}
    </div>
  );
}

function Row({ products, onAdd, onWish, wishlist, openProduct }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
      {products.map(p => <ProductCard key={p.id} p={p} onAdd={onAdd} onWish={onWish} wished={wishlist.includes(p.id)} onOpen={openProduct} />)}
    </div>
  );
}

function HomeBenefits({ onNav }) {
  const isMobile = useIsMobile();
  const primary = [
    { ic: 'truck', t: 'Brza isporuka', s: 'Od 3 do 6 radnih dana' },
    { ic: 'rotate-ccw', t: 'Povrat 14 dana', s: 'Bez objašnjenja' },
    { ic: 'package-search', t: 'Prati status porudžbine', s: 'Unesi kod i vidi gde je paket' },
  ];
  return (
    <div style={{ background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-lg)', padding: isMobile ? '8px 16px' : '22px 26px' }}>
      {/* primary benefits */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 0 : 16 }}>
        {primary.map((x, i) => {
          const isTrack = x.ic === 'package-search';
          return (
          <div key={i} style={{
            position: 'relative',
            display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left',
            padding: isMobile ? '14px 0' : '4px 0',
            borderRight: !isMobile && i < 2 ? '1px solid var(--sm-border)' : 'none',
            borderTop: isMobile && i > 0 ? '1px solid var(--sm-border)' : 'none',
          }}>
            <span style={{ width: 46, height: 46, flex: 'none', borderRadius: '50%', background: 'var(--sm-purple-50)', color: 'var(--sm-primary)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{I(x.ic, 22)}</span>
            <span style={{ flex: 1, minWidth: 0 }}>
              <span style={{ display: 'block', fontFamily: 'var(--sm-font-display)', fontWeight: 600, fontSize: 15.5 }}>{x.t}</span>
              <span style={{ display: 'block', fontSize: 13, color: 'var(--sm-text-muted)' }}>{x.s}</span>
            </span>
            {isTrack && isMobile && (
              <button onClick={() => onNav({ view: 'page', key: 'prati-porudzbinu' })} style={{ flex: 'none', height: 40, padding: '0 20px', borderRadius: 'var(--sm-radius-pill)', border: 'none', background: 'var(--sm-primary)', color: '#fff', fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 14, cursor: 'pointer' }}>Prati</button>
            )}
            {isTrack && !isMobile && (
              <button onClick={() => onNav({ view: 'page', key: 'prati-porudzbinu' })} aria-label="Prati porudžbinu" style={{ position: 'absolute', inset: 0, background: 'none', border: 'none', cursor: 'pointer' }}></button>
            )}
          </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { Home });

const BRAND_LOGOS = [
  { name: 'Bosch', src: 'brands/bosch.png' },
  { name: 'Gorenje', src: 'brands/gorenje.png' },
  { name: 'Electrolux', src: 'brands/electrolux.png' },
  { name: 'LG', src: 'brands/lg.png', maxH: '42%', maxW: '60%' },
  { name: 'Haier', src: 'brands/haier.png', maxH: '38%', maxW: '54%' },
  { name: 'Tesla', src: 'brands/tesla.png' },
  { name: 'ASUS', src: 'brands/asus.png', maxH: '34%', maxW: '50%' },
  { name: 'Lenovo', src: 'brands/lenovo.png' },
  { name: 'HONOR', src: 'brands/honor.png' },
  { name: 'Apple', src: 'brands/apple.png', maxH: '36%', maxW: '40%' },
  { name: 'Kärcher', src: 'brands/karcher.png' },
  { name: 'Samsung', src: 'brands/samsung.png', maxH: '34%', maxW: '64%' },
  { name: 'Beko', src: 'brands/beko.png', maxH: '52%', maxW: '46%' },
  { name: 'Whirlpool', src: 'brands/whirlpool.png', maxH: '46%', maxW: '64%' },
  { name: 'Candy', src: 'brands/candy.png', maxH: '40%', maxW: '64%' },
  { name: 'Midea', src: 'brands/midea.png', maxH: '50%', maxW: '60%' },
  { name: 'Elica', src: 'brands/elica.png', maxH: '34%', maxW: '52%' },
  { name: 'DeLonghi', src: 'brands/delonghi.png', maxH: '34%', maxW: '60%' },
  { name: 'Vivax', src: 'brands/vivax.png', maxH: '34%', maxW: '54%' },
  { name: 'Canon', src: 'brands/canon.png', maxH: '34%', maxW: '58%' },
  { name: 'JBL', src: 'brands/jbl.png', maxH: '52%', maxW: '40%' },
  { name: 'GoPro', src: 'brands/gopro.png', maxH: '44%', maxW: '50%' },
  { name: 'FOX', src: 'brands/fox.png', maxH: '44%', maxW: '52%' },
  { name: 'Linea', src: 'brands/linea.png', maxH: '36%', maxW: '50%' },
  { name: 'Xiaomi', src: 'brands/xiaomi.png', maxH: '46%', maxW: '30%' },
  { name: 'Cecotec', src: 'brands/cecotec.png', maxH: '30%', maxW: '60%' },
  { name: 'Ufesa', src: 'brands/ufesa.png', maxH: '40%', maxW: '46%' },
  { name: 'Beper', src: 'brands/beper.png', maxH: '32%', maxW: '58%' },
];

function BrandMarquee({ onNav }) {
  const A = SM_DATA.A;
  const go = onNav || (() => {});
  const N = BRAND_LOGOS.length;
  const loop = [...BRAND_LOGOS, ...BRAND_LOGOS];
  const CARD = 217, GAP = 18, STEP = CARD + GAP;
  const [idx, setIdx] = React.useState(0);
  const [anim, setAnim] = React.useState(true);
  const [paused, setPaused] = React.useState(false);
  // advance one brand every ~2.4s (the slide itself takes .6s, then it waits)
  React.useEffect(() => {
    if (paused) return;
    const t = setInterval(() => setIdx(i => i + 1), 2400);
    return () => clearInterval(t);
  }, [paused]);
  // when a full set has scrolled past, snap back to 0 with no transition
  React.useEffect(() => {
    if (idx >= N) {
      const t = setTimeout(() => { setAnim(false); setIdx(0); }, 650);
      return () => clearTimeout(t);
    }
    if (!anim) {
      const r = requestAnimationFrame(() => requestAnimationFrame(() => setAnim(true)));
      return () => cancelAnimationFrame(r);
    }
  }, [idx, anim, N]);
  return (
    <div className="sm-mq" style={{ overflow: 'hidden', padding: '8px 0' }}
      onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
      <div style={{
        display: 'flex', gap: GAP, width: 'max-content',
        transform: `translateX(${-idx * STEP}px)`,
        transition: anim ? 'transform .6s cubic-bezier(.45,0,.15,1)' : 'none',
      }}>
        {loop.map((b, i) => (
          <div key={i} title={b.name} onClick={() => go({ view: 'category', brand: b.name })} style={{
            flex: 'none', width: CARD, height: 150, background: '#fff', border: '1px solid var(--sm-border)',
            borderRadius: 'var(--sm-radius-lg)', boxShadow: 'var(--sm-shadow-sm)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'transform .18s, box-shadow .18s, border-color .18s',
          }}
            onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-3px)'; e.currentTarget.style.boxShadow = 'var(--sm-shadow-md)'; e.currentTarget.style.borderColor = 'var(--sm-purple-300)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'var(--sm-shadow-sm)'; e.currentTarget.style.borderColor = 'var(--sm-border)'; }}>
            <img src={A + '/' + b.src} alt={b.name} style={{ maxWidth: b.maxW || '70%', maxHeight: b.maxH || '50%', objectFit: 'contain', pointerEvents: 'none' }} />
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { BrandMarquee, BRAND_LOGOS });
