/* === App: router + tweaks + 8 family data === */

const FAMILIES = {
  1: {
    num: "01", label: "TARGHETTE · ROTOLI", pages: "06 — 07",
    title: { pre: "Targhette", accent: "in rotolo" },
    img: "products/01-targhette-rotoli/rotolo_yellow_1.png",
    icon: "roll",
    gallery: [
      "products/01-targhette-rotoli/rotolo_white_1.png",
      "products/01-targhette-rotoli/rotolo_yellow_1.png",
    ],
    lead: "Sistema di siglatura in rotoli FLAT: targhette in PVC rigido 0,5 mm, formato a stelo, già pronte da stampare e inserire nei tubetti FLAT.",
    body: "Compatibile con stampanti CAB Squix tipo Rolly. Tre gesti — stampa, distacca, inserisci: taglio netto da pre-tranciatura, inserimento facile nei tubetti FLAT (PVC o HF/EVA). PVC rigido UL94 VØ U.V., senza silicone, −30 / +60 °C. CEI EN 60464-2 e UNI EN ISO 175.",
    pills: ["PVC VØ U.V.", "UL94", "CAB SQUIX tipo Rolly", "−30 / +60 °C", "H ROTOLO 100 MM", "NO SILICONE"],
    features: [
      { icon: "check", label: "Materiale",     value: "PVC rigido VØ U.V.",  note: "Autoestinguente UL94. Stabilità termica garantita." },
      { icon: "info",  label: "Stampanti",     value: "CAB Squix · Rolly", note: "Trasferimento termico, ribbon standard." },
      { icon: "check", label: "Range termico", value: "−30 / +60 °C", note: "Quadri indoor / outdoor." },
      { icon: "check", label: "Norme",         value: "CEI EN 60464-2", note: "Conforme UNI EN ISO 175." },
    ],
  },
  2: {
    num: "02", label: "TARGHETTE · CARD", pages: "08 — 11",
    title: { pre: "Targhette", accent: "in card" },
    img: "products/02-targhette-card/card_white.png",
    icon: "card",
    gallery: [
      "products/02-targhette-card/card_white.png",
      "products/02-targhette-card/card_yellow.png",
    ],
    lead: "Sistema di siglatura in foglietti pre-fustellati: targhette in PVC FLAT 0,5 mm, già pronte da stampare e inserire nei tubetti FLAT. Stampa selettiva per piccoli lotti.",
    body: "Compatibile con tutte le stampanti modelli MG. PVC rigido UL94 VØ U.V., senza silicone, −30 / +60 °C. CEI EN 60464-2 e UNI EN ISO 175. Triple listino: industrial, reduced e halogen-free EVA.",
    pills: ["PVC VØ U.V.", "+ HF/EVA", "STAMPANTI MG", "5 FORMATI SIGLA", "PACK 50 / 25"],
  },
  3: {
    num: "03", label: "TUBETTI TRASPARENTI", pages: "12 — 51",
    title: { pre: "Tubetti", accent: "trasparenti" },
    img: "products/03-tubetti/tubetti_sezione_da0-a6.png",
    icon: "tube",
    lead: "Sezioni 0 → 6 · FLAT 0,5 mm + 2 mm PVC + 2 mm HF EVA · Shore 70 / 83 / 89. Master e Mini pack.",
    body: "Tubetti porta-targhetta in PVC trasparente o HF EVA. Shore 70 (morbido), 83 (rigido), 89 (HF Gummy). Disponibili in pack Master industriale e Mini per piccoli lotti. Compatibili con targhette FLAT MarketProtect e codici terzi.",
    pills: ["Shore 70 · morbido", "Shore 83 · rigido", "Shore 89 · HF Gummy", "FLAT 0,5 mm", "PVC 2 mm", "HF EVA 2 mm", "Cristal", "Blue"],
  },
  4: {
    num: "04", label: "FASCETTABILI", pages: "52 — 65",
    title: { pre: "Fascettabili", accent: "1 → 10" },
    img: "products/04-fascettabili/tubetti_fascettabili_5.png",
    icon: "cable-tie",
    lead: "Galleria 1 → 10 + clip. FLAT 0,5 + 2 mm PVC + 2 mm HF EVA. Tag 4 / 9 / 15 mm.",
    body: "Sistema di siglatura per cavi tramite fascetta: porta-targhetta con anello di fissaggio. Disponibili in PVC FLAT 0,5, PVC 2 mm e HF EVA 2 mm. Compatibili con fascette larghezza 2,5 → 9 mm.",
    pills: ["Tag 4 mm", "Tag 9 mm", "Tag 15 mm", "PVC FLAT 0,5", "PVC 2 mm", "HF EVA 2 mm"],
  },
  5: {
    num: "05", label: "TUBETTI ADESIVI", pages: "60 — 63",
    title: { pre: "Tubetti", accent: "adesivi" },
    img: "products/03-tubetti/tubetti_adesivi_1.png",
    icon: "external",
    lead: "Identificazione adesiva su componenti, superfici lisce o goffrate. PVC VØ trasparente con biadesivo strutturale. Slim adhesive o HP adhesive.",
    body: "Portatarghette in PVC VØ trasparente con biadesivo strutturale. Slim per superfici lisce e componenti, HP per superfici goffrate o uso esterno quadro. Disponibili spessore FLAT 0,5 mm e 2 mm.",
    pills: ["PVC VØ", "Biadesivo strutturale", "Slim adhesive", "HP adhesive", "FLAT 0,5", "2 mm", "Tag 4 mm"],
  },
  6: {
    num: "06", label: "TUBETTI PER BINARI", pages: "64 — 65",
    title: { pre: "Tubetti", accent: "per binari" },
    img: "products/03-tubetti/tubetti_binari_1.png",
    icon: "insert",
    lead: "Tubetti snap-in per binario 9 mm. PVC VØ, tag 4 mm, sei lunghezze standard.",
    body: "Portatarghette PVC VØ trasparente, sistema di aggancio rapido (snap-in) sul binario 9 mm. Tag 4 mm per targhette FLAT 0,5 o 2 mm. Pack Mini dispenser.",
    pills: ["PVC VØ", "Snap-in", "Binario 9 mm", "Tag 4 mm", "Mini dispenser"],
  },
  7: {
    num: "07", label: "BINARI PORTA-TARGHETTA", pages: "66 — 73",
    title: { pre: "Binari", accent: "porta-targhetta" },
    img: "products/05-binari/binario_portatarghetta_black_1.png",
    icon: "rail",
    gallery: [
      "products/05-binari/binario_portatarghetta_black_1.png",
      "products/05-binari/binario_portatarghetta_grey_1.png",
      "products/05-binari/binario_portatarghetta_black_adesivo_1.png",
    ],
    lead: "Neri / grigi · 9 / 15 mm · senza fori, con fori, adesivi HP & 3M Slim · cover & alto.",
    body: "Profili in PVC VØ U.V. per il fissaggio delle targhette FLAT in quadro elettrico. Disponibili senza fori, pre-forati, adesivi (3M Slim o HP) e con cover trasparenti. Lunghezze 430 / 500 / 650 / 1000 mm.",
    pills: ["9 mm", "15 mm", "Neri", "Grigi", "Adesivo HP", "3M Slim", "Senza fori", "Con fori", "Cover"],
  },
  8: {
    num: "08", label: "SUPPORTI PER PULSANTI", pages: "74 — 77",
    title: { pre: "Supporti", accent: "per pulsanti" },
    img: "products/06-pulsanti/pulsanti_1.png",
    icon: "button",
    gallery: [
      "products/06-pulsanti/pulsanti_0.png",
      "products/06-pulsanti/pulsanti_2.png",
      "products/06-pulsanti/pulsanti_4.png",
    ],
    lead: "D 22 + 17 × N · rettangolari / arrotondati · adesivi · kit completi.",
    body: "Porta-targhette per pulsanti Ø 22 e formato 17 × N. Geometria rettangolare o arrotondata, versione adesiva o senza adesivo, kit completi con targhetta + vetro.",
    pills: ["D 22", "17 × N", "Rettangolare", "Round", "Adesivo", "NO Adhesive", "Kit completo"],
  },
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "mp",
  "density": "regular"
}/*EDITMODE-END*/;

function App() {
  const [route, setRoute] = React.useState("home");
  const [familyId, setFamilyId] = React.useState(1);
  const [compatQuery, setCompatQuery] = React.useState("");
  const [highlightSku, setHighlightSku] = React.useState(null);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Force palette table theme — non tweakable
  React.useEffect(() => {
    document.documentElement.setAttribute("data-accent", t.accent);
    document.documentElement.setAttribute("data-density", t.density);
    document.documentElement.setAttribute("data-table-theme", "palette");
  }, [t.accent, t.density]);

  // Browser back/forward support via History API
  React.useEffect(() => {
    if (!window.history.state) {
      window.history.replaceState({ route: "home", familyId: 1, compatQuery: "", highlightSku: null }, "");
    }
    const onPop = (e) => {
      const s = e.state || { route: "home", familyId: 1, compatQuery: "", highlightSku: null };
      setRoute(s.route || "home");
      if (s.familyId != null) setFamilyId(s.familyId);
      setCompatQuery(s.compatQuery || "");
      setHighlightSku(s.highlightSku || null);
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  const navigate = (r, fid, q, sku) => {
    const nextFid = fid != null ? fid : familyId;
    const nextQ  = q !== undefined ? q : compatQuery;
    const nextSku = sku || null;
    setRoute(r);
    if (fid != null) setFamilyId(fid);
    if (q !== undefined) setCompatQuery(q);
    setHighlightSku(nextSku);
    window.scrollTo({ top: 0, behavior: "instant" });
    const state = { route: r, familyId: nextFid, compatQuery: nextQ, highlightSku: nextSku };
    try { window.history.pushState(state, "", ""); } catch (e) {}
  };

  const family = FAMILIES[familyId] || FAMILIES[1];
  const products = window.PRODUCTS_DATA || [];

  return (
    <>
      <Header route={route} navigate={navigate} />

      {route === "home" && (
        <>
          <HeroRotator navigate={navigate} />
          <StatsBlock />
          <FamilyGrid navigate={navigate} families={FAMILIES} />
          <CompatFinderHome navigate={navigate} products={products} />
          <ConradBlock />
        </>
      )}

      {route === "family" && (
        <FamilyDetail family={family} navigate={navigate} highlightSku={highlightSku} />
      )}

      {route === "azienda" && (
        <AziendaPage navigate={navigate} />
      )}

      {route === "compatibilita" && (
        <CompatibilitaPage navigate={navigate} products={products} initialQuery={compatQuery} />
      )}

      {route === "listini" && (
        <ListiniPage navigate={navigate} setFamilyId={setFamilyId} />
      )}

      {route === "contatti" && (
        <ContattiPage />
      )}

      <Footer navigate={navigate} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Accent" />
        <TweakColor label="Colore"
          value={t.accent === "mp" ? "#2A9D8F" : t.accent === "navy" ? "#0F2E4C" : "#15181C"}
          options={["#2A9D8F", "#0F2E4C", "#15181C"]}
          onChange={(hex) => {
            const map = { "#2A9D8F": "mp", "#0F2E4C": "navy", "#15181C": "ink" };
            setTweak("accent", map[hex] || "mp");
          }} />

        <TweakSection label="Densità" />
        <TweakRadio label="Spazio"
          value={t.density}
          options={[
            { value: "compact", label: "Compatto" },
            { value: "regular", label: "Regolare" },
            { value: "airy",    label: "Aerato" },
          ]}
          onChange={(v) => setTweak("density", v)} />

        <TweakSection label="Vai a…" />
        <TweakButton label="Home · Sistema"      onClick={() => navigate("home")} />
        <TweakButton label="01 · Rotoli"         onClick={() => navigate("family", 1)} />
        <TweakButton label="02 · Card"           onClick={() => navigate("family", 2)} />
        <TweakButton label="03 · Tubetti"        onClick={() => navigate("family", 3)} />
        <TweakButton label="04 · Fascettabili"   onClick={() => navigate("family", 4)} />
        <TweakButton label="05 · Adesivi"        onClick={() => navigate("family", 5)} />
        <TweakButton label="06 · Per binari"     onClick={() => navigate("family", 6)} />
        <TweakButton label="07 · Binari"         onClick={() => navigate("family", 7)} />
        <TweakButton label="08 · Pulsanti"       onClick={() => navigate("family", 8)} />
        <TweakButton label="Compatibilità"       onClick={() => navigate("compatibilita")} />
        <TweakButton label="Azienda & Qualità"   onClick={() => navigate("azienda")} />
        <TweakButton label="Listini"             onClick={() => navigate("listini")} />
        <TweakButton label="Contatti"            onClick={() => navigate("contatti")} />
      </TweaksPanel>
    </>
  );
}

Object.assign(window, { App, FAMILIES });
