// App shell — routing, cart state, chrome, toast.
(function () {
  if (typeof React === "undefined") return;
  const DS = window.VElaStvNajmanDesignSystem_bc3fc2;
  const Icon = window.VNIcon;

  // 9.4 — announcement bar: 3 rotating messages, auto every 4s, manual arrows
  function Announce() {
    const msgs = [
      { ic: "truck", node: <span>Matky zasíláme v klíckách <strong>doporučeně</strong> po celé ČR</span> },
      { ic: "shield", node: <span>Ke každé zásilce <strong>veterinární osvědčení</strong> o zdraví včelstev</span> },
      { ic: "door", node: <span>Osobní převzetí na včelnici <strong>po domluvě</strong> · Na Samotě 1029, Hostivice</span> },
    ];
    const [i, setI] = React.useState(0);
    React.useEffect(() => {
      const t = setInterval(() => setI((v) => (v + 1) % msgs.length), 4000);
      return () => clearInterval(t);
    }, []);
    const move = (d) => setI((v) => (v + d + msgs.length) % msgs.length);
    const m = msgs[i];
    return (
      <div className="kit-announce">
        <button className="kit-announce__nav" onClick={() => move(-1)} aria-label="Předchozí sdělení">‹</button>
        <div className="kit-announce__msg" key={i}><Icon name={m.ic} size={15} /> {m.node}</div>
        <button className="kit-announce__nav" onClick={() => move(1)} aria-label="Další sdělení">›</button>
      </div>
    );
  }

  // Friendly, honey-themed 404 / error fallback
  function Error404({ onHome, onShop }) {
    return (
      <main className="kit kit-404">
        <div className="kit-shell kit-404__inner">
          <div className="kit-404__badge" aria-hidden="true"><span>404</span></div>
          <h1 className="kit-404__title">Tahle stránka se někam zatoulala</h1>
          <p className="kit-404__lead">Asi ji odnesla na křídlech nějaká zatoulaná včela — matky v úlích máme, ale tuhle adresu jsme nenašli ani pod posledním plástem. Zkuste to prosím znovu.</p>
          <div className="kit-404__cta">
            <DS.Button variant="primary" size="lg" onClick={onHome} iconStart={<Icon name="home" size={18} />}>Zpátky domů</DS.Button>
            <DS.Button variant="secondary" size="lg" onClick={onShop}>Prohlédnout nabídku</DS.Button>
          </div>
          <p className="kit-404__hint">🐝 Tip: matka se výjimečně zatoulá — stránky bohužel častěji.</p>
        </div>
      </main>
    );
  }

  // Catches render errors anywhere in the screen and shows the 404 instead of a white screen
  class ErrorBoundary extends React.Component {
    constructor(p) { super(p); this.state = { err: false }; }
    static getDerivedStateFromError() { return { err: true }; }
    componentDidUpdate(prev) { if (prev.routeKey !== this.props.routeKey && this.state.err) this.setState({ err: false }); }
    render() { return this.state.err ? <Error404 onHome={this.props.onHome} onShop={this.props.onShop} /> : this.props.children; }
  }

  function App() {
    const [route, setRoute] = React.useState({ screen: "home", arg: null });
    const [cart, setCart] = React.useState([]);
    const [cartOpen, setCartOpen] = React.useState(false);
    const [cartPeek, setCartPeek] = React.useState(false);
    const [menuOpen, setMenuOpen] = React.useState(false);
    const [quickView, setQuickView] = React.useState(null);
    const [preorder, setPreorder] = React.useState(null);
    const [toast, setToast] = React.useState(null);
    const [user, setUser] = React.useState(null);
    const [authOpen, setAuthOpen] = React.useState(false);
    const [cartPulse, setCartPulse] = React.useState(0);
    const [showTop, setShowTop] = React.useState(false);
    const toastTimer = React.useRef(null);
    React.useEffect(() => {
      const fn = () => setShowTop(window.scrollY > 500);
      window.addEventListener("scroll", fn, { passive: true });
      return () => window.removeEventListener("scroll", fn);
    }, []);
    React.useEffect(() => {
      window.__openRezervace = (p, qty) => { go("rezervace", p); };
      return () => { delete window.__openRezervace; };
    }, []);
    // Preview the 404 page by adding #404 (or any unknown #hash) to the URL
    React.useEffect(() => {
      const sync = () => {
        const h = (window.location.hash || "").replace(/^#/, "");
        if (h === "404") setRoute({ screen: "404", arg: null });
      };
      sync();
      window.addEventListener("hashchange", sync);
      return () => window.removeEventListener("hashchange", sync);
    }, []);

    const go = (screen, arg = null) => {
      setRoute({ screen, arg });
      setMenuOpen(false);
      setCartOpen(false);
      setCartPeek(false);
      if (screen !== "product") window.scrollTo({ top: 0, behavior: "auto" });
      else window.scrollTo({ top: 0 });
    };

    const login = (u) => {
      const acc = window.SHOP_DATA && window.SHOP_DATA.account;
      const resolved = u || (acc && acc.user) || null;
      setUser(resolved);
      setAuthOpen(false);
      const fn = (resolved && resolved.firstName) || "";
      const initials = resolved ? (((resolved.firstName || "")[0] || "") + ((resolved.lastName || "")[0] || "")).toUpperCase() : "";
      showToast({ kind: "status", title: fn ? ("Vítejte zpět, " + fn) : "Přihlášeno", sub: "Jsme rádi, že jste zpět.", initials });
    };
    const logout = () => { setUser(null); go("home"); showToast({ kind: "status", title: "Byli jste odhlášeni", icon: "logout" }); };

    const showToast = (data) => {
      setToast(data);
      clearTimeout(toastTimer.current);
      const dur = data && typeof data === "object" ? 3200 : 2400;
      toastTimer.current = setTimeout(() => setToast(null), dur);
    };

    const openRezervace = (p, qty = 1) => {
      if (!p || p.stock === "out") return;
      if (window.__openRezervace) window.__openRezervace(p, qty);
      else go("rezervace", p);
    };
    const addToCart = (p, qty = 1) => openRezervace(p, qty);
    const buyNow = (p, qty = 1) => openRezervace(p, qty);
    const setQty = (id, q) => setCart((c) => c.map((i) => i.id === id ? { ...i, qty: q } : i));
    const removeItem = (id) => setCart((c) => c.filter((i) => i.id !== id));

    const cartCount = cart.reduce((s, i) => s + i.qty, 0);
    const notify = (p) => showToast(`Dáme vědět, až naskádníme: ${p.name}`);

    let screen;
    const props = { go, addToCart, onQuickView: setQuickView, onNotify: notify, onPreorder: setPreorder };
    switch (route.screen) {
      case "category": screen = <window.VNCategory {...props} catId={route.arg} />; break;
      case "product": screen = <window.VNProduct {...props} productId={route.arg} />; break;
      case "blog": screen = <window.VNBlog go={go} />; break;
      case "article": screen = <window.VNArticle go={go} postId={route.arg} />; break;
      case "about": screen = <window.VNAbout go={go} />; break;
      case "contact": screen = <window.VNContact go={go} />; break;
      case "podminky": screen = <window.VNLegal go={go} kind="podminky" />; break;
      case "gdpr": screen = <window.VNLegal go={go} kind="gdpr" />; break;
      case "checkout":
      case "rezervace": screen = <window.VNRezervace go={go} preset={route.arg} presetQty={1} />; break;
      case "account":
        screen = user
          ? <window.VNAccount go={go} section={route.arg} user={user} onLogout={logout}
              addToCart={(p, q = 1) => addToCart(p, q, { peek: true })} onQuickView={setQuickView} onNotify={notify} onPreorder={setPreorder} />
          : <window.VNHome {...props} />;
        break;
      case "404": screen = <Error404 onHome={() => go("home")} onShop={() => go("category")} />; break;
      default: screen = <window.VNHome {...props} />;
    }

    return (
      <div className="kit">
        <Announce />
        <window.VNHeader go={go} current={route.screen} currentArg={route.arg} cartCount={cartCount} cartPulse={cartPulse}
          onCart={() => { setCartPeek(false); setCartOpen(true); }} onMenu={() => setMenuOpen(true)}
          user={user} onProfile={() => setAuthOpen(true)} onLogout={logout} />
        <div className="kit-screen" key={route.screen + ":" + (route.arg || "")}>
          <ErrorBoundary routeKey={route.screen + ":" + (route.arg || "")} onHome={() => go("home")} onShop={() => go("category")}>{screen}</ErrorBoundary>
        </div>
        <window.VNFooter go={go} />

        <window.VNDrawer open={menuOpen} onClose={() => setMenuOpen(false)} go={go} />
{/* košík vypnutý — rezervačný flow */}

        {window.VNPreorder && <window.VNPreorder product={preorder} onClose={() => setPreorder(null)}
          onAddToCart={addToCart} onBuyNow={buyNow} onContact={() => go("contact")} />}

        {window.VNAuth && <window.VNAuth open={authOpen} onClose={() => setAuthOpen(false)} onLogin={login} />}

        <button className={"kit-totop" + (showTop ? " is-visible" : "")} onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })} aria-label="Nahoru na začátek">
          <svg viewBox="0 0 44 48" width="44" height="48" aria-hidden="true">
            <path className="kit-totop__hex" d="M22 2.5 L41.5 13.75 L41.5 34.25 L22 45.5 L2.5 34.25 L2.5 13.75 Z" />
            <path className="kit-totop__arr" d="M14.5 25.5 L22 18 L29.5 25.5" />
          </svg>
        </button>

        <div className="kit-toast" data-rich="true" data-show={toast && typeof toast === "object" && toast.kind === "cart" ? "true" : undefined}>
          {toast && typeof toast === "object" && toast.kind === "cart" && (
            <>
              <div className="kit-toast__thumb"><DS.Photo src={toast.image} ratio="1 / 1" label={toast.weight} /></div>
              <div className="kit-toast__main">
                <span className="kit-toast__title"><Icon name="check" size={16} /> {toast.preorder ? "Předobjednávka přidána" : "Přidáno do košíku"}</span>
                <span className="kit-toast__sub">{toast.name} · {toast.weight}</span>
              </div>
              <button className="kit-toast__cta" onClick={() => { setToast(null); setCartPeek(false); setCartOpen(true); }}>
                Zobrazit košík <Icon name="arrowRight" size={15} />
              </button>
            </>
          )}
        </div>

        <div className="kit-toast kit-toast--status" data-pos="top" data-show={toast && !(typeof toast === "object" && toast.kind === "cart") ? "true" : undefined}>
          {toast && !(typeof toast === "object" && toast.kind === "cart") && (
            typeof toast === "object" ? (
              <>
                {toast.initials
                  ? <span className="kit-toast__avatar">{toast.initials}</span>
                  : <span className="kit-toast__ok"><Icon name={toast.icon || "check"} size={17} /></span>}
                <div className="kit-toast__main">
                  <span className="kit-toast__title">{toast.title}</span>
                  {toast.sub ? <span className="kit-toast__sub kit-toast__sub--dark">{toast.sub}</span> : null}
                </div>
              </>
            ) : (
              <><span className="kit-toast__ok"><Icon name="check" size={17} /></span> <span className="kit-toast__title">{toast}</span></>
            )
          )}
        </div>
      </div>
    );
  }

  // NOTE: do not auto-mount here. This file is also concatenated into
  // _ds_bundle.js; mounting at load time would crash the bundle (and any
  // consumer that imports it). index.html mounts <VNApp/> explicitly after
  // all kit scripts have loaded.
  window.VNApp = App;
})();
