// ============================================
// APP — Nav lateral + composição de seções + Tweaks
// ============================================
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "tradicional",
  "typePair": "alegreya-robotoslab",
  "density": "cozy",
  "texture": true
}/*EDITMODE-END*/;

// Paleta variations — só mexe em --accent/--highlight/bg tweaks
const PALETTE_VARIATIONS = {
  tradicional: {
    label: "Tradicional",
    vars: {} // default from tokens.css
  },
  noturno: {
    label: "Noturno",
    vars: {
      "--bg": "#1A1512",
      "--bg-alt": "#241B15",
      "--ink": "#FAF6EC",
      "--ink-muted": "rgba(250,246,236,0.8)",
      "--ink-soft": "rgba(250,246,236,0.55)",
      "--rule": "rgba(250,246,236,0.12)",
      "--rule-strong": "rgba(250,246,236,0.25)"
    }
  },
  bordo: {
    label: "Bordô",
    vars: {
      "--accent": "#7A2B1F",
      "--accent-strong": "#9B3E2E",
      "--highlight": "#D4A24A"
    }
  },
  claro: {
    label: "Claro",
    vars: {
      "--bg": "#FFFFFF",
      "--bg-alt": "#FAF6EC",
      "--papel": "#F5EFE0"
    }
  }
};

const TYPE_PAIRS = {
  "alegreya-robotoslab": {
    label: "Alegreya + Roboto Slab",
    vars: {
      "--font-display": "'Alegreya', Georgia, serif",
      "--font-body": "'Roboto Slab', Georgia, serif"
    }
  },
  "alegreya-lora": {
    label: "Alegreya + Lora",
    vars: {
      "--font-display": "'Alegreya', Georgia, serif",
      "--font-body": "'Lora', Georgia, serif"
    }
  }
};

function applyTweaks(tweaks) {
  const root = document.documentElement;
  // Reset inline vars that we may have set
  const touchedVars = new Set();
  Object.values(PALETTE_VARIATIONS).forEach(p => Object.keys(p.vars).forEach(k => touchedVars.add(k)));
  Object.values(TYPE_PAIRS).forEach(p => Object.keys(p.vars).forEach(k => touchedVars.add(k)));
  touchedVars.forEach(k => root.style.removeProperty(k));

  const palette = PALETTE_VARIATIONS[tweaks.palette] || PALETTE_VARIATIONS.tradicional;
  Object.entries(palette.vars).forEach(([k, v]) => root.style.setProperty(k, v));

  const pair = TYPE_PAIRS[tweaks.typePair] || TYPE_PAIRS["alegreya-robotoslab"];
  Object.entries(pair.vars).forEach(([k, v]) => root.style.setProperty(k, v));

  root.setAttribute("data-density", tweaks.density || "cozy");
  document.body.classList.toggle("no-texture", !tweaks.texture);
}

function NavSidebar({ active, open, onClose }) {
  const groups = [
    {
      title: "A marca",
      items: [
        { id: "capa", label: "Capa" },
        { id: "essencia", label: "Essência" },
        { id: "historia", label: "Nossa história" },
        { id: "linhagem", label: "A linhagem" },
        { id: "manifesto", label: "Manifesto" },
      ]
    },
    {
      title: "Identidade",
      items: [
        { id: "logo", label: "Logo & marca" },
        { id: "elemento", label: "Elemento gráfico" },
        { id: "cores", label: "Paleta de cores" },
        { id: "tipografia", label: "Tipografia" },
      ]
    },
    {
      title: "Sistema",
      items: [
        { id: "componentes", label: "Componentes" },
        { id: "voz", label: "Voz & tom" },
        { id: "mandamentos", label: "Mandamentos" },
        { id: "glossario", label: "Glossário da casa" },
      ]
    },
    {
      title: "Aplicações",
      items: [
        { id: "aplicacoes", label: "A marca no mundo" },
        { id: "fim", label: "Encerramento" },
      ]
    }
  ];

  const handleClick = (e, id) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) {
      el.scrollIntoView({ behavior: "smooth", block: "start" });
    }
    if (onClose) onClose();
  };

  return (
    <>
      <div
        className={"sidebar-backdrop " + (open ? "open" : "")}
        onClick={onClose}
      />
      <nav className={"sidebar " + (open ? "open" : "")}>
        <div className="sidebar-logo">
          <img src="assets/logo.png" alt="Choperia do Mário" />
        </div>
        <div className="sidebar-brand">Choperia<br/><em>do Mário</em></div>
        <div className="sidebar-sub">Brand System · v1.0</div>
      {groups.map((g, gi) => (
        <div key={g.title} className="nav-group">
          <div className="nav-group-title">
            <span style={{ opacity: 0.6 }}>{String(gi + 1).padStart(2, "0")}</span> &nbsp; {g.title}
          </div>
          {g.items.map(item => (
            <a
              key={item.id}
              href={`#${item.id}`}
              className={"nav-link " + (active === item.id ? "active" : "")}
              onClick={e => handleClick(e, item.id)}
            >
              {item.label}
            </a>
          ))}
        </div>
      ))}
    </nav>
    </>
  );
}

function TweaksPanel({ tweaks, setTweak, visible }) {
  if (!visible) return null;
  return (
    <div className="tweaks-panel">
      <h4>Tweaks</h4>
      <div className="tweak-group">
        <label className="tweak-label">Paleta</label>
        <div className="tweak-opts">
          {Object.entries(PALETTE_VARIATIONS).map(([k, v]) => (
            <button
              key={k}
              className={"tweak-btn " + (tweaks.palette === k ? "active" : "")}
              onClick={() => setTweak("palette", k)}
            >
              {v.label}
            </button>
          ))}
        </div>
      </div>
      <div className="tweak-group">
        <label className="tweak-label">Tipografia</label>
        <div className="tweak-opts">
          {Object.entries(TYPE_PAIRS).map(([k, v]) => (
            <button
              key={k}
              className={"tweak-btn " + (tweaks.typePair === k ? "active" : "")}
              onClick={() => setTweak("typePair", k)}
              style={{ minWidth: 96 }}
            >
              {v.label}
            </button>
          ))}
        </div>
      </div>
      <div className="tweak-group">
        <label className="tweak-label">Densidade</label>
        <div className="tweak-opts">
          {["compact", "cozy", "spacious"].map(d => (
            <button
              key={d}
              className={"tweak-btn " + (tweaks.density === d ? "active" : "")}
              onClick={() => setTweak("density", d)}
            >
              {d === "compact" ? "Compacto" : d === "cozy" ? "Padrão" : "Amplo"}
            </button>
          ))}
        </div>
      </div>
      <div className="tweak-group">
        <label className="tweak-label">Textura de papel</label>
        <div className="tweak-opts">
          <button
            className={"tweak-btn " + (tweaks.texture ? "active" : "")}
            onClick={() => setTweak("texture", true)}
          >
            Sim
          </button>
          <button
            className={"tweak-btn " + (!tweaks.texture ? "active" : "")}
            onClick={() => setTweak("texture", false)}
          >
            Não
          </button>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [tweaksVisible, setTweaksVisible] = useState(false);
  const [active, setActive] = useState("capa");
  const [navOpen, setNavOpen] = useState(false);

  useEffect(() => {
    applyTweaks(tweaks);
  }, [tweaks]);

  // Observer for active nav link
  useEffect(() => {
    const sections = document.querySelectorAll("section[id]");
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) setActive(e.target.id);
      });
    }, { rootMargin: "-40% 0px -50% 0px", threshold: 0 });
    sections.forEach(s => obs.observe(s));
    return () => obs.disconnect();
  }, []);

  // Tweaks host protocol
  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === "__activate_edit_mode") setTweaksVisible(true);
      if (e.data?.type === "__deactivate_edit_mode") setTweaksVisible(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  const setTweak = (key, val) => {
    const next = { ...tweaks, [key]: val };
    setTweaks(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [key]: val } }, "*");
  };

  return (
    <>
      <button
        className="mobile-nav-toggle"
        onClick={() => setNavOpen(true)}
        aria-label="Abrir navegação"
      >
        ☰
      </button>
      <NavSidebar active={active} open={navOpen} onClose={() => setNavOpen(false)} />
      <main className="main">
        <Cover />
        <Essencia />
        <HistoriaCapitulos />
        <Linhagem />
        <Manifesto />
        <LogoSection />
        <ElementoGrafico />
        <ColorSection />
        <TypographySection />
        <UIKitSection />
        <VoiceSection />
        <MandamentosSection />
        <GlossarioSection />
        <AplicacoesSection />
        <ClosingSection />
      </main>
      <TweaksPanel tweaks={tweaks} setTweak={setTweak} visible={tweaksVisible} />
    </>
  );
}

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