const PALETTES = {
  calabria: {
    label: "Calabria",
    light: { "--paper": "#f5f0e6", "--paper-2": "#eae3d3", "--ink": "#0c1b2a", "--ocra": "#c9920c", "--petrolio": "#1a5e8e", "--muted": "#536872", "--line": "#cecdbc" },
    dark:  { "--paper": "#0a1520", "--paper-2": "#142030", "--ink": "#edf2f5", "--ocra": "#e8a822", "--petrolio": "#5ba8d8", "--muted": "#7ba8c0", "--line": "#22384a" },
  },
  mediterraneo: {
    label: "Mediterraneo",
    light: { "--paper": "#f2ede3", "--paper-2": "#e8e1d2", "--ink": "#262019", "--ocra": "#a8804a", "--petrolio": "#1e4d5c", "--muted": "#6b5f4e", "--line": "#d9cfbd" },
    dark:  { "--paper": "#1a1612", "--paper-2": "#241e17", "--ink": "#f1ebdf", "--ocra": "#c9955a", "--petrolio": "#6ba6b6", "--muted": "#a89a84", "--line": "#3a3129" },
  },
  terracotta: {
    label: "Terracotta",
    light: { "--paper": "#faf5ec", "--paper-2": "#f0e3d3", "--ink": "#2b1a12", "--ocra": "#c65d3c", "--petrolio": "#2d4a3e", "--muted": "#7a5a48", "--line": "#e3cdb3" },
    dark:  { "--paper": "#1c120e", "--paper-2": "#261813", "--ink": "#f5ead9", "--ocra": "#e07a52", "--petrolio": "#6ea897", "--muted": "#b49884", "--line": "#3d2a22" },
  },
  bianco_pepe: {
    label: "Bianco & pepe",
    light: { "--paper": "#ffffff", "--paper-2": "#f3efe8", "--ink": "#0f0f0f", "--ocra": "#8b3a2f", "--petrolio": "#2a3338", "--muted": "#6a6a6a", "--line": "#e5e1d8" },
    dark:  { "--paper": "#0f0e0c", "--paper-2": "#1b1917", "--ink": "#f5f2eb", "--ocra": "#d97153", "--petrolio": "#94a6ad", "--muted": "#9a968d", "--line": "#2c2a26" },
  },
  petrolio: {
    label: "Petrolio",
    light: { "--paper": "#eef0ea", "--paper-2": "#dfe3dc", "--ink": "#0d2327", "--ocra": "#b87a3a", "--petrolio": "#0d5763", "--muted": "#566a6d", "--line": "#cad2c8" },
    dark:  { "--paper": "#0d1416", "--paper-2": "#17201f", "--ink": "#e5ecea", "--ocra": "#d89862", "--petrolio": "#7cc2cd", "--muted": "#8ca3a4", "--line": "#2a3735" },
  },
  peperoncino: {
    label: "Peperoncino",
    light: { "--paper": "#fdf6ec", "--paper-2": "#f5e3d1", "--ink": "#2a0f0a", "--ocra": "#c33a1e", "--petrolio": "#3b5a3a", "--muted": "#805041", "--line": "#e7cfb8" },
    dark:  { "--paper": "#160a07", "--paper-2": "#22100c", "--ink": "#f8ead8", "--ocra": "#e8604a", "--petrolio": "#87b390", "--muted": "#b8917f", "--line": "#3a1d15" },
  },
  bronzi: {
    label: "Bronzi di Riace",
    light: { "--paper": "#edeee8", "--paper-2": "#dcddd4", "--ink": "#1a221f", "--ocra": "#8a6b32", "--petrolio": "#4b7d8c", "--muted": "#5f6b66", "--line": "#c9cbc0" },
    dark:  { "--paper": "#0e1311", "--paper-2": "#18201c", "--ink": "#e8ebe4", "--ocra": "#c9a24d", "--petrolio": "#8fc2cf", "--muted": "#9aa5a0", "--line": "#2a332f" },
  },
};

const FONT_PAIRS = {
  "cormorant-inter": { label: "Cormorant + Inter", display: '"Cormorant Garamond", serif', body: '"Inter", sans-serif' },
  "fraunces-dm":     { label: "Fraunces + DM Sans", display: '"Fraunces", serif',           body: '"DM Sans", sans-serif' },
  "playfair-work":   { label: "Playfair + Work",    display: '"Playfair Display", serif',  body: '"Work Sans", sans-serif' },
  "eb-inter":        { label: "EB Garamond + Inter",display: '"EB Garamond", serif',        body: '"Inter", sans-serif' },
};

function applyTweaks({ palette, fontPair, density, dark }) {
  const root = document.documentElement;
  const pal = PALETTES[palette] || PALETTES.mediterraneo;
  const vars = dark ? pal.dark : pal.light;
  Object.entries(vars).forEach(([k, v]) => root.style.setProperty(k, v));
  const fp = FONT_PAIRS[fontPair] || FONT_PAIRS["cormorant-inter"];
  root.style.setProperty("--font-display", fp.display);
  root.style.setProperty("--font-body", fp.body);
  root.classList.remove("dense", "airy");
  if (density === "dense") root.classList.add("dense");
  if (density === "airy") root.classList.add("airy");
  root.classList.toggle("dark", !!dark);
}
window.applyTweaks = applyTweaks;
window.PALETTES = PALETTES;
window.FONT_PAIRS = FONT_PAIRS;

function TweaksPanel({ state, setState, onClose }) {
  const set = (patch) => {
    const next = { ...state, ...patch };
    setState(next);
    try {
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: patch }, "*");
    } catch {}
  };

  const Row = ({ label, children }) => (
    <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)" }}>
      <div style={{
        fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em",
        textTransform: "uppercase", color: "var(--muted)", marginBottom: 10,
      }}>{label}</div>
      {children}
    </div>
  );

  const Pill = ({ active, onClick, children }) => (
    <button onClick={onClick} style={{
      padding: "6px 12px", borderRadius: 999, border: "1px solid " + (active ? "var(--ink)" : "var(--line)"),
      background: active ? "var(--ink)" : "transparent", color: active ? "var(--paper)" : "var(--ink)",
      fontSize: 11, letterSpacing: "0.06em",
    }}>{children}</button>
  );

  return (
    <div style={{
      position: "fixed", bottom: 24, right: 24, width: 340, zIndex: 300,
      background: "var(--paper)", border: "1px solid var(--line)",
      boxShadow: "0 20px 60px -10px rgba(0,0,0,.25)",
      maxHeight: "80vh", overflowY: "auto",
      fontFamily: "var(--font-body)",
    }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: "16px 20px", borderBottom: "1px solid var(--line)", position: "sticky", top: 0, background: "var(--paper)", zIndex: 2,
      }}>
        <div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500, lineHeight: 1 }}>Tweaks</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em", color: "var(--muted)", marginTop: 4, textTransform: "uppercase" }}>
            Modifica dal vivo
          </div>
        </div>
        <button onClick={onClose} aria-label="Chiudi" style={{
          background: "transparent", border: "1px solid var(--line)",
          width: 32, height: 32, borderRadius: 999, display: "grid", placeItems: "center", color: "var(--ink)",
        }}><IconClose /></button>
      </div>

      <Row label="Palette">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          {Object.entries(PALETTES).map(([k, p]) => {
            const cols = p.light;
            const active = state.palette === k;
            return (
              <button key={k} onClick={() => set({ palette: k })} style={{
                padding: 10, border: "1px solid " + (active ? "var(--ink)" : "var(--line)"),
                background: "transparent", textAlign: "left", display: "flex", flexDirection: "column", gap: 8,
              }}>
                <div style={{ display: "flex", height: 18 }}>
                  {[cols["--paper"], cols["--ocra"], cols["--petrolio"], cols["--ink"]].map((c, i) => (
                    <div key={i} style={{ flex: 1, background: c }} />
                  ))}
                </div>
                <div style={{ fontSize: 11, fontWeight: active ? 600 : 400 }}>{p.label}</div>
              </button>
            );
          })}
        </div>
      </Row>

      <Row label="Coppia di font">
        <div style={{ display: "grid", gap: 6 }}>
          {Object.entries(FONT_PAIRS).map(([k, fp]) => {
            const active = state.fontPair === k;
            return (
              <button key={k} onClick={() => set({ fontPair: k })} style={{
                padding: "10px 12px", border: "1px solid " + (active ? "var(--ink)" : "var(--line)"),
                background: active ? "var(--paper-2)" : "transparent", textAlign: "left",
              }}>
                <div style={{ fontFamily: fp.display, fontSize: 20, lineHeight: 1 }}>Aa</div>
                <div style={{ fontFamily: fp.body, fontSize: 11, marginTop: 4, color: "var(--muted)" }}>{fp.label}</div>
              </button>
            );
          })}
        </div>
      </Row>

      <Row label="Densità">
        <div style={{ display: "flex", gap: 6 }}>
          {[["dense", "Compatto"], ["default", "Default"], ["airy", "Spazioso"]].map(([k, l]) => (
            <Pill key={k} active={state.density === k} onClick={() => set({ density: k })}>{l}</Pill>
          ))}
        </div>
      </Row>

      <Row label="Stile card">
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {[["editorial", "Editoriale"], ["overlay", "Overlay"], ["compact", "Compatto"]].map(([k, l]) => (
            <Pill key={k} active={state.cardStyle === k} onClick={() => set({ cardStyle: k })}>{l}</Pill>
          ))}
        </div>
      </Row>

      <Row label="Hero">
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {[["split", "Split"], ["centered", "Centrato"], ["fullbleed", "Full-bleed"]].map(([k, l]) => (
            <Pill key={k} active={state.heroLayout === k} onClick={() => set({ heroLayout: k })}>{l}</Pill>
          ))}
        </div>
      </Row>

      <Row label="Tema">
        <div style={{ display: "flex", gap: 6 }}>
          <Pill active={!state.dark} onClick={() => set({ dark: false })}>☼ Chiaro</Pill>
          <Pill active={state.dark} onClick={() => set({ dark: true })}>☾ Scuro</Pill>
        </div>
      </Row>
    </div>
  );
}
window.TweaksPanel = TweaksPanel;
