/* TAKEBOX — Produkt detail (?id=…) with dynamic SEO */
const { useState: useStateP, useEffect: useEffectP } = React;
const { useLang: useLangP, withLang: withLangP, UI: UIP, Header: HeaderP, Footer: FooterP } = window.TB;

function getId() {
  try { return new URLSearchParams(location.search).get("id") || ""; } catch (e) { return ""; }
}

function setMeta(id, content) { var el = document.getElementById(id); if (el) el.setAttribute(el.hasAttribute("content") ? "content" : "href", content); }

/* produktové FAQ — 4 standardní otázky (viditelné + schema) */
function pdpFaq(p, lang) {
  var nm = window.TB_NAME(p, lang);
  if (lang === "de") return [
    { q: "Wie lange dauert die Fertigung von " + nm + "?", a: "Die Lieferzeit hängt von Komplexität und Umfang des Auftrags ab. Den genauen Termin bestätigen wir zusammen mit dem Angebot — auf Anfragen antworten wir in der Regel innerhalb eines Werktags." },
    { q: "Können die Abmessungen angepasst werden?", a: "Ja. Jedes Case wird nach Maß gefertigt — Abmessungen, Innenaufteilung, Schaumstoffeinlagen und Beschläge passen wir exakt an Ihre Ausrüstung an." },
    { q: "Wie viel kostet dieses Case?", a: "Der Preis richtet sich nach Abmessungen, Konstruktion und Ausstattung. Senden Sie eine unverbindliche Anfrage — wir erstellen Entwurf und Angebot kostenlos." },
    { q: "Liefern Sie auch außerhalb Tschechiens?", a: "Ja, wir fertigen in Tschechien und liefern in die gesamte Europäische Union." }
  ];
  if (lang === "en") return [
    { q: "What is the lead time for " + nm + "?", a: "Lead time depends on the complexity and scope of the order. We confirm the exact date together with the quote — typically within one business day of your inquiry." },
    { q: "Can the dimensions be customised?", a: "Yes. Every case is built to measure — we adapt dimensions, interior layout, foam inserts and hardware exactly to your equipment." },
    { q: "What materials is the case made of?", a: "Hexagon-surface panels, aluminium profiles and metal corners. Hardware is genuine Adam Hall and Penn Elcom, castors are Blickle with brakes." },
    { q: "How does ordering work?", a: "Send a no-obligation inquiry (or use the 3D designer), we prepare a proposal and quote, and after approval we build and deliver the case — across the Czech Republic and the whole EU." }
  ];
  return [
    { q: "Jaká je dodací doba — " + nm + "?", a: "Termín výroby závisí na složitosti a rozsahu zakázky. Přesný termín potvrdíme spolu s cenovou nabídkou — na poptávku odpovídáme obvykle do jednoho pracovního dne." },
    { q: "Lze upravit rozměry?", a: "Ano. Každý case vyrábíme na míru — rozměry, vnitřní uspořádání, pěnové výplně i kování přizpůsobíme přesně vašemu vybavení." },
    { q: "Z jakých materiálů je case vyroben?", a: "Desky s povrchem Hexagon, hliníkové profily a kovové rohy. Kování je originál Adam Hall a Penn Elcom, kolečka Blickle s brzdou." },
    { q: "Jak probíhá objednávka?", a: "Pošlete nezávaznou poptávku (nebo využijte 3D návrh), připravíme návrh a cenovou nabídku a po odsouhlasení case vyrobíme a doručíme — po celé ČR i EU." }
  ];
}

function applySEO(p, lang) {
  if (!p) return;
  var nm = window.TB_NAME(p, lang);
  var title = (lang === "cs" && p.seoTitle) ? p.seoTitle : (nm + " — TAKEBOX");
  var desc = (lang === "cs" && p.metaDesc) ? p.metaDesc : p.desc[lang];
  var url = "https://www.takebox.eu/Produkt.html?id=" + p.id;
  var img = p.photos[0].src ? "https://www.takebox.eu/" + p.photos[0].src : "https://www.takebox.eu/og-image.jpg";
  document.title = title;
  setMeta("m-canonical", p.slug ? "https://www.takebox.eu/produkty/" + p.slug + ".html" : url);
  setMeta("m-hl-cs", url + "&lang=cs");
  setMeta("m-hl-en", url + "&lang=en");
  setMeta("m-og-title", title);
  setMeta("m-og-desc", desc);
  setMeta("m-og-url", url);
  setMeta("m-og-image", img);
  setMeta("m-tw-title", title);
  setMeta("m-tw-image", img);
  var ld = document.getElementById("m-jsonld");
  if (ld) {
    var faq = pdpFaq(p, "cs");
    ld.textContent = JSON.stringify([
      {
        "@context": "https://schema.org", "@type": "Product", name: nm,
        description: desc, image: p.photos.filter(function (x) { return x.src; }).map(function (x) { return "https://www.takebox.eu/" + x.src; }),
        category: p.cat, sku: p.id,
        brand: { "@type": "Brand", name: "TAKEBOX" }, url: url,
        offers: { "@type": "Offer", priceCurrency: "CZK", price: "0", availability: "https://schema.org/PreOrder", description: "Cena dle konfigurace — nezávazná poptávka", url: url }
      },
      {
        "@context": "https://schema.org", "@type": "BreadcrumbList",
        itemListElement: [
          { "@type": "ListItem", position: 1, name: "TAKEBOX", item: "https://www.takebox.eu/" },
          { "@type": "ListItem", position: 2, name: "Showroom", item: "https://www.takebox.eu/Showroom.html" },
          { "@type": "ListItem", position: 3, name: nm, item: url }
        ]
      },
      {
        "@context": "https://schema.org", "@type": "FAQPage",
        mainEntity: faq.map(function (f) { return { "@type": "Question", name: f.q, acceptedAnswer: { "@type": "Answer", text: f.a } }; })
      }
    ]);
  }
}

function Media(ph, alt, big, fit) {
  if (ph.src) return <img src={ph.src} alt={alt} style={{ width: "100%", height: "100%", objectFit: fit || "cover", display: "block" }} />;
  return <image-slot id={ph.slot} style={{ width: "100%", height: "100%", display: "block" }} placeholder={big ? "+ hlavní foto" : "+ foto"}></image-slot>;
}

/* Lightbox — celý produkt (contain) + miniatury + šipky */
function PLightbox({ photos, index, title, onClose, onIndex }) {
  useEffectP(() => {
    function onKey(e) {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowRight") onIndex((index + 1) % photos.length);
      else if (e.key === "ArrowLeft") onIndex((index - 1 + photos.length) % photos.length);
    }
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [index, photos.length]);
  const n = photos.length;
  return (
    <div className="sx-lb" onClick={onClose} role="dialog" aria-modal="true" aria-label={title || LB_A.gallery}>
      <button type="button" className="sx-lb-close" aria-label={LB_A.close} onClick={onClose}>×</button>
      <div className="sx-lb-stage" onClick={(e) => { e.stopPropagation(); if (e.target === e.currentTarget) onClose(); }}>
        {n > 1 && <button type="button" className="sx-lb-nav prev" aria-label={LB_A.prev} onClick={() => onIndex((index - 1 + n) % n)}><svg><use href="#i-arrow-right" /></svg></button>}
        <img src={photos[index]} alt={(title || LB_A.photo) + " — " + (index + 1) + "/" + n} />
        {n > 1 && <button type="button" className="sx-lb-nav next" aria-label={LB_A.next} onClick={() => onIndex((index + 1) % n)}><svg><use href="#i-arrow-right" /></svg></button>}
        <span className="sx-lb-counter">{String(index + 1).padStart(2, "0")} / {String(n).padStart(2, "0")}</span>
      </div>
      {n > 1 && (
        <div className="sx-lb-thumbs" onClick={(e) => e.stopPropagation()}>
          {photos.map((src, i) => (
            <button key={i} type="button" className={"sx-lb-thumb" + (i === index ? " on" : "")} onClick={() => onIndex(i)} aria-label={LB_A.photo + " " + (i + 1)}>
              <img src={src.replace("img/", "img/thumb/")} alt="" loading="lazy" />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function ProduktApp() {
  const [lang, setLang] = useLangP();
  const cat = window.TB_CATALOG;
  const p = cat.products.find((x) => x.id === getId());
  const [active, setActive] = useStateP(0);
  const [lbOpen, setLbOpen] = useStateP(false);

  useEffectP(() => { applySEO(p, lang); }, [lang]);

  if (!p) {
    return (
      <React.Fragment>
        <HeaderP lang={lang} setLang={setLang} />
        <main><section className="section pad"><div className="wrap">
          <h1 className="h2">{UIP.not_found[lang]}</h1>
          <p className="lead" style={{ marginTop: 16 }}><a href={withLangP("Showroom.html", lang)} style={{ color: "var(--accent)" }}>{UIP.back[lang]}</a></p>
        </div></section></main>
        <FooterP lang={lang} />
      </React.Fragment>
    );
  }

  const catName = (function () { var c = cat.cats.find((x) => x.id === p.cat); return c ? c[lang] : p.cat; })();
  const nm = window.TB_NAME(p, lang);
  const real = !!p.photos[0].src;
  const related = cat.products.filter((x) => x.cat === p.cat && x.id !== p.id).slice(0, 3);

  return (
    <React.Fragment>
      <HeaderP lang={lang} setLang={setLang} />
      <main>
        <section className="section pad">
          <div className="wrap">
            <a className="pdp-back" href={withLangP("Showroom.html", lang)}><svg style={{ width: 15, height: 15 }}><use href="#i-arrow-left" /></svg>{UIP.back[lang]}</a>

            <div className="pdp-grid">
              {/* gallery */}
              <div className="pdp-gallery">
                <div className="pdp-main ticks" style={{ background: "#cfd0d1" }}><span className="tick-bl"></span><span className="tick-br"></span>
                  {real
                    ? <button type="button" className="pdp-main-btn" aria-label={nm + " — " + LB_A.zoom} onClick={() => setLbOpen(true)} style={{ display: "block", width: "100%", height: "100%", border: 0, padding: 0, background: "transparent", cursor: "zoom-in" }}>{Media(p.photos[active], nm, true, "contain")}</button>
                    : Media(p.photos[0], nm, true)}
                  {real && p.photos.length > 1 && (
                    <React.Fragment>
                      <button type="button" className="hc-nav hc-prev" aria-label={LB_A.prev} onClick={() => setActive((active - 1 + p.photos.length) % p.photos.length)}><svg><use href="#i-arrow-right" /></svg></button>
                      <button type="button" className="hc-nav hc-next" aria-label={LB_A.next} onClick={() => setActive((active + 1) % p.photos.length)}><svg><use href="#i-arrow-right" /></svg></button>
                      <span className="hc-counter">{String(active + 1).padStart(2, "0")} / {String(p.photos.length).padStart(2, "0")}</span>
                    </React.Fragment>
                  )}
                </div>
                <div className="pdp-thumbs">
                  {real
                    ? p.photos.map((ph, i) => (
                        <button key={i} className={"pdp-thumb" + (i === active ? " on" : "")} onClick={() => setActive(i)}>
                          <img src={ph.src ? ph.src.replace("img/", "img/thumb/") : ph.src} alt="" loading="lazy" decoding="async" />
                        </button>
                      ))
                    : p.photos.slice(1).map((ph, i) => (
                        <div key={i} className="pdp-thumb pdp-thumb-slot">{Media(ph, nm, false)}</div>
                      ))}
                </div>
              </div>

              {/* info */}
              <div>
                <p className="eyebrow">{catName}</p>
                <h1 className="h2" style={{ marginTop: 16 }}>{nm}</h1>
                <p className="lead" style={{ marginTop: 18 }}>{p.desc[lang]}</p>

                {(!window.TBStore || window.TBStore.dget(["template", "specs"], true)) && (
                  <React.Fragment>
                    <h2 className="pdp-spec-h">{UIP.specs[lang]}</h2>
                    <ul className="pspecs">
                      {p.specs.map((s, i) => (
                        <li key={i}><span>{s.k[lang]}</span><b>{s.v[lang]}</b></li>
                      ))}
                    </ul>
                  </React.Fragment>
                )}

                {(!window.TBStore || window.TBStore.dget(["template", "upgrades"], true)) && (
                  <React.Fragment>
                    <h2 className="pdp-spec-h">{lang === "en" ? "Available upgrades" : lang === "de" ? "Mögliche Anpassungen" : "Dostupné úpravy"}</h2>
                    <ul className="pdp-chips">
                      {(function () {
                        var custom = window.TBStore && window.TBStore.dget(["upgrades", "list"], "");
                        if (custom) return String(custom).split("\n").map(function (l) { return l.trim(); }).filter(Boolean).map(function (l) { var i = l.indexOf("—"); return i >= 0 ? l.slice(0, i).trim() : l; });
                        return lang === "en"
                          ? ["Doors — one or both sides", "Reinforced floor", "Folding ramp (alu / wood)", "Ramp lock", "Corner handles", "Drawers", "Fixed shelves", "Removable shelves", "Interior padding"]
                          : lang === "de"
                          ? ["Türen — eine oder beide Seiten", "Verstärkter Boden", "Klapprampe (Alu / Holz)", "Rampenverriegelung", "Eckgriffe", "Schubladen", "Feste Böden", "Herausnehmbare Böden", "Innenpolsterung"]
                          : ["Dveře — jedna či obě strany", "Zesílená podlaha", "Skládací rampa (hliník / dřevo)", "Zámek rampy", "Rohová madla", "Zásuvky", "Pevné police", "Vyjímatelné police", "Polstrování interiéru"];
                      })().map((t, i) => (
                        <li key={i}><svg><use href="#i-check" /></svg>{t}</li>
                      ))}
                    </ul>
                    <p className="pdp-chips-note">{lang === "en" ? "Every box is built to order — tell us what you need." : lang === "de" ? "Jedes Case wird auf Bestellung gefertigt — sagen Sie uns, was Sie brauchen." : "Každý box vyrábíme na míru — napište nám, co potřebujete."}</p>
                  </React.Fragment>
                )}

                {(!window.TBStore || window.TBStore.dget(["template", "cta"], true)) && (
                  <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 30 }}>
                    <a className="btn btn-primary" href={withLangP("index.html#poptavka", lang)}>{UIP.request_similar[lang]} <svg style={{ width: 17, height: 17 }}><use href="#i-arrow-right" /></svg></a>
                    {(function () {
                      var map = { autopilot: "drawerbox", workstation: "workstation", elevision: "elevision", drawerbox: "drawerbox", kufrik1: "kufrik", kufrik2: "kufrik", drawerside: "flightcase", case2: "flightcase", case6: "rack", case7: "rack" };
                      var ty = map[p.id] || "flightcase";
                      var href = withLangP("3D-navrh.html?type=" + ty, lang);
                      return <a className="btn btn-ghost" href={href}>{lang === "en" ? "Edit in 3D" : lang === "de" ? "In 3D bearbeiten" : "Upravit ve 3D"} <svg style={{ width: 16, height: 16 }}><use href="#i-scan" /></svg></a>;
                    })()}
                  </div>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* produktové FAQ — viditelná sekce (zdroj pro FAQPage schema) */}
        <section className="section pad" id="pdp-faq">
          <div className="wrap" style={{ maxWidth: 880 }}>
            <p className="eyebrow">{lang === "en" ? "FAQ" : lang === "de" ? "FAQ" : "Časté dotazy"}</p>
            <h2 className="h2" style={{ marginBottom: 22 }}>{lang === "en" ? "Questions about this case" : lang === "de" ? "Fragen zu diesem Case" : "Dotazy k tomuto case"}</h2>
            <div className="faq-list" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {pdpFaq(p, lang).map(function (f, i) {
                return (
                  <details className="faq-item" key={i} style={{ border: "1px solid var(--border)", borderRadius: 12, padding: "4px 18px", background: "var(--surface)" }}>
                    <summary style={{ cursor: "pointer", fontWeight: 700, padding: "12px 0" }}>{f.q}</summary>
                    <p style={{ color: "var(--muted)", lineHeight: 1.65, margin: "0 0 14px" }}>{f.a}</p>
                  </details>
                );
              })}
            </div>
          </div>
        </section>

        {related.length > 0 && (
          <section className="section invert pad">
            <div className="wrap">
              <p className="eyebrow">{UIP.related[lang]}</p>
              <div className="showroom-grid sr-grid" style={{ marginTop: 30 }}>
                {related.map((r) => (
                  <a key={r.id} className="card" href={(lang === "cs" && r.slug) ? "produkty/" + r.slug + ".html" : withLangP("Produkt.html?id=" + r.id, lang)}>
                    <div className="media">{Media(r.photos[0], window.TB_NAME(r, lang), false)}</div>
                    <div className="body"><div><span className="sr-cat">{catName}</span><h3>{window.TB_NAME(r, lang)}</h3><p>{r.tag[lang]}</p></div><span className="go"><svg style={{ width: 16, height: 16 }}><use href="#i-arrow-ur" /></svg></span></div>
                  </a>
                ))}
              </div>
            </div>
          </section>
        )}
      </main>
      {real && lbOpen && <PLightbox photos={p.photos.filter((x) => x.src).map((x) => x.src)} index={active} title={nm} onClose={() => setLbOpen(false)} onIndex={(i) => setActive(i)} />}
      <FooterP lang={lang} />
    </React.Fragment>
  );
}

function mountProdukt() {
  var ORIG = JSON.stringify(window.TB_CATALOG);
  var root = ReactDOM.createRoot(document.getElementById("root"));
  root.render(<ProduktApp />);
  window.__tbApplyPreview = function () {
    try { window.TB_CATALOG = JSON.parse(ORIG); window.TBStore.applyCatalog(window.TB_CATALOG); } catch (e) {}
    root.render(<ProduktApp />);
  };
}
mountProdukt();function lbA() {
  var l = "cs";
  try {
    var q = new URLSearchParams(location.search).get("lang");
    var ls = localStorage.getItem("tb-lang");
    l = q || ls || "cs";
  } catch (e) {}
  return l === "cs"
    ? { close: "Zavřít", prev: "Předchozí", next: "Další", photo: "Foto", gallery: "Galerie fotek", zoom: "zvětšit fotky" }
    : { close: "Close", prev: "Previous", next: "Next", photo: "Photo", gallery: "Photo gallery", zoom: "view photos" };
}
/* dynamický proxy objekt — čte aktuální jazyk při každém použití */
const LB_A = ["close", "prev", "next", "photo", "gallery", "zoom"].reduce(function (o, k) {
  Object.defineProperty(o, k, { get: function () { return lbA()[k]; } });
  return o;
}, {});

