// Product detail page (PDP).
(function () {
  if (typeof React === "undefined") return;
  const DS = window.VElaStvNajmanDesignSystem_bc3fc2;
  const { Photo, Button, Badge, Tag, Rating, QuantityStepper, SectionHeading, Input } = DS;
  const Icon = window.VNIcon;

  function Accordion({ title, children, open: defOpen }) {
    const [open, setOpen] = React.useState(!!defOpen);
    return (
      <div className="kit-acc" data-open={open}>
        <button className="kit-acc__head" onClick={() => setOpen((o) => !o)} aria-expanded={open}>
          {title}<Icon name="chevronDown" size={20} />
        </button>
        <div className="kit-acc__body"><p>{children}</p></div>
      </div>
    );
  }

  // Count-up animation for the price (3.3) — eases the number to its new value.
  function useCountUp(value, ms) {
    const [disp, setDisp] = React.useState(value);
    const prev = React.useRef(value);
    React.useEffect(() => {
      const from = prev.current, to = value; prev.current = value;
      if (from === to) return;
      const reduce = window.matchMedia && !window.matchMedia('(prefers-reduced-motion: no-preference)').matches;
      if (reduce) { setDisp(to); return; }
      let raf, start;
      const step = (t) => {
        if (!start) start = t;
        const p = Math.min(1, (t - start) / ms);
        setDisp(Math.round(from + (to - from) * p));
        if (p < 1) raf = requestAnimationFrame(step);
      };
      raf = requestAnimationFrame(step);
      return () => cancelAnimationFrame(raf);
    }, [value, ms]);
    return disp;
  }

  function Product({ go, addToCart, onNotify, onPreorder, productId }) {
    const D = window.SHOP_DATA;
    const p = D.products.find((x) => x.id === productId) || D.products[0];
    const honeyVariants = p.variants && p.variants.length ? p.variants : null;
    const [qty, setQty] = React.useState(1);
    const [activeImg, setActiveImg] = React.useState(0);
    const [lightbox, setLightbox] = React.useState(false);
    const touchX = React.useRef(null);
    const onTouchStart = (e) => { touchX.current = e.touches[0].clientX; };
    const onTouchEnd = (e) => {
      if (touchX.current == null) return;
      const dx = e.changedTouches[0].clientX - touchX.current;
      touchX.current = null;
      if (Math.abs(dx) < 40) return;
      setActiveImg((i) => Math.max(0, Math.min(3, dx < 0 ? i + 1 : i - 1)));
    };
    const [vIdx, setVIdx] = React.useState(0);
    React.useEffect(() => {
      setQty(1); setActiveImg(0); setLightbox(false);
      const di = honeyVariants ? Math.max(0, honeyVariants.findIndex(v => v.w === p.weight)) : 0;
      setVIdx(di);
    }, [productId]);
    const variant = honeyVariants ? honeyVariants[Math.min(vIdx, honeyVariants.length - 1)] : null;
    const curPrice = variant ? variant.price : p.price;
    const curWeight = variant ? variant.w : p.weight;
    const dispPrice = useCountUp(curPrice * qty, 150);
    // 4.1 — sticky buy bar appears only once the real buy box scrolls out of view.
    // Uses a scroll listener (works everywhere, incl. environments where IO is flaky).
    const buyRef = React.useRef(null);
    const [showSticky, setShowSticky] = React.useState(false);
    React.useEffect(() => {
      const el = buyRef.current;
      if (!el) return;
      const check = () => {
        const r = el.getBoundingClientRect();
        setShowSticky(r.bottom < 80);
      };
      check();
      window.addEventListener("scroll", check, { passive: true });
      window.addEventListener("resize", check);
      return () => { window.removeEventListener("scroll", check); window.removeEventListener("resize", check); };
    }, [productId, vIdx, soldOut, notified]);
    // close lightbox on Escape
    React.useEffect(() => {
      if (!lightbox) return;
      const onKey = (e) => { if (e.key === "Escape") setLightbox(false); };
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, [lightbox]);
    const curStock = variant ? variant.stock : (p.stock || "in");
    const soldOut = curStock === "out";
    const curRestock = (variant && variant.restock) || p.restock || null;
    const [notifyEmail, setNotifyEmail] = React.useState("");
    const [notified, setNotified] = React.useState(false);
    React.useEffect(() => { setNotified(false); setNotifyEmail(""); }, [productId, vIdx]);
    const buyItem = { ...p, id: variant ? p.id + "-" + variant.w : p.id, name: p.name, price: curPrice, weight: curWeight };
    const preorderItem = { ...p, price: curPrice, weight: curWeight, restock: curRestock };
    const HONEY = ["kvetove", "pastovany", "lesni"];
    const related = (() => {
      const pool = D.products.filter((x) => x.id !== p.id);
      const seen = new Set();
      const out = [];
      const add = (arr) => arr.forEach((x) => { if (!seen.has(x.id) && out.length < 3) { seen.add(x.id); out.push(x); } });
      add(pool.filter((x) => x.cat === p.cat));                                   // same category first
      if (HONEY.includes(p.cat)) add(pool.filter((x) => HONEY.includes(x.cat)));  // then honey siblings
      add(pool.filter((x) => x.cat !== "gift"));                                  // then anything else (skip gift bundle)
      add(pool);                                                                  // final fallback
      return out;
    })();
    const MENU_CAT = {
      carnica: { label: "Kraňské matky", arg: "carnica" }, buckfast: { label: "Buckfast matky", arg: "buckfast" },
      inseminace: { label: "Inseminované", arg: "inseminace" }, oddelky: { label: "Oddělky a včelstva", arg: "oddelky" },
    };
    const crumbCat = MENU_CAT[p.cat] || { label: "Matky", arg: "carnica" };

    return (
      <main className="kit">
        <div className="kit-shell">
          <nav className="kit-breadcrumb" style={{ paddingTop: 24 }}>
            <a href="#" onClick={(e)=>{e.preventDefault();go("home");}}>Domů</a>
            <Icon name="chevronRight" size={13} />
            <a href="#" onClick={(e)=>{e.preventDefault();go("category", crumbCat.arg);}}>{crumbCat.label}</a>
            <Icon name="chevronRight" size={13} /> <span className="kit-breadcrumb__here">{p.name}</span>
          </nav>
        </div>

        <div className="kit-shell kit-pdp">
          {/* GALLERY */}
          <div className="kit-gallery">
            <div className="kit-gallery__main" onClick={() => setLightbox(true)}
                 onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}
                 title="Klikněte pro zvětšení">
              <Photo src={activeImg === 0 ? p.image : undefined} ratio="1 / 1" alt={p.name} label={"Foto " + (activeImg + 1) + " · " + p.weight} />
              <button className="kit-gallery__zoom" onClick={(e) => { e.stopPropagation(); setLightbox(true); }} aria-label="Zvětšit na celý obraz"><Icon name="plus" size={18} /></button>
            </div>
            <div className="kit-gallery__dots" role="tablist" aria-label="Fotografie produktu">
              {[0,1,2,3].map((i) => (
                <button key={i} className={"kit-gallery__dot" + (activeImg === i ? " is-active" : "")}
                  onClick={() => setActiveImg(i)} aria-label={"Foto " + (i + 1)} aria-selected={activeImg === i} />
              ))}
            </div>
            <div className="kit-gallery__thumbs">
              {[0,1,2,3].map((i) => (
                <Photo key={i} src={i === 0 ? p.image : undefined} ratio="1 / 1" label="·" data-active={activeImg === i}
                  onClick={() => { setActiveImg(i); }} />
              ))}
            </div>
          </div>

          {/* INFO */}
          <div className="kit-pdp__info">
            <div className="kit-pdp__titlerow">
              <h1>{p.name}</h1>
              <span className={"vn-chip kit-pdp__statuschip vn-chip--" + (curStock === "out" ? "red" : curStock === "low" ? "gold" : "green")}>
                <span className="vn-chip__dot" />{curStock === "out" ? "Vyprodáno" : curStock === "low" ? "Poslední kusy" : "Skladem"}
              </span>
            </div>
            {p.taste && <p className="kit-pdp__taste">{p.taste}</p>}
            <p className="kit-pdp__desc">{p.desc}</p>

            {/* SELECTION CARD — balení + cena pohromadě, jasně barevně odlišené */}
            <div className={"kit-pdp__selector" + (honeyVariants ? "" : " is-single")}>
              {honeyVariants && (
                <div className="kit-pdp__variants">
                  <span className="kit-pdp__variants-label">Vyberte balení</span>
                  <div className="kit-pdp__pills">
                    {honeyVariants.map((v, i) => (
                      <button key={i} type="button" className="kit-pill" data-active={i === vIdx} disabled={v.stock === "out"}
                        onClick={() => { setVIdx(i); setQty(1); }} aria-pressed={i === vIdx}>
                        <span className="kit-pill__check" aria-hidden="true"><Icon name="check" size={13} /></span>
                        <span className="kit-pill__w">{v.w}</span>
                        <span className="kit-pill__p">{v.stock === "out" ? "vyprodáno" : v.price + " Kč"}</span>
                      </button>
                    ))}
                  </div>
                </div>
              )}
              <div className="kit-pdp__priceline">
                <div className="kit-pdp__price">
                  <b>{curPrice > 0 ? dispPrice + " Kč" : "Cena na dotaz"}</b>
                  <span>vč. DPH{qty > 1 ? " · " + qty + " ks" : ""} · {curWeight}</span>
                </div>
              </div>
            </div>

            <div className="kit-pdp__buybox" ref={buyRef}>
            {soldOut ? (
              curRestock ? (
                <div className="kit-preorder-block">
                  <p className="kit-restock"><Icon name="truck" size={16} /> Naskladňujeme: <strong>{curRestock}</strong></p>
                  <Button variant="primary" size="lg" block iconStart={<Icon name="check" size={18} />} onClick={() => onPreorder && onPreorder(preorderItem)}>Předobjednat</Button>
                </div>
              ) : (
                <div className="kit-notify-block">
                  {notified ? (
                    <p className="kit-notify-ok"><Icon name="check" size={16} /> Dáme vědět, jakmile bude {curWeight ? curWeight + " " : ""}skladem.</p>
                  ) : (
                    <form className="kit-notify-form" onSubmit={(e) => { e.preventDefault(); if (notifyEmail) setNotified(true); }}>
                      <Input type="email" required placeholder="vas@email.cz" aria-label="E-mail pro upozornění" value={notifyEmail} onChange={(e) => setNotifyEmail(e.target.value)} />
                      <Button variant="secondary" size="lg" type="submit" iconStart={<Icon name="mail" size={18} />}>Upozornit, až naskladníme</Button>
                    </form>
                  )}
                </div>
              )
            ) : (
              <div className="kit-pdp__buy">
                <QuantityStepper value={qty} onChange={setQty} max={20} />
                <Button variant="primary" size="lg" onClick={() => addToCart(buyItem, qty)} iconStart={<Icon name="calendar" size={18} />} style={{ flex: 1, minWidth: 180 }}>{curPrice > 0 ? "Rezervovat" : "Objednat na dotaz"}</Button>
              </div>
            )}
            </div>

            <div className="kit-pdp__ship"><Icon name="truck" size={18} /> Osobní převzetí na včelnici v Hostivicích · matky zasíláme i poštou</div>

            {/* PROVENANCE — původ a kvalita: mapka + data */}
            <div className="kit-prov">
              <div className="kit-prov__data">
                <p className="vn-eyebrow" style={{ marginBottom: 8 }}>Původ a kvalita</p>
                <dl className="kit-prov__list">
                  <div><dt>Původ / linie</dt><dd>{p.region}</dd></div>
                  <div><dt>Období</dt><dd>{p.prov ? p.prov.harvest : "—"}</dd></div>
                  <div><dt>Ročník</dt><dd>{p.prov ? p.prov.year : "—"}</dd></div>
                  <div><dt>Evidenční číslo</dt><dd className="kit-prov__lot"><span className="kit-prov__stamp" aria-hidden="true"><Icon name="hexagon" size={13} /></span>{p.prov ? p.prov.lot : "—"}</dd></div>
                </dl>
                <span className="kit-prov__badge"><Icon name="shield" size={15} /> Veterinární osvědčení k dispozici</span>
              </div>
              <a className="kit-prov__map" href={"https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent("Hostivice, Česko")} target="_blank" rel="noopener noreferrer" aria-label="Zobrazit chovnou stanici Hostivice na mapě">
                <span className="kit-prov__map-hc" aria-hidden="true" />
                <span className="kit-prov__medallion">
                  <span className="kit-prov__pin"><Icon name="pin" size={26} /></span>
                </span>
                <span className="kit-prov__region">Chovná stanice · Hostivice</span>
                <span className="kit-prov__maplink">Zobrazit na mapě <Icon name="arrowRight" size={14} /></span>
              </a>
            </div>

            {/* TASTE PROFILE */}
            {window.VNTasteProfile && p.profile && (p.profile.color > 0 || p.profile.sweet > 0 || (p.profile.traits && p.profile.traits.length)) && (
              <div className="kit-pdp__taste-block">
                <p className="vn-eyebrow" style={{ marginBottom: 10 }}>Vlastnosti linie</p>
                <window.VNTasteProfile profile={p.profile} />
              </div>
            )}

            <div className="kit-pdp__meta">
              <Accordion title="Převzetí a doprava matek" open>Matky předáváme osobně na včelnici v Hostivicích po domluvě, nebo je posíláme v klíckách doporučeně po ČR. Oddělky a včelstva se přebírají výhradně osobně.</Accordion>
              <Accordion title="Přidání matky do včelstva">Matku přidávejte v klícce do včelstva bez matky, za příznivého počasí a snůšky. Plný postup najdete v našem blogu v sekci Sezónní práce.</Accordion>
              <Accordion title="Veterinární podmínky">Ke každé zásilce přikládáme veterinární osvědčení o zdraví včelstev. Přesun včel mezi stanovišti se řídí platnou legislativou.</Accordion>
            </div>
          </div>
        </div>

        {/* RELATED */}
        <section className="kit-section">
          <div className="kit-shell">
            <div className="kit-section__head"><SectionHeading eyebrow="Mohlo by se vám hodit" title="Podobná genetika" /></div>
            <div className="kit-pgrid kit-related">
              {related.map((r) => (
                <window.VNProductCard key={r.id} product={r}
                  onOpen={(pr) => { go("product", pr.id); window.scrollTo(0,0); }}
                  onAdd={() => addToCart(r)} onNotify={onNotify} onPreorder={onPreorder} />
              ))}
            </div>
          </div>
        </section>

        {/* 4.2 fullscreen lightbox */}
        {lightbox && (
          <div className="kit-gallery__lightbox" onClick={() => setLightbox(false)} role="dialog" aria-modal="true" aria-label={p.name}>
            <button className="kit-gallery__lightbox-close" onClick={() => setLightbox(false)} aria-label="Zavřít"><Icon name="close" size={22} /></button>
            <div className="kit-gallery__lightbox-stage" onClick={(e) => e.stopPropagation()} onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
              <Photo src={activeImg === 0 ? p.image : undefined} ratio="1 / 1" alt={p.name} label={"Foto " + (activeImg + 1) + " · " + p.weight} />
            </div>
            <div className="kit-gallery__lightbox-dots">
              {[0,1,2,3].map((i) => (
                <button key={i} className={"kit-gallery__dot" + (activeImg === i ? " is-active" : "")}
                  onClick={(e) => { e.stopPropagation(); setActiveImg(i); }} aria-label={"Foto " + (i + 1)} />
              ))}
            </div>
          </div>
        )}

        {/* sticky mobile bar — only once the real buy box is out of view */}
        <div className={"kit-stickybar" + (showSticky ? " is-visible" : "")} aria-hidden={!showSticky}>
          <span className="kit-stickybar__price">{curPrice > 0 ? curPrice + " Kč" : "Cena na dotaz"}{curPrice > 0 ? <small>vč. DPH{honeyVariants ? " · " + curWeight : ""}</small> : null}</span>
          {soldOut
            ? (curRestock
                ? <Button variant="primary" size="lg" onClick={() => onPreorder && onPreorder(preorderItem)} iconStart={<Icon name="check" size={18} />}>Předobjednat</Button>
                : <Button variant="secondary" size="lg" onClick={() => setNotified(true)} iconStart={<Icon name="mail" size={18} />}>Upozornit</Button>)
            : <Button variant="primary" size="lg" onClick={() => addToCart(buyItem, qty)} iconStart={<Icon name="calendar" size={18} />}>{curPrice > 0 ? "Rezervovat" : "Objednat na dotaz"}</Button>}
        </div>
      </main>
    );
  }
  window.VNProduct = Product;
})();
