/* global React, FORMATS, CATEGORIES, DEVICES, FormatPreview, DimSchema */
const { useState, useMemo, useEffect } = React;

function useMobile() {
  const [mobile, setMobile] = useState(window.innerWidth < 768);
  useEffect(() => {
    const h = () => setMobile(window.innerWidth < 768);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  return mobile;
}

const FONT = "'Jost', sans-serif";
const MONO = "'Spline Sans Mono', monospace";
const Y = "#FFDF00", DK = "#1C1C1C", BG = "#FFFFFF", CARD = "#F2F2F2", MUTE = "#888";

// ─── Language context ────────────────────────────────────────
const LangCtx = React.createContext({ lang: 'it', setLang: () => {} });
const useLang = () => React.useContext(LangCtx);
// Picks the _en variant of a field when lang is 'en', falls back to base field
const loc = (obj, field, lang) =>
  lang === 'en' && obj[field + '_en'] !== undefined ? obj[field + '_en'] : obj[field];

const TR = {
  it: {
    hero: ["PIANIFICA", "LA TUA", "CAMPAGNA"],
    heroSub: "Tutte le specifiche tecniche, i pesi e i template pronti per la consegna su AUTOMOTO network",
    clearFilters: "azzera filtri",
    noFormats: "Nessun formato trovato",
    noFormatsHint: "Prova a modificare i filtri.",
    fmtCount: (n) => `${n} ${n === 1 ? "formato" : "formati"}`,
    previewLabel: "Anteprima in pagina",
    dimSchema: "Schema dimensioni",
    techSpecs: "Specifiche tecniche",
    noteLabel: "Nota",
    copyLink: "Copia link",
    copied: "✓ Copiato",
    footerKeyword: "Materiali",
    footerDeadline: "almeno 3 giorni lavorativi prima della messa online.",
    html5LinkText: "Requisiti tecnici per le creatività HTML5 →",
    html5ValidateText: "Valida la correttezza degli asset HTML5 con",
    html5ValidateLink: "questo tool →",
    dimLabel: "Dimensioni",
    weightLabel: "Peso max",
    filesLabel: "File ammessi",
    varDim: "dimensioni variabili",
  },
  en: {
    hero: ["PLAN", "YOUR", "CAMPAIGN"],
    heroSub: "All technical specs, weights and ready-to-deliver templates for the AUTOMOTO network",
    clearFilters: "clear filters",
    noFormats: "No formats found",
    noFormatsHint: "Try changing the filters.",
    fmtCount: (n) => `${n} ${n === 1 ? "format" : "formats"}`,
    previewLabel: "In-page preview",
    dimSchema: "Dimensions diagram",
    techSpecs: "Technical specs",
    noteLabel: "Note",
    copyLink: "Copy link",
    copied: "✓ Copied",
    footerKeyword: "Materials",
    footerDeadline: "at least 3 business days before going live.",
    html5LinkText: "Technical requirements for HTML5 creatives →",
    html5ValidateText: "Validate your HTML5 assets with",
    html5ValidateLink: "this tool →",
    dimLabel: "Dimensions",
    weightLabel: "Max weight",
    filesLabel: "Accepted files",
    varDim: "variable dimensions",
  }
};

// ─────────────────────────────────────────────
// Header — white, ALL CAPS nav, lang toggle
// ─────────────────────────────────────────────
function AdvHeader({ onLogo, mobile }) {
  const { lang, setLang } = useLang();
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
      background: BG, borderBottom: "1px solid rgba(28,28,28,0.08)",
      height: 60, display: "flex", alignItems: "center",
      padding: mobile ? "0 20px" : "0 52px", gap: mobile ? 12 : 36
    }}>
      <div onClick={onLogo} style={{ display: "flex", gap: 10, cursor: "pointer", alignItems: "center", flexShrink: 0 }}>
        <img src="assets/am_network.svg" alt="Automoto Network" style={{ height: mobile ? 28 : 40 }} />
      </div>

      <div style={{ marginLeft: "auto", display: "flex", gap: 10, alignItems: "center" }}>
        {!mobile && <span style={{
          fontFamily: FONT, fontSize: 11, fontWeight: 600, letterSpacing: 0.8,
          color: "rgba(28,28,28,0.45)"
        }}>MEDIA KIT 2026</span>}
        {/* Language toggle */}
        <div style={{ display: "flex", borderRadius: 100, border: "1.5px solid rgba(28,28,28,0.18)", overflow: "hidden", flexShrink: 0 }}>
          {["it", "en"].map(l =>
            <button key={l} onClick={() => setLang(l)} style={{
              height: 28, padding: "0 11px",
              background: lang === l ? DK : BG,
              color: lang === l ? "#fff" : MUTE,
              border: "none", fontFamily: FONT, fontSize: 11, fontWeight: 700,
              cursor: "pointer", letterSpacing: 0.8, textTransform: "uppercase",
              transition: "background 0.15s, color 0.15s"
            }}>{l}</button>
          )}
        </div>
      </div>
    </header>);
}

// ─────────────────────────────────────────────
// Hero — editorial two-column
// ─────────────────────────────────────────────
function Hero({ total, mobile }) {
  const { lang } = useLang();
  const t = TR[lang];
  return (
    <div style={{ maxWidth: 1160, margin: "0 auto", padding: mobile ? "32px 20px 28px" : "60px 52px 52px", display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: mobile ? 24 : 48, alignItems: "center" }}>
      {/* Left — headline */}
      <div>
        {/* badge */}
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 28 }}>
          <span style={{ width: 22, height: 22, borderRadius: "50%", background: Y, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 800 }}>✓</span>
          <span style={{ fontFamily: FONT, fontSize: 11, fontWeight: 700, letterSpacing: 2, textTransform: "uppercase", color: DK }}>ADV</span>
        </div>

        {/* headline — 3 stacked lines with underrule */}
        <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
          {[
          { text: t.hero[0], w: 300 },
          { text: t.hero[1], w: 600 },
          { text: t.hero[2], w: 900, accent: true }].
          map(({ text, w, accent }) =>
          <div key={text} style={{
            fontFamily: FONT, fontWeight: w, fontSize: mobile ? 52 : 84, lineHeight: 1,
            letterSpacing: -2, color: DK, textTransform: "uppercase",
            borderBottom: `2px solid ${accent ? Y : "rgba(28,28,28,0.12)"}`,
            paddingBottom: 6, marginBottom: 2,
            display: "flex", alignItems: "center", justifyContent: "space-between"
          }}>
              {text}
            </div>
          )}
        </div>

        <p style={{
          fontFamily: FONT, fontSize: 15, fontWeight: 400, color: MUTE, lineHeight: 1.6,
          margin: "26px 0 0", maxWidth: 440
        }}>{t.heroSub}</p>
      </div>

      {/* Right — hero image */}
      {!mobile && <div style={{ position: "relative", height: 360 }}>
        <img
          src="uploads/pasted-1781780817099-0.png"
          alt="Dispositivi media"
          style={{ width: "100%", height: "100%", objectFit: "contain", objectPosition: "center" }} />
      </div>}
    </div>);
}

// ─────────────────────────────────────────────
// Filter pills — outlined on white
// ─────────────────────────────────────────────
function FilterPill({ label, count, active, onClick }) {
  const [hover, setHover] = useState(false);
  return (
    <button onClick={onClick}
    onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
    style={{
      display: "inline-flex", alignItems: "center", gap: 8,
      height: 38,
      background: active ? DK : hover ? CARD : BG,
      color: active ? "#fff" : DK,
      border: `1.5px solid ${active ? DK : "rgba(28,28,28,0.18)"}`,
      borderRadius: 100, fontFamily: FONT, fontSize: 12, fontWeight: 600,
      cursor: "pointer", whiteSpace: "nowrap", transition: "all 0.15s", letterSpacing: 0.3, padding: "0px 16px"
    }}>
      {label}
      {count != null &&
      <span style={{ fontFamily: MONO, fontSize: 10, fontWeight: 600, color: active ? "rgba(255,255,255,0.5)" : MUTE }}>{count}</span>
      }
    </button>);
}

// ─────────────────────────────────────────────
// Format card — #F2F2F2 bg, editorial style
// ─────────────────────────────────────────────
function FormatCard({ fmt, onOpen }) {
  const [hover, setHover] = useState(false);
  const { lang } = useLang();
  return (
    <div
      onClick={() => onOpen(fmt)}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: hover ? "#EAEAEA" : CARD,
        borderRadius: 18,
        display: "flex", flexDirection: "column", cursor: "pointer",
        padding: "22px 22px 20px",
        transition: "background 0.2s ease, transform 0.2s ease",
        transform: hover ? "translateY(-2px)" : "none"
      }}>

      {/* top row */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <span style={{ fontFamily: FONT, fontSize: 10.5, fontWeight: 700, letterSpacing: 1.8, color: MUTE, textTransform: "uppercase" }}>{loc(fmt, 'catLabel', lang)}</span>
        <span style={{
          width: 26, height: 26, borderRadius: "50%", flexShrink: 0,
          border: `1.5px solid ${hover ? DK : "rgba(28,28,28,0.25)"}`,
          background: hover ? Y : "transparent",
          color: DK,
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 16, lineHeight: 1, transition: "all 0.2s"
        }}>+</span>
      </div>

      {/* name */}
      <div style={{
        fontFamily: FONT, fontWeight: 700, fontSize: 22, color: DK,
        lineHeight: 1.12, letterSpacing: -0.4, marginTop: 14
      }}>{loc(fmt, 'name', lang)}</div>

      {/* meta */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: MONO, fontSize: 11.5, color: MUTE, marginTop: 7 }}>
        <span>{fmt.dim}</span>
        <span style={{ width: 3, height: 3, borderRadius: "50%", background: "#CCC" }}></span>
        <span style={{ fontFamily: FONT, fontWeight: 400, fontSize: 12 }}>{fmt.device}</span>
      </div>

      {/* illustration */}
      <div style={{ marginTop: "auto", paddingTop: 20 }}>
        {fmt.device === "Mobile" ?
        <div style={{ display: "flex", justifyContent: "center" }}>
            <div style={{ width: 80, height: 130, overflow: "hidden", borderRadius: 6 }}>
              <FormatPreview kind={fmt.kind} dim={fmt.dim} height={130} />
            </div>
          </div> :

        <FormatPreview kind={fmt.kind} dim={fmt.dim} height={120} />
        }
      </div>
    </div>);
}

// Copy link button
function CopyLinkBtn() {
  const [copied, setCopied] = useState(false);
  const { lang } = useLang();
  const t = TR[lang];
  const copy = () => {
    navigator.clipboard.writeText(window.location.href).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };
  return (
    <button onClick={copy} style={{
      ...navBtn, gap: 5, padding: "0 12px", width: "auto",
      background: copied ? "#FFDF00" : "#fff",
      border: `1.5px solid ${copied ? "#FFDF00" : "rgba(28,28,28,0.2)"}`,
      transition: "all 0.2s", fontSize: 11, letterSpacing: 0.4, fontWeight: 700
    }}>
      {copied ? t.copied : t.copyLink}
    </button>);
}

// Spec chip — compact card for the 2-col grid
function SpecChip({ label, value, mono, accent, html5, link, onLink }) {
  const hasHtml5 = html5 && typeof value === "string" && value.includes("HTML5");
  // Append "px" to dimension values (e.g. "728×90" → "728×90 px")
  const displayValue = label === "Dimensioni" && value && value !== "—" && !value.includes("px") && /[\d×x]/.test(value) ?
  value + " px" :
  value;
  return (
    <div onClick={link && onLink ? () => onLink(link) : undefined} style={{ background: CARD, borderRadius: 8, padding: "10px 12px", display: "flex", flexDirection: "column", gap: 3, cursor: link ? "pointer" : "default", position: "relative", transition: "background 0.15s" }} onMouseEnter={link ? (e) => e.currentTarget.style.background = "#E6E6E6" : undefined} onMouseLeave={link ? (e) => e.currentTarget.style.background = CARD : undefined}>
      <div style={{ fontFamily: FONT, fontSize: 9.5, fontWeight: 700, letterSpacing: 1.2, color: MUTE, textTransform: "uppercase" }}>{label}</div>
      <div style={{ ...{
          fontFamily: mono ? MONO : FONT,
          fontSize: accent ? 15 : 12.5,
          fontWeight: accent ? 700 : 500,
          color: DK, lineHeight: 1.3
        }, fontWeight: "700" }}>
        {hasHtml5 ? <WithHtml5Note text={displayValue} /> : displayValue}
      </div>
      {link && <span style={{ position: "absolute", top: 8, right: 8, width: 18, height: 18, borderRadius: 4, background: "#FFDF00", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, fontWeight: 800, color: DK }}>↗</span>}
    </div>);
}

// ─────────────────────────────────────────────
// Detail modal
// ─────────────────────────────────────────────
function DetailModal({ fmt, onClose, onNav, onOpen }) {
  const mobile = useMobile();
  const { lang } = useLang();
  const t = TR[lang];

  useEffect(() => {
    const h = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") onNav(-1);
      if (e.key === "ArrowRight") onNav(1);
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose, onNav]);

  if (!fmt) return null;

  const mPad = mobile ? 16 : 26;
  const displaySpecs = lang === 'en' && fmt.specs_en && Object.keys(fmt.specs_en).length > 0
    ? fmt.specs_en : fmt.specs;
  const ctaButtons = loc(fmt, 'ctaButtons', lang);
  const fmtName = loc(fmt, 'name', lang);
  const fmtCatLabel = loc(fmt, 'catLabel', lang);
  const fmtNote = loc(fmt, 'note', lang);

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 100,
      background: "rgba(10,10,10,0.55)", backdropFilter: "blur(4px)",
      display: "flex", alignItems: mobile ? "flex-end" : "center", justifyContent: "center", padding: mobile ? 0 : 32
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: BG, width: "100%", maxWidth: mobile ? "100%" : 960,
        height: mobile ? "92dvh" : "auto", maxHeight: mobile ? "92dvh" : "88vh",
        display: "flex", flexDirection: "column", overflow: "hidden",
        borderRadius: mobile ? "18px 18px 0 0" : 20, boxShadow: "0 24px 80px rgba(0,0,0,0.3)"
      }}>
        {/* Header */}
        {mobile ? (
          /* Mobile header */
          <div style={{ background: BG, borderBottom: `1px solid rgba(28,28,28,0.08)`, padding: "12px 16px 14px", flexShrink: 0 }}>
            <div style={{ width: 36, height: 4, borderRadius: 2, background: "rgba(28,28,28,0.15)", margin: "0 auto 12px" }}></div>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <span style={{ display: "inline-block", padding: "3px 10px", borderRadius: 100, background: Y, fontFamily: FONT, fontSize: 9, fontWeight: 700, letterSpacing: 1.2, color: DK, textTransform: "uppercase", marginBottom: 6 }}>{fmtCatLabel}</span>
                <div style={{ fontFamily: FONT, fontWeight: 800, fontSize: 18, color: DK, letterSpacing: -0.3, lineHeight: 1.15, wordBreak: "break-word" }}>{fmtName}</div>
                <div style={{ fontFamily: MONO, fontSize: 11, color: MUTE, fontWeight: 500, marginTop: 3 }}>{fmt.dim} · {fmt.device}</div>
              </div>
              <button onClick={onClose} style={{ ...navBtn, flexShrink: 0, marginTop: 2 }}>✕</button>
            </div>
          </div>
        ) : (
          /* Desktop header */
          <div style={{ background: BG, borderBottom: `1px solid rgba(28,28,28,0.1)`, padding: "22px 28px", display: "flex", alignItems: "center", gap: 16, flexShrink: 0 }}>
            <span style={{ padding: "4px 12px", borderRadius: 100, background: Y, fontFamily: FONT, fontSize: 10, fontWeight: 700, letterSpacing: 1.4, color: DK, textTransform: "uppercase" }}>{fmtCatLabel}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: FONT, fontWeight: 800, fontSize: 22, color: DK, letterSpacing: -0.5, lineHeight: 1.1 }}>{fmtName}</div>
              <div style={{ fontFamily: MONO, fontSize: 12, color: MUTE, fontWeight: 500, marginTop: 4 }}>{fmt.dim} · {fmt.device}</div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <button onClick={() => onNav(-1)} style={navBtn}>‹</button>
              <button onClick={() => onNav(1)} style={navBtn}>›</button>
              <CopyLinkBtn />
              <button onClick={onClose} style={{ ...navBtn, marginLeft: 4 }}>✕</button>
            </div>
          </div>
        )}

        {/* Body */}
        <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1.05fr 1fr", overflow: "auto", flex: 1, minHeight: 0 }}>
          {/* Left panel — preview */}
          <div style={{ padding: mPad, borderRight: mobile ? "none" : "1px solid rgba(28,28,28,0.08)", borderBottom: mobile ? "1px solid rgba(28,28,28,0.08)" : "none", background: CARD }}>
            <SectionLabel>{t.previewLabel}</SectionLabel>
            {fmt.device === "Mobile" ? (
            <div style={{ display: "flex", justifyContent: "center", marginBottom: 20 }}>
                <div style={{ width: mobile ? 160 : 200, height: mobile ? 290 : 360, background: "#F2F2F2", border: "1px solid #E6E6E6", borderRadius: 10, overflow: "hidden" }}>
                  <FormatPreview kind={fmt.kind} dim={fmt.dim} height={mobile ? 290 : 360} animated={true} />
                </div>
              </div>) :
            <div style={{ background: "#F2F2F2", padding: mobile ? 10 : 16, border: "1px solid #E6E6E6", marginBottom: 20, borderRadius: 10 }}>
                <FormatPreview kind={fmt.kind} dim={fmt.dim} height={mobile ? 200 : 300} animated={true} />
              </div>
            }
            {!fmt.hideDimSchema && <><SectionLabel>{t.dimSchema}</SectionLabel>
            <div style={{ display: "flex", flexWrap: "wrap", justifyContent: "center", background: "#fff", border: "1px solid #E6E6E6", padding: mobile ? "16px 0 6px" : "8px 0 6px", borderRadius: 10, gap: 0, overflowX: "hidden" }}>
              {fmt.schemas ?
                fmt.schemas.map((s, i) => <DimSchema key={i} w={s.w} h={s.h}
                  label={lang === 'en' && s.label_en ? s.label_en : s.label}
                  maxW={mobile ? 120 : 180} maxH={mobile ? 90 : 130} />) :
                <DimSchema w={fmt.w} h={fmt.h}
                  label={fmt.dim === "—" ? t.varDim : null}
                  maxW={mobile ? 120 : 240} maxH={mobile ? 90 : 150} />
                }
            </div></>}
          </div>

          {/* Right panel — specs + note + CTA */}
          <div style={{ padding: mPad, display: "flex", flexDirection: "column", gap: 18, overflow: mobile ? "visible" : "auto" }}>

            {/* ── Specifiche tecniche ── */}
            <div>
              <SectionLabel>{t.techSpecs}</SectionLabel>
              {fmt.specGroups ?
              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                  {fmt.specGroups.map((group, gi) =>
                <div key={gi}>
                      <div style={{ fontFamily: FONT, fontSize: 10, fontWeight: 700, letterSpacing: 1.2, color: MUTE, textTransform: "uppercase", marginBottom: 7, paddingBottom: 5, borderBottom: `1px solid rgba(28,28,28,0.07)` }}>
                        {lang === 'en' && group.title_en ? group.title_en : group.title}
                      </div>
                      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                        {group.chips.map((c, ci) =>
                    <SpecChip key={ci}
                          label={lang === 'en' && c.label_en ? c.label_en : c.label}
                          value={lang === 'en' && c.value_en ? c.value_en : c.value}
                          mono={c.mono} accent={c.accent} link={c.link} onLink={onOpen} />
                    )}
                      </div>
                    </div>
                )}
                </div> :

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                  <SpecChip label={loc(fmt, 'dimLabel', lang) || t.dimLabel} value={fmt.dim} mono accent />
                  {fmt.weight && <SpecChip label={t.weightLabel} value={fmt.weight} />}
                  <SpecChip label={t.filesLabel} value={fmt.files} html5 />
                  {Object.entries(displaySpecs).map(([k, v]) => <SpecChip key={k} label={k} value={v} link={fmt.specLinks && fmt.specLinks[k]} onLink={onOpen} />)}
                </div>
              }
            </div>

            {/* ── Nota operativa ── */}
            {fmtNote && <div style={{ background: "#fff", borderRadius: 10, padding: "12px 14px", border: `1px solid rgba(28,28,28,0.1)`, borderLeft: `3px solid ${Y}` }}>
              <div style={{ fontFamily: FONT, fontSize: 10, fontWeight: 700, letterSpacing: 1.2, color: MUTE, textTransform: "uppercase", marginBottom: 5 }}>{t.noteLabel}</div>
              <div style={{ fontFamily: FONT, fontSize: 12.5, color: DK, lineHeight: 1.55 }}>{fmtNote}</div>
            </div>}

            {/* ── HTML5 footnote ── */}
            {fmt.files && fmt.files.includes("HTML5") &&
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                  <span style={{ width: 20, height: 20, borderRadius: 5, background: Y, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 800, color: DK, marginTop: 1 }}>↗</span>
                  <span style={{ fontFamily: FONT, fontSize: 13, color: DK, lineHeight: 1.45, fontWeight: 400 }}>
                    <a href={HTML5_URL} style={{ color: DK, fontWeight: 700, textDecoration: "underline" }}>{t.html5LinkText}</a>
                  </span>
                </div>
                <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                  <span style={{ width: 20, height: 20, borderRadius: 5, background: Y, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 800, color: DK, marginTop: 1 }}>↗</span>
                  <span style={{ fontFamily: FONT, fontSize: 13, color: DK, lineHeight: 1.45, fontWeight: 400 }}>
                    {t.html5ValidateText}{" "}
                    <a href="https://h5validator.appspot.com/adwords/asset" target="_blank" rel="noopener" style={{ color: DK, fontWeight: 700, textDecoration: "underline" }}>{t.html5ValidateLink}</a>
                  </span>
                </div>
              </div>
            }

            {/* ── CTA buttons (format-specific) ── */}
            {ctaButtons &&
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: "auto" }}>
                {ctaButtons.map((btn, i) =>
              <a key={i} href={btn.href} style={{
                display: "flex", alignItems: "center", justifyContent: "center",
                height: 46, border: "none",
                borderRadius: 100, background: Y,
                color: DK, fontFamily: FONT, fontSize: 14, fontWeight: 700,
                cursor: "pointer", letterSpacing: 0.3, textDecoration: "none"
              }}>{btn.label}</a>
              )}
              </div>
            }

          </div>
        </div>

        {/* Mobile bottom nav bar */}
        {mobile && (
          <div style={{ borderTop: `1px solid rgba(28,28,28,0.09)`, padding: "10px 16px", display: "flex", alignItems: "center", gap: 8, background: BG, flexShrink: 0 }}>
            <button onClick={() => onNav(-1)} style={{ ...navBtn, flex: 1, width: "auto", height: 42, fontSize: 20 }}>‹</button>
            <CopyLinkBtn />
            <button onClick={() => onNav(1)} style={{ ...navBtn, flex: 1, width: "auto", height: 42, fontSize: 20 }}>›</button>
          </div>
        )}
      </div>
    </div>);
}

const navBtn = { width: 34, height: 34, borderRadius: 8, border: `1.5px solid rgba(28,28,28,0.2)`, background: BG, color: DK, fontSize: 16, fontWeight: 700, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: FONT };
const btnPrimary = { width: "100%", height: 46, border: "none", borderRadius: 100, background: Y, color: DK, fontFamily: FONT, fontSize: 14, fontWeight: 700, cursor: "pointer", letterSpacing: 0.3 };
const btnGhost = { height: 46, padding: "0 24px", border: `1.5px solid ${DK}`, borderRadius: 100, background: BG, color: DK, fontFamily: FONT, fontSize: 14, fontWeight: 700, cursor: "pointer" };

const HTML5_URL = "html5-specs.html";

function WithHtml5Note({ text }) {
  return <>{text}</>;
}

function SectionLabel({ children }) {
  return <div style={{ fontFamily: FONT, fontSize: 11, fontWeight: 700, letterSpacing: 1.4, color: "#9E9E9E", textTransform: "uppercase", marginBottom: 11 }}>{children}</div>;
}
function SpecRow({ label, value, mono }) {
  const hasHtml5 = typeof value === "string" && value.includes("HTML5");
  return (
    <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 12, padding: "9px 0", borderBottom: "1px solid #F0F0F0" }}>
      <div style={{ fontFamily: FONT, fontSize: 11, fontWeight: 600, letterSpacing: 0.6, color: "#9E9E9E", textTransform: "uppercase" }}>{label}</div>
      <div style={{ fontFamily: mono ? MONO : FONT, fontSize: 13.5, fontWeight: mono ? 600 : 500, color: DK }}>
        {hasHtml5 ? <WithHtml5Note text={value} /> : value}
      </div>
    </div>);
}

// ─────────────────────────────────────────────
// App
// ─────────────────────────────────────────────
function AdvApp() {
  const [lang, setLang] = useState('it');
  const [cat, setCat] = useState("all");
  const [device, setDevice] = useState(null);
  const [openId, setOpenIdState] = useState(() => window.location.hash.slice(1) || null);
  const mobile = useMobile();
  const t = TR[lang];

  // Sync URL hash → state
  useEffect(() => {
    const onHash = () => setOpenIdState(window.location.hash.slice(1) || null);
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const openFormat = (id) => { window.location.hash = id; setOpenIdState(id); };
  const closeFormat = () => {
    history.pushState("", document.title, window.location.pathname + window.location.search);
    setOpenIdState(null);
  };

  const catCount = useMemo(() => {
    const m = { all: FORMATS.length };
    FORMATS.forEach((f) => { m[f.cat] = (m[f.cat] || 0) + 1; });
    return m;
  }, []);

  const filtered = useMemo(() =>
  FORMATS.filter((f) => {
    if (cat !== "all" && f.cat !== cat) return false;
    if (device && f.device !== device && f.device !== "All" && f.device !== "Desktop - Mobile") return false;
    return true;
  }), [cat, device]);

  const allIdx = FORMATS.findIndex((f) => f.id === openId);
  const openFmt = allIdx >= 0 ? FORMATS[allIdx] : null;
  const nav = (dir) => {
    if (allIdx < 0) return;
    const next = FORMATS[(allIdx + dir + FORMATS.length) % FORMATS.length];
    openFormat(next.id);
  };

  const catLabel = (c) => lang === 'en' && c.label_en ? c.label_en : c.label;

  return (
    <LangCtx.Provider value={{ lang, setLang }}>
      <div style={{ minHeight: "100vh", background: BG, fontFamily: FONT }}>
        <AdvHeader onLogo={() => { setCat("all"); setDevice(null); }} mobile={mobile} />

        <Hero total={FORMATS.length} mobile={mobile} />

        {/* Divider */}
        <div style={{ maxWidth: 1160, margin: "0 auto", padding: mobile ? "0 20px" : "0 52px" }}>
          <div style={{ height: 1, background: "rgba(28,28,28,0.08)" }}></div>
        </div>

        {/* Filter bar */}
        <div style={{ maxWidth: 1160, margin: "0 auto", padding: mobile ? "14px 20px 12px" : "28px 52px 24px" }}>
          {mobile ? (
          /* Mobile: select + device toggle */
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <select value={cat} onChange={(e) => setCat(e.target.value)} style={{
                flex: 1, height: 40, borderRadius: 100, border: `1.5px solid rgba(28,28,28,0.18)`,
                padding: "0 16px", fontFamily: FONT, fontSize: 13, fontWeight: 600, color: DK,
                background: BG, appearance: "none", cursor: "pointer"
              }}>
                  {CATEGORIES.map((c) => <option key={c.key} value={c.key}>{catLabel(c)} ({catCount[c.key] || 0})</option>)}
                </select>
                <div style={{ display: "flex", gap: 6 }}>
                  {DEVICES.map((d) =>
                <button key={d} onClick={() => setDevice(device === d ? null : d)} style={{
                  height: 40, padding: "0 14px", borderRadius: 100,
                  background: device === d ? DK : BG, color: device === d ? "#fff" : MUTE,
                  border: `1.5px solid ${device === d ? DK : "rgba(28,28,28,0.15)"}`,
                  fontFamily: FONT, fontSize: 12, fontWeight: 600, cursor: "pointer", whiteSpace: "nowrap"
                }}>{d}</button>
                )}
                </div>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                {(cat !== "all" || device) &&
              <button onClick={() => { setCat("all"); setDevice(null); }} style={{
                background: "none", border: "none", cursor: "pointer",
                fontFamily: FONT, fontSize: 12, fontWeight: 700, color: DK, textDecoration: "underline", padding: 0
              }}>{t.clearFilters}</button>
              }
                <span style={{ marginLeft: "auto", fontFamily: MONO, fontSize: 11, color: MUTE }}>
                  {t.fmtCount(filtered.length)}
                </span>
              </div>
            </div>) : (

          /* Desktop: pill row */
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
              {CATEGORIES.map((c) =>
            <FilterPill key={c.key} label={catLabel(c)} count={catCount[c.key] || 0} active={cat === c.key} onClick={() => setCat(c.key)} />
            )}
              <div style={{ width: 1, height: 22, background: "rgba(28,28,28,0.12)", margin: "0 6px" }}></div>
              {DEVICES.map((d) =>
            <button key={d} onClick={() => setDevice(device === d ? null : d)} style={{
              height: 34, padding: "0 14px", borderRadius: 100,
              background: device === d ? DK : BG,
              color: device === d ? "#fff" : MUTE,
              border: `1px solid ${device === d ? DK : "rgba(28,28,28,0.15)"}`,
              fontFamily: FONT, fontSize: 12, fontWeight: 600, cursor: "pointer", transition: "all 0.15s"
            }}>{d}</button>
            )}
              {(cat !== "all" || device) &&
            <button onClick={() => { setCat("all"); setDevice(null); }} style={{
              background: "none", border: "none", cursor: "pointer",
              fontFamily: FONT, fontSize: 12, fontWeight: 700, color: DK, textDecoration: "underline", marginLeft: 4
            }}>{t.clearFilters}</button>
            }
              <span style={{ marginLeft: "auto", fontFamily: MONO, fontSize: 11, color: MUTE }}>
                {t.fmtCount(filtered.length)}
              </span>
            </div>)
          }
        </div>

        {/* Grid */}
        <div style={{ maxWidth: 1160, margin: "0 auto", padding: mobile ? "0 20px 60px" : "0 52px 100px" }}>
          {filtered.length === 0 ?
          <div style={{ padding: "80px 0", textAlign: "center" }}>
                <div style={{ fontSize: 18, fontWeight: 700, color: DK, marginBottom: 6 }}>{t.noFormats}</div>
                <div style={{ fontSize: 14, color: MUTE }}>{t.noFormatsHint}</div>
              </div> :
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 16 }}>
                {filtered.map((f) => <FormatCard key={f.id} fmt={f} onOpen={() => openFormat(f.id)} />)}
              </div>
          }
        </div>

        {/* Footer */}
        <div style={{ borderTop: "1px solid rgba(28,28,28,0.08)" }}>
          <div style={{ maxWidth: 1160, margin: "0 auto", padding: mobile ? "16px 20px" : "24px 52px", display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
            <img src="assets/am_network.svg" alt="Automoto Network" style={{ height: 24 }} onError={(e) => { e.target.style.display = "none"; }} />
            <span style={{ fontFamily: FONT, fontSize: 12, fontWeight: 400, color: MUTE }}>
              {t.footerKeyword}: <strong style={{ color: DK }}>adv@moto.it</strong> — {t.footerDeadline}
            </span>
            <span style={{ marginLeft: "auto", fontFamily: MONO, fontSize: 11, color: "rgba(28,28,28,0.3)" }}>© 2026 Automoto Network</span>
          </div>
        </div>

        <DetailModal fmt={openFmt} onClose={closeFormat} onNav={nav} onOpen={openFormat} />
      </div>
    </LangCtx.Provider>);
}

Object.assign(window, { AdvApp });
