// Main app — wires content, language switch, tweaks panel

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "Pergamino (default)",
  "primaryGold": "#8a6a2a",
  "background": "#ede5d5",
  "paper": "#0a0908",
  "accent": "#6b2737",
  "fontPreset": "Inter (Helvética-style)",
  "headlineFont": "Inter",
  "bodyFont": "Inter",
  "headlineWeight": 700,
  "bodyWeight": 300,
  "headlineItalic": false,
  "iconPack": "lucide",
  "brandsLayout": "compact",
  "audienceLayout": "index",
  "methodLayout": "split",
  "servicesLayout": "list",
  "footerLayout": "functional",
  "heroBackground": "light",
  "navHover": "color"
}/*EDITMODE-END*/;

// Theme presets — each is a complete color system
const THEMES = {
  "Pergamino (default)": {
    cls: "theme-parchment",
    bg: "#ede5d5", bg2: "#e3d9c5", paper: "#0a0908",
    paperDim: "#4a423a", paperFaint: "#8a8276",
    gold: "#8a6a2a", goldDeep: "#5a4418",
    accent: "#6b2737",
    line: "rgba(10,9,8,0.14)", lineStrong: "rgba(10,9,8,0.28)",
    desc: "Crema cálido, dorado tostado. ADN de la marca.",
  },
  "Papel + tinta (editorial)": {
    cls: "theme-paper",
    bg: "#F7F4EE", bg2: "#EFEAE0", paper: "#1A1612",
    paperDim: "#5A5048", paperFaint: "#8F857A",
    gold: "#7A5A1F", goldDeep: "#4A3812",
    accent: "#5A2030",
    line: "rgba(26,22,18,0.12)", lineStrong: "rgba(26,22,18,0.28)",
    desc: "Blanco hueso, tinta carbón. Suplemento dominical.",
  },
  "Galería (museo)": {
    cls: "theme-gallery",
    bg: "#FFFFFF", bg2: "#FAFAFA", paper: "#0E0E0E",
    paperDim: "#555555", paperFaint: "#9A9A9A",
    gold: "#1A1A1A", goldDeep: "#000000",
    accent: "#1A1A1A",
    line: "rgba(0,0,0,0.10)", lineStrong: "rgba(0,0,0,0.30)",
    desc: "Blanco puro, una sola tinta. Catálogo de subasta.",
  },
  "Mármol y oro": {
    cls: "theme-marble",
    bg: "#F5F1E8", bg2: "#EDE7D9", paper: "#1F1A12",
    paperDim: "#5A4F3D", paperFaint: "#9A8E78",
    gold: "#A87E3A", goldDeep: "#6E4E1A",
    accent: "#7A2838",
    line: "rgba(31,26,18,0.14)", lineStrong: "rgba(31,26,18,0.30)",
    desc: "Mármol cálido, oro mate. Perfumería de nicho.",
  },
  "Suizo (tipográfico)": {
    cls: "theme-swiss",
    bg: "#FFFFFF", bg2: "#F4F4F4", paper: "#000000",
    paperDim: "#555555", paperFaint: "#888888",
    gold: "#000000", goldDeep: "#000000",
    accent: "#000000",
    line: "rgba(0,0,0,0.18)", lineStrong: "rgba(0,0,0,0.50)",
    desc: "Retícula suiza. Solo negro y gris. Vignelli.",
  },
  "Manuscrito (sepia)": {
    cls: "theme-manuscript",
    bg: "#F2EDE3", bg2: "#E8E1D2", paper: "#3A2818",
    paperDim: "#6A523A", paperFaint: "#9C846A",
    gold: "#7A4A1E", goldDeep: "#4A2A0E",
    accent: "#5A1820",
    line: "rgba(58,40,24,0.16)", lineStrong: "rgba(58,40,24,0.34)",
    desc: "Crema con tinta sepia. Cuaderno de erudito.",
  },
  "Bizantino (azul + oro)": {
    cls: "theme-byzantine",
    bg: "#0E1830", bg2: "#15203C", paper: "#F4ECD8",
    paperDim: "#C7BBA0", paperFaint: "#7A7158",
    gold: "#D4A859", goldDeep: "#A07E32",
    accent: "#C7355A",
    line: "rgba(244,236,216,0.14)", lineStrong: "rgba(244,236,216,0.32)",
    desc: "Azul medianoche + oro. Mosaico bizantino.",
  },
  "Bot\u00e1nico (verde + bronce)": {
    cls: "theme-botanical",
    bg: "#EDE8D8", bg2: "#E2DCC8", paper: "#1F2A1A",
    paperDim: "#4A5440", paperFaint: "#8A8A70",
    gold: "#7A6A2A", goldDeep: "#4E4218",
    accent: "#3A5A2A",
    line: "rgba(31,42,26,0.14)", lineStrong: "rgba(31,42,26,0.30)",
    desc: "Crema sage + tinta oliva. Herbolario.",
  },
  "Veneciano (terracota + oro)": {
    cls: "theme-venetian",
    bg: "#F5E8D8", bg2: "#EDDEC8", paper: "#3A1814",
    paperDim: "#6A3830", paperFaint: "#A07060",
    gold: "#A8763A", goldDeep: "#6E4E1A",
    accent: "#9A2820",
    line: "rgba(58,24,20,0.14)", lineStrong: "rgba(58,24,20,0.30)",
    desc: "Crema terracota + tinta veneciana. Quattrocento.",
  },
  "Cobre antiguo": {
    cls: "theme-copper",
    bg: "#F0E8DC", bg2: "#E5DCC8", paper: "#1F1814",
    paperDim: "#5A4A3A", paperFaint: "#9A8870",
    gold: "#B86838", goldDeep: "#7A4220",
    accent: "#5A2820",
    line: "rgba(31,24,20,0.14)", lineStrong: "rgba(31,24,20,0.30)",
    desc: "Crema c\u00e1lido + cobre forjado. Tipograf\u00eda industrial.",
  },
  "Tinta nocturna (oscuro)": {
    cls: "theme-nocturne",
    bg: "#0A0908", bg2: "#14110D", paper: "#EDE5D5",
    paperDim: "#A89E88", paperFaint: "#6A6258",
    gold: "#C9A961", goldDeep: "#8a6a2a",
    accent: "#A03848",
    line: "rgba(237,229,213,0.10)", lineStrong: "rgba(237,229,213,0.24)",
    desc: "Modo oscuro. Tinta nocturna + oro encendido.",
  },
  "Verdigris (p\u00e1tina)": {
    cls: "theme-verdigris",
    bg: "#EFE9D8", bg2: "#E3DCC4", paper: "#142824",
    paperDim: "#3A4E48", paperFaint: "#7A8A82",
    gold: "#3E7A6A", goldDeep: "#1F4E42",
    accent: "#A07838",
    line: "rgba(20,40,36,0.14)", lineStrong: "rgba(20,40,36,0.30)",
    desc: "Cobre oxidado + crema. P\u00e1tina del tiempo.",
  },
  "\u00c1mbar (miel + sombra)": {
    cls: "theme-amber",
    bg: "#F4E4C4", bg2: "#EDD8B0", paper: "#2A1A0A",
    paperDim: "#5A4220", paperFaint: "#8A7048",
    gold: "#A87024", goldDeep: "#6E4612",
    accent: "#7A2818",
    line: "rgba(42,26,10,0.14)", lineStrong: "rgba(42,26,10,0.30)",
    desc: "Miel + sombra. Resina antigua, dorado intenso.",
  },
  "Borgo\u00f1a (vino + crema)": {
    cls: "theme-bordeaux",
    bg: "#F2E8DC", bg2: "#E8DCC8", paper: "#2A0810",
    paperDim: "#5A2030", paperFaint: "#9A6878",
    gold: "#8A5A2A", goldDeep: "#5A3818",
    accent: "#7A1828",
    line: "rgba(42,8,16,0.14)", lineStrong: "rgba(42,8,16,0.30)",
    desc: "Crema + vino borgo\u00f1a. C\u00e1lido y refinado.",
  },
  "\u00cdndigo (azul tinta + ocre)": {
    cls: "theme-indigo",
    bg: "#E8E4D4", bg2: "#DCD8C4", paper: "#0A1830",
    paperDim: "#3A4A6A", paperFaint: "#7A8AA0",
    gold: "#B07A2A", goldDeep: "#7A5018",
    accent: "#5A2030",
    line: "rgba(10,24,48,0.14)", lineStrong: "rgba(10,24,48,0.30)",
    desc: "Azul tinta profundo + ocre. Cart\u00f3grafo del XVIII.",
  },
  "Carb\u00f3n (dark editorial)": {
    cls: "theme-charcoal",
    bg: "#181614", bg2: "#22201D", paper: "#F4F0E8",
    paperDim: "#A89E88", paperFaint: "#6A6258",
    gold: "#B89858", goldDeep: "#7A6028",
    accent: "#C95040",
    line: "rgba(244,240,232,0.10)", lineStrong: "rgba(244,240,232,0.24)",
    desc: "Carb\u00f3n editorial. Magazine nocturno.",
  },
  "Lino (off-white minimal)": {
    cls: "theme-linen",
    bg: "#F8F4EC", bg2: "#F0EAE0", paper: "#2A2620",
    paperDim: "#5A5448", paperFaint: "#8A8478",
    gold: "#8A7038", goldDeep: "#5A4820",
    accent: "#7A3838",
    line: "rgba(42,38,32,0.10)", lineStrong: "rgba(42,38,32,0.26)",
    desc: "Lino lavado. M\u00ednimo, c\u00e1lido, callado.",
  },
};

// Curated typographic presets — each is a complete system (display + body + weights + style)
const FONT_PRESETS = {
  "Inter (Helvética-style)": {
    headline: "Inter", body: "Inter", hw: 700, bw: 300, italic: false,
    desc: "Sans neogrotesco. Bold + light. Actual.",
  },
  "Helvetica Neue": {
    headline: "Helvetica Neue", body: "Helvetica Neue", hw: 700, bw: 300, italic: false,
    desc: "Helvética nativa del sistema. Clásico atemporal.",
  },
  "Söhne (Inter Tight)": {
    headline: "Inter Tight", body: "Inter Tight", hw: 600, bw: 400, italic: false,
    desc: "Sans condensada moderna. Editorial tech.",
  },
  "Space Grotesk": {
    headline: "Space Grotesk", body: "Space Grotesk", hw: 600, bw: 400, italic: false,
    desc: "Geométrica con personalidad. Diseño contemporáneo.",
  },
  "DM Sans": {
    headline: "DM Sans", body: "DM Sans", hw: 700, bw: 400, italic: false,
    desc: "Sans humanista limpia. Producto digital.",
  },
  "Manrope": {
    headline: "Manrope", body: "Manrope", hw: 700, bw: 300, italic: false,
    desc: "Sans variable balanceada. Calmada y profesional.",
  },
  "Cormorant + Inter": {
    headline: "Cormorant Garamond", body: "Inter", hw: 500, bw: 300, italic: true,
    desc: "Serif renacentista + sans. Místico editorial.",
  },
  "Playfair + Inter": {
    headline: "Playfair Display", body: "Inter", hw: 500, bw: 300, italic: true,
    desc: "Serif high-contrast + sans. Editorial moda.",
  },
  "Cinzel + Manrope": {
    headline: "Cinzel", body: "Manrope", hw: 500, bw: 300, italic: false,
    desc: "Capitales romanas + sans. Ritual / alquímico.",
  },
  "Italiana + Manrope": {
    headline: "Italiana", body: "Manrope", hw: 400, bw: 300, italic: false,
    desc: "Didone ultra fina + sans. Lujo discreto.",
  },
  "DM Serif + DM Sans": {
    headline: "DM Serif Display", body: "DM Sans", hw: 400, bw: 400, italic: false,
    desc: "Serif moderna + sans hermana. Editorial actual.",
  },
  "Fraunces + Inter": {
    headline: "Fraunces", body: "Inter", hw: 500, bw: 300, italic: false,
    desc: "Serif variable cálida. Intelectual contemporánea.",
  },
  "EB Garamond + JetBrains Mono": {
    headline: "EB Garamond", body: "EB Garamond", hw: 500, bw: 400, italic: true,
    desc: "Garamond histórico + mono técnico. Manuscrito digital.",
  },
  "Tenor Sans (mono)": {
    headline: "Tenor Sans", body: "Tenor Sans", hw: 400, bw: 400, italic: false,
    desc: "Sans con remates triangulares. Minimalista uncial.",
  },
};

const App = () => {
  const [lang, setLang] = React.useState("es");
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const t = window.CONTENT[lang];

  // Section parallax fade — IntersectionObserver for cross-browser support
  React.useEffect(() => {
    const sections = document.querySelectorAll(".fa-shell > section:not(#hero)");
    if (!sections.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("is-visible");
          entry.target.classList.remove("is-leaving");
        } else {
          // Only mark as "leaving" if scrolled past (not before reaching)
          const rect = entry.boundingClientRect;
          if (rect.top < 0) {
            entry.target.classList.add("is-leaving");
            entry.target.classList.remove("is-visible");
          }
        }
      });
    }, { threshold: [0, 0.15, 0.85, 1], rootMargin: "-10% 0px -10% 0px" });
    sections.forEach((s) => io.observe(s));
    return () => io.disconnect();
  }, []);

  // Apply tweaks as CSS variables
  React.useEffect(() => {
    const root = document.documentElement;
    const theme = THEMES[tweaks.theme] || THEMES["Pergamino (default)"];

    // Apply theme palette as base
    root.style.setProperty("--fa-bg", theme.bg);
    root.style.setProperty("--fa-bg-2", theme.bg2);
    root.style.setProperty("--fa-paper", theme.paper);
    root.style.setProperty("--fa-paper-dim", theme.paperDim);
    root.style.setProperty("--fa-paper-faint", theme.paperFaint);
    root.style.setProperty("--fa-gold", theme.gold);
    root.style.setProperty("--fa-gold-deep", theme.goldDeep);
    root.style.setProperty("--fa-burgundy", theme.accent);
    root.style.setProperty("--fa-line", theme.line);
    root.style.setProperty("--fa-line-strong", theme.lineStrong);

    // Toggle theme class on body for theme-specific overrides (nav bg, etc.)
    document.body.className = document.body.className
      .split(" ").filter(c => !c.startsWith("theme-")).join(" ").trim();
    document.body.classList.add(theme.cls);

    // Typography
    root.style.setProperty("--fa-serif", `"${tweaks.headlineFont}", Georgia, serif`);
    root.style.setProperty("--fa-sans", `"${tweaks.bodyFont}", -apple-system, sans-serif`);
    root.style.setProperty("--fa-headline-weight", tweaks.headlineWeight);
    root.style.setProperty("--fa-body-weight", tweaks.bodyWeight);
    root.style.setProperty("--fa-headline-style", tweaks.headlineItalic ? "italic" : "normal");
  }, [tweaks]);

  // Apply preset
  const applyPreset = (name) => {
    const p = FONT_PRESETS[name];
    if (!p) return;
    setTweak({
      fontPreset: name,
      headlineFont: p.headline,
      bodyFont: p.body,
      headlineWeight: p.hw,
      bodyWeight: p.bw,
      headlineItalic: p.italic,
    });
  };

  return (
    <IconPackContext.Provider value={tweaks.iconPack}>
    <div className={`fa-shell nav-hover-${tweaks.navHover || 'color'}`}>
      <Nav t={t} lang={lang} setLang={setLang} />
      <Hero t={t} layout={tweaks.heroBackground} />
      <Services t={t} layout={tweaks.servicesLayout} />
      <Brands t={t} layout={tweaks.brandsLayout} />
      <Clients t={t} />
      <Audience t={t} layout={tweaks.audienceLayout} />
      <Contact t={t} />
      <Footer t={t} layout={tweaks.footerLayout} />

      <TweaksPanel title="Tweaks">
        <TweakSection title="Tema">
          <TweakSelect label="Theme" value={tweaks.theme}
            options={Object.keys(THEMES)}
            onChange={(v) => setTweak("theme", v)} />
          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", lineHeight: 1.4, padding: "2px 0 6px" }}>
            {THEMES[tweaks.theme]?.desc}
          </div>
        </TweakSection>
        <TweakSection title="Color (override)">
          <TweakColor label="Dorado primario" value={tweaks.primaryGold}
            onChange={(v) => setTweak("primaryGold", v)} />
          <TweakColor label="Fondo" value={tweaks.background}
            onChange={(v) => setTweak("background", v)} />
          <TweakColor label="Pergamino (texto)" value={tweaks.paper}
            onChange={(v) => setTweak("paper", v)} />
          <TweakColor label="Acento" value={tweaks.accent}
            onChange={(v) => setTweak("accent", v)} />
        </TweakSection>
        <TweakSection title="Tipografía">
          <TweakSelect label="Preset" value={tweaks.fontPreset}
            options={Object.keys(FONT_PRESETS)}
            onChange={applyPreset} />
          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", lineHeight: 1.4, padding: "2px 0 6px" }}>
            {FONT_PRESETS[tweaks.fontPreset]?.desc}
          </div>
        </TweakSection>
        <TweakSection title="Ajuste fino">
          <TweakSelect label="Display" value={tweaks.headlineFont}
            options={[
              "Inter","Inter Tight","Helvetica Neue","Space Grotesk","DM Sans","Manrope","Tenor Sans",
              "Cormorant Garamond","EB Garamond","Playfair Display","Cinzel","Italiana","DM Serif Display","Fraunces"
            ]}
            onChange={(v) => setTweak("headlineFont", v)} />
          <TweakSelect label="Body" value={tweaks.bodyFont}
            options={["Inter","Inter Tight","Helvetica Neue","Space Grotesk","DM Sans","Manrope","Tenor Sans","EB Garamond"]}
            onChange={(v) => setTweak("bodyFont", v)} />
          <TweakSlider label="Display weight" value={tweaks.headlineWeight}
            min={200} max={800} step={100}
            onChange={(v) => setTweak("headlineWeight", v)} />
          <TweakSlider label="Body weight" value={tweaks.bodyWeight}
            min={200} max={600} step={100}
            onChange={(v) => setTweak("bodyWeight", v)} />
          <TweakToggle label="Display itálica acento" value={tweaks.headlineItalic}
            onChange={(v) => setTweak("headlineItalic", v)} />
        </TweakSection>
        <TweakSection title="Iconografía">
          <TweakSelect label="Pack" value={tweaks.iconPack}
            options={Object.keys(ICON_PACKS)}
            onChange={(v) => setTweak("iconPack", v)} />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 6, padding: "6px 0" }}>
            {Object.keys(ICON_PACKS).map((k) => (
              <button key={k} onClick={() => setTweak("iconPack", k)}
                title={ICON_PACK_LABELS[k]}
                style={{
                  background: tweaks.iconPack === k ? "rgba(255,255,255,0.18)" : "rgba(255,255,255,0.05)",
                  border: tweaks.iconPack === k ? "1px solid rgba(255,255,255,0.4)" : "1px solid rgba(255,255,255,0.12)",
                  borderRadius: 4, padding: "8px 4px", color: "#e8c878",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  cursor: "pointer", minHeight: 36,
                }}>
                <IconPackContext.Provider value={k}>
                  <Icon name="counsel" size={20} />
                </IconPackContext.Provider>
              </button>
            ))}
          </div>
        </TweakSection>
        <TweakSection title="Marcas — Layout">
          <TweakSelect label="Estilo" value={tweaks.brandsLayout}
            options={[
              { value: "compact", label: "1 · Compacto (3×3 mobile)" },
              { value: "marquee", label: "2 · Marquee infinito" },
              { value: "big", label: "3 · Grande 2 columnas" },
              { value: "carousel", label: "4 · Carrusel paginado" },
              { value: "stack", label: "5 · Lista vertical editorial" },
            ]}
            onChange={(v) => setTweak("brandsLayout", v)} />
        </TweakSection>
        <TweakSection title="Servicios — Layout">
          <TweakSelect label="Estilo" value={tweaks.servicesLayout}
            options={[
              { value: "list", label: "1 · Lista accordion (actual)" },
              { value: "pictogram", label: "2 · Pictograma XL (3 col)" },
              { value: "numeral", label: "3 · Numeral monumental" },
              { value: "triad", label: "4 · Triada radial" },
              { value: "vcards", label: "5 · Cards verticales" },
              { value: "minimal", label: "6 · Glyph + duración" },
              { value: "flow", label: "7 · Flujo horizontal" },
              { value: "emblem", label: "8 · Emblema / cartel" },
              { value: "editorial", label: "9 · Editorial · índice de libro ★" },
              { value: "sticky", label: "10 · Sticky scroll cinematográfico ★" },
              { value: "audience", label: "11 · Para quién (audiencia) ★" },
            ]}
            onChange={(v) => setTweak("servicesLayout", v)} />
        </TweakSection>
        <TweakSection title="Método — Layout">
          <TweakSelect label="Estilo" value={tweaks.methodLayout}
            options={[
              { value: "split", label: "1 · Split (actual)" },
              { value: "steps", label: "2 · Pasos numerados" },
              { value: "tabs", label: "3 · Tabs / acordeón" },
              { value: "diagram", label: "4 · Diagrama radial" },
              { value: "cards", label: "5 · Cards 2×2" },
              { value: "stack", label: "6 · Stack editorial XL" },
              { value: "marquee", label: "7 · Banda + detalle" },
              { value: "timeline", label: "8 · Timeline vertical" },
              { value: "simple", label: "9 · Editorial mínima ★" },
            ]}
            onChange={(v) => setTweak("methodLayout", v)} />
        </TweakSection>
        <TweakSection title="Audiencia — Layout">
          <TweakSelect label="Estilo" value={tweaks.audienceLayout}
            options={[
              { value: "split", label: "1 · Split editorial (actual)" },
              { value: "manifesto", label: "2 · Manifiesto centrado" },
              { value: "index", label: "3 · Índice numerado" },
              { value: "matrix", label: "4 · Matriz fricción" },
              { value: "ribbon", label: "5 · Banda + outcomes" },
              { value: "ledger", label: "6 · Hoja contable" },
            ]}
            onChange={(v) => setTweak("audienceLayout", v)} />
        </TweakSection>
        <TweakSection title="Hero — Fondo">
          <TweakSelect label="Estilo" value={tweaks.heroBackground}
            options={[
              { value: "photo", label: "1 · Foto original" },
              { value: "ink", label: "2 · Tinta dorada (SVG)" },
              { value: "video", label: "3 · Video" },
              { value: "light", label: "4 · Rayo de luz ★" },
            ]}
            onChange={(v) => setTweak("heroBackground", v)} />
        </TweakSection>
        <TweakSection title="Nav — Hover">
          <TweakSelect label="Estilo" value={tweaks.navHover}
            options={[
              { value: "underline", label: "1 · Línea inferior (actual)" },
              { value: "color", label: "2 · Solo color" },
              { value: "pill", label: "3 · Cápsula de fondo" },
              { value: "brackets", label: "4 · Brackets [ texto ]" },
              { value: "dot", label: "5 · Punto a la izquierda" },
              { value: "tracking", label: "6 · Tracking expandido" },
              { value: "slash", label: "7 · Slash prefix /" },
              { value: "italic", label: "8 · Cursiva" },
            ]}
            onChange={(v) => setTweak("navHover", v)} />
        </TweakSection>
        <TweakSection title="Footer — Layout">
          <TweakSelect label="Estilo" value={tweaks.footerLayout}
            options={[
              { value: "default", label: "1 · Default (logo + tagline + rights)" },
              { value: "monumental", label: "2 · Monumental · wordmark a sangre ★" },
              { value: "cta", label: "3 · CTA · última invitación ★" },
              { value: "colophon", label: "4 · Colofón · sigilo + frase ★" },
              { value: "functional", label: "5 · Funcional · 4 columnas" },
              { value: "grid3", label: "6 · Grid 3 — marca · nav · redes ★" },
            ]}
            onChange={(v) => setTweak("footerLayout", v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
    </IconPackContext.Provider>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
