// E-shop chrome: header, mobile drawer, slide-in cart, search overlay, footer.
(function () {
  if (typeof React === "undefined") return;
  const DS = window.VElaStvNajmanDesignSystem_bc3fc2;
  const { Button, IconButton, Input } = DS;
  const Icon = window.VNIcon;

  // Sesterský web — medová větev značky (rodinný e-shop s medem a medovinou).
  const HONEY_URL = "https://www.vcelarstvinajman.cz";

  const NAV = [
    { id: "category", label: "Nabídka" },
    { id: "blog", label: "Blog" },
    { id: "about", label: "O chovu" },
    { id: "contact", label: "Kontakt" },
    { id: "med", label: "Med", external: true, href: HONEY_URL },
  ];

  function Logo({ onClick, footer }) {
    return (
      <a className="kit-logo" onClick={(e) => { e.preventDefault(); onClick && onClick(); }} href="#">
        <svg className="kit-logo__mark" width="38" height="43" viewBox="0 0 48 54" fill="none" aria-hidden="true">
          <path d="M24 2 L45.65 14.5 L45.65 39.5 L24 52 L2.35 39.5 L2.35 14.5 Z" style={{ stroke: "var(--tmavy-med)" }} strokeWidth="2.4" strokeLinejoin="round"/>
          <path d="M24 16 L34.39 22 L34.39 34 L24 40 L13.61 34 L13.61 22 Z" style={{ fill: "var(--accent)" }}/>
        </svg>
        <span className="kit-logo__wm">
          <span className="a">Včelařství Najman</span>
          <span className="b">Chov matek · Hostivice</span>
        </span>
      </a>
    );
  }

  function ProfileMenu({ user, go, onLogout, onClose }) {
    return (
      <div className="kit-pmenu" data-open="true">
        <div className="kit-pmenu__head">
          <span className="kit-pmenu__name">{user.firstName} {user.lastName}</span>
          <span className="kit-pmenu__email">{user.email}</span>
        </div>
        <button className="kit-pmenu__item" onClick={() => { onClose(); go("account", "profil"); }}>
          <Icon name="user" size={18} /> <span>Můj profil</span>
        </button>
        <button className="kit-pmenu__item" onClick={() => { onClose(); go("account", "objednavky"); }}>
          <Icon name="fileText" size={18} /> <span>Objednávky</span>
        </button>
        <div className="kit-pmenu__sep" />
        <button className="kit-pmenu__item kit-pmenu__item--logout" onClick={() => { onClose(); onLogout(); }}>
          <Icon name="logout" size={18} /> <span>Odhlásit</span>
        </button>
      </div>
    );
  }

  function HeaderProfile({ user, go, onProfile, onLogout }) {
    const [open, setOpen] = React.useState(false);
    const ref = React.useRef(null);
    React.useEffect(() => {
      if (!open) return;
      const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
      const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
      document.addEventListener("mousedown", onDoc);
      window.addEventListener("keydown", onKey);
      return () => { document.removeEventListener("mousedown", onDoc); window.removeEventListener("keydown", onKey); };
    }, [open]);

    if (!user) {
      return (
        <button className="kit-avatarbtn" aria-label="Přihlásit se" title="Přihlásit se" onClick={onProfile}>
          <Icon name="user" />
        </button>
      );
    }
    const initials = ((user.firstName[0] || "") + (user.lastName[0] || "")).toUpperCase();
    return (
      <div className="kit-header__profile" ref={ref}>
        <button className="kit-avatarbtn kit-avatarbtn--in" aria-label="Můj účet" title="Můj účet"
          aria-expanded={open} onClick={() => setOpen((v) => !v)}>
          <span className="kit-avatarbtn__initials">{initials}</span>
        </button>
        {open && <ProfileMenu user={user} go={go} onLogout={onLogout} onClose={() => setOpen(false)} />}
      </div>
    );
  }

  function Header({ go, current, currentArg, cartCount, cartPulse, onCart, onMenu, user, onProfile, onLogout }) {
    const [scrolled, setScrolled] = React.useState(false);
    const [bump, setBump] = React.useState(false);
    React.useEffect(() => {
      if (!cartPulse) return;
      setBump(true);
      const t = setTimeout(() => setBump(false), 360);
      return () => clearTimeout(t);
    }, [cartPulse]);
    React.useEffect(() => {
      const sc = document.querySelector(".kit-scrollroot") || window;
      const t = sc === window ? document.documentElement : sc;
      const fn = () => setScrolled((t.scrollTop || window.scrollY) > 8);
      sc.addEventListener("scroll", fn, { passive: true });
      return () => sc.removeEventListener("scroll", fn);
    }, []);
    return (
      <header className="kit-header" data-scrolled={scrolled}>
        <div className="kit-shell kit-header__bar">
          <IconButton className="kit-header__menu-btn" label="Menu" onClick={onMenu}><Icon name="menu" /></IconButton>
          <Logo onClick={() => go("home")} />
          <nav className="kit-nav">
            {NAV.map((n, i) => n.dropdown ? (
              <div key={i} className="kit-nav__item">
                <button className="kit-nav__drop-trigger" onMouseDown={(e)=>e.preventDefault()} onClick={() => go(n.id)}>
                  {n.label} <Icon name="chevronDown" size={13} style={{ flexShrink: 0 }} />
                </button>
                <div className="kit-nav__dropdown">
                  {n.dropdown.map((d, j) => (
                    <a key={j} href="#"
                       aria-current={current === n.id && (d.arg||null) === (currentArg||null) ? "true" : undefined}
                       onClick={(e)=>{ e.preventDefault(); go(n.id, d.arg); e.currentTarget.blur(); }}>
                      {d.label}
                    </a>
                  ))}
                </div>
              </div>
            ) : n.external ? (
              <a key={i} href={n.href} target="_blank" rel="noopener noreferrer" title="Medový e-shop">
                {n.label}
              </a>
            ) : (
              <a key={i} href="#"
                 aria-current={current === n.id && (n.arg||null) === (currentArg||null) ? "true" : undefined}
                 onClick={(e)=>{ e.preventDefault(); go(n.id, n.arg); }}>{n.label}</a>
            ))}
          </nav>
          <div className="kit-header__actions">
            <HeaderProfile user={user} go={go} onProfile={onProfile} onLogout={onLogout} />
            <button type="button" className="kit-nav__cta" onClick={() => go("rezervace")} style={{ background: "none", border: "none", cursor: "pointer", font: "inherit", color: "inherit", padding: 0 }}>Rezervovat</button>
          </div>
        </div>
      </header>
    );
  }

  function Drawer({ open, onClose, go }) {
    return (
      <>
        <div className="kit-scrim" data-open={open} onClick={onClose} />
        <aside className="kit-drawer" data-open={open} aria-hidden={!open}>
          <div className="kit-drawer__head">
            <Logo onClick={() => { onClose(); go("home"); }} />
            <IconButton label="Zavřít" onClick={onClose}><Icon name="close" /></IconButton>
          </div>
          <nav className="kit-drawer__nav">
            {NAV.map((n, i) => n.dropdown ? (
              <React.Fragment key={i}>
                <span className="kit-drawer__nav-cat">{n.label}</span>
                {n.dropdown.map((d, j) => (
                  <a key={j} href="#" className="kit-drawer__nav-sub"
                     onClick={(e)=>{ e.preventDefault(); onClose(); go(n.id, d.arg); }}>
                    {d.label}<Icon name="chevronRight" size={16} />
                  </a>
                ))}
              </React.Fragment>
            ) : n.external ? (
              <a key={i} href={n.href} target="_blank" rel="noopener noreferrer" title="Medový e-shop">
                {n.label}<Icon name="chevronRight" size={18} />
              </a>
            ) : (
              <a key={i} href="#" onClick={(e)=>{ e.preventDefault(); onClose(); go(n.id, n.arg); }}>
                {n.label}<Icon name="chevronRight" size={18} />
              </a>
            ))}
          </nav>
          <div className="kit-drawer__foot">
            <p style={{ margin: "0 0 6px" }}>Na Samotě 1029, Hostivice</p>
            <a href="#">+420 603 887 482</a>
          </div>
        </aside>
      </>
    );
  }

  function CartLine({ item, onQty, onRemove }) {
    const { Photo, QuantityStepper } = DS;
    return (
      <div className="kit-line">
        <div className="kit-line__thumb"><Photo src={item.image} ratio="1 / 1" label={item.weight} /></div>
        <div className="kit-line__main">
          <p className="kit-line__name">{item.name}</p>
          <p className="kit-line__meta">{item.region} · {item.weight}</p>
          {item.preorder && <p className="kit-line__preorder"><span className="kit-line__preorder-dot" />Předobjednávka — odešleme po naskladnění ({item.preorder})</p>}
          <div className="kit-line__row">
            <QuantityStepper size="sm" value={item.qty} onChange={(v) => onQty(item.id, v)} />
            <span className="kit-line__price">{item.price * item.qty} Kč</span>
          </div>
          <button className="kit-line__remove" onClick={() => onRemove(item.id)}>Odebrat</button>
        </div>
      </div>
    );
  }

  function Cart({ open, onClose, items, onQty, onRemove, onCheckout, onAdd, peek, onClear }) {
    const { Photo } = DS;
    const D = window.SHOP_DATA;
    const total = items.reduce((s, i) => s + i.price * i.qty, 0);
    const count = items.reduce((s, i) => s + i.qty, 0);
    const freeAt = 4;
    const left = Math.max(0, freeAt - count);
    const pct = Math.min(100, (count / freeAt) * 100);

    // "Mohlo by se hodit" — nabízí produkty, které v košíku ještě NEJSOU (podle
    // druhu, napříč variantami — porovnání přes název) a jsou skladem, aby šly
    // rovnou dokoupit. Řazeno dle oblíbenosti, max 3. Sekce zmizí, až jsou
    // v košíku všechny dostupné druhy z nabídky.
    const cartNames = new Set(items.map(i => i.name));
    const cartIds = new Set(items.map(i => i.id));
    const inCart = (p) => cartNames.has(p.name) || cartIds.has(p.id) || items.some(i => String(i.id).indexOf(p.id + "-") === 0);
    const recs = (D && D.products)
      ? D.products.filter(p => !inCart(p) && p.stock !== "out").sort((a,b)=>b.reviews-a.reviews).slice(0,3)
      : [];

    return (
      <>
        <div className="kit-scrim" data-open={open} data-peek={peek ? "true" : undefined} onClick={onClose} style={{ zIndex: "var(--z-cart)" }} />
        <aside className="kit-cart" data-open={open} aria-hidden={!open}>
          <div className="kit-cart__head">
            <h3>Váš košík{count ? ` · ${count}` : ""}</h3>
            {items.length > 0 ? (
              <button className="kit-cart__clear" onClick={onClear} aria-label="Vyprázdnit celý košík">
                <Icon name="trash" size={16} /> Vyprázdnit košík
              </button>
            ) : (
              <IconButton label="Zavřít" onClick={onClose}><Icon name="close" /></IconButton>
            )}
          </div>
          <div className="kit-cart__body">
            {items.length === 0 ? (
              <div className="kit-cart__empty">
                <div style={{ width: 120, margin: "0 auto 18px" }}><Photo ratio="1 / 1" label="Zatím prázdno" /></div>
                <p className="kit-cart__empty-hl">Plástve jsou plné.</p>
                <p>Košík zatím ne. Pojďme to změnit.</p>
                <Button variant="primary" onClick={onClose}>Prohlédnout nabídku</Button>
              </div>
            ) : items.map((it) => (
              <CartLine key={it.id} item={it} onQty={onQty} onRemove={onRemove} />
            ))}
          </div>

          {items.length > 0 && recs.length > 0 && (
            <div className="kit-cart__recs">
              <p className="vn-eyebrow" style={{ margin: "0 0 12px" }}>Mohlo by se hodit</p>
              {recs.map(p => (
                <div key={p.id} className="kit-cart__rec">
                  <div className="kit-cart__rec-thumb">
                    <Photo src={p.image} ratio="1 / 1" label={p.weight} />
                  </div>
                  <div className="kit-cart__rec-info">
                    <span className="kit-cart__rec-name">{p.name}</span>
                    <span className="kit-cart__rec-meta">{p.weight} · {p.price} Kč</span>
                  </div>
                  <button className="kit-cart__rec-btn" onClick={() => onAdd && onAdd(p)} aria-label={"Přidat " + p.name}>
                    <Icon name="plus" size={17} />
                    Do košíku
                  </button>
                </div>
              ))}
            </div>
          )}

          {items.length > 0 && (
            <div className="kit-cart__foot">
              <div className="kit-cart__ship">
                <Icon name="shield" size={18} />
                <span>Matky zasíláme poštou, oddělky a včelstva osobně. Ke každé zásilce <strong>veterinární osvědčení</strong>.</span>
              </div>
              <div className="kit-cart__total"><span>Celkem (s DPH)</span><b>{total} Kč</b></div>
              <Button variant="primary" block size="lg" onClick={onCheckout} iconEnd={<Icon name="arrowRight" size={18} />}>Do pokladny</Button>
            </div>
          )}
        </aside>
      </>
    );
  }

  function Footer({ go }) {
    // Footer links to homepage sections: navigate home, then scroll to the anchor.
    const goHomeTo = (id) => {
      go("home");
      setTimeout(() => {
        const el = document.getElementById(id);
        if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 80, behavior: "smooth" });
      }, 80);
    };
    return (
      <footer className="kit-footer">
        <div className="kit-shell kit-footer__top">
          <div className="kit-footer__brand">
            <Logo onClick={() => go("home")} />
            <p style={{ marginTop: 14 }}>Šlechtitelský chov včelích matek a prodej oddělků z Hostivic. Mírné linie kraňky a vitální Buckfast — s doloženým původem.</p>
            <div className="kit-footer__social">
              <a href="#" aria-label="Instagram"><Icon name="instagram" size={20} /></a>
              <a href="#" aria-label="Facebook"><Icon name="facebook" size={20} /></a>
              <a href="#" aria-label="YouTube"><Icon name="youtube" size={20} /></a>
              <a href="#" aria-label="WhatsApp"><Icon name="whatsapp" size={20} /></a>
            </div>
          </div>
          <div>
            <h4>Nabídka</h4>
            <div className="kit-footer__links">
              <a href="#" onClick={(e)=>{e.preventDefault();go("category","carnica");}}>Kraňské matky</a>
              <a href="#" onClick={(e)=>{e.preventDefault();go("category","buckfast");}}>Buckfast matky</a>
              <a href="#" onClick={(e)=>{e.preventDefault();go("category","inseminace");}}>Inseminované a plemenné</a>
              <a href="#" onClick={(e)=>{e.preventDefault();go("category","oddelky");}}>Oddělky a včelstva</a>
            </div>
          </div>
          <div>
            <h4>Chov</h4>
            <div className="kit-footer__links">
              <a href="#" onClick={(e)=>{e.preventDefault();go("about");}}>Náš chov</a>
              <a href="#" onClick={(e)=>{e.preventDefault();go("blog");}}>Blog o chovu</a>
              <a href="#" onClick={(e)=>{e.preventDefault();go("contact");}}>Převzetí a doprava</a>
              <a href="#" onClick={(e)=>{e.preventDefault();goHomeTo("vn-faq");}}>Časté dotazy</a>
            </div>
          </div>
          <div>
            <h4>Kontakt</h4>
            <div className="kit-footer__contact">
              Na Samotě 1029<br />253 01 Hostivice<br />
              <a href="tel:+420603887482">+420 603 887 482</a><br />
              <a href="mailto:vcelahostivice@seznam.cz">vcelahostivice@seznam.cz</a>
            </div>
          </div>
        </div>
        <div className="kit-shell kit-footer__sister">
          <Icon name="dipper" size={18} />
          <span>Hledáte med? Náš rodinný e-shop s medem a medovinou najdete na <a href={HONEY_URL} target="_blank" rel="noopener noreferrer">Včelařství Najman <Icon name="arrowUpRight" size={14} /></a></span>
        </div>
        <div className="kit-shell kit-footer__bottom">
          <span>© 2026 Rodinné včelařství Najman · IČO 12345678</span>
          <span style={{ display: "flex", gap: 18 }}>
            <a href="#" onClick={(e)=>{e.preventDefault();go("podminky");}}>Obchodní podmínky</a><a href="#" onClick={(e)=>{e.preventDefault();go("gdpr");}}>Ochrana údajů (GDPR)</a>
          </span>
        </div>
      </footer>
    );
  }

  Object.assign(window, { VNHeader: Header, VNDrawer: Drawer, VNCart: Cart, VNFooter: Footer, VNLogo: Logo, VN_NAV: NAV });
})();
