// Tweaks panel — toggled by host toolbar via postMessage protocol
const { useState: useTweakState, useEffect: useTweakEffect } = React;

function TweaksPanel({ defaults }) {
  const [active, setActive] = useTweakState(false);
  const [values, setValues] = useTweakState(defaults);

  useTweakEffect(() => {
    const handler = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setActive(true);
      if (e.data.type === "__deactivate_edit_mode") setActive(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  // apply values live
  useTweakEffect(() => {
    document.documentElement.style.setProperty("--purple", values.accentColor);
    // derive dark/light variants
    document.documentElement.style.setProperty("--purple-dark", shade(values.accentColor, -0.12));
    document.documentElement.style.setProperty("--purple-light", shade(values.accentColor, 0.55));

    const fonts = FONT_PAIRS[values.fontPair] || FONT_PAIRS.default;
    document.documentElement.style.setProperty("--font-serif", fonts.serif);
    document.documentElement.style.setProperty("--font-sans", fonts.sans);
    // Also update inline style nodes using hardcoded family strings
    document.documentElement.style.setProperty("--tweak-serif", fonts.serif);
    document.documentElement.style.setProperty("--tweak-sans", fonts.sans);
  }, [values]);

  const update = (k, v) => {
    const next = { ...values, [k]: v };
    setValues(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
  };

  if (!active) return null;

  return (
    <div style={{
      position: "fixed",
      bottom: 24, right: 88,
      width: 320,
      background: "#fff",
      border: "1px solid #E5E5E5",
      borderRadius: 12,
      boxShadow: "0 20px 48px rgba(0,0,0,0.18)",
      zIndex: 100,
      fontFamily: '"Noto Sans JP", sans-serif',
      overflow: "hidden",
    }}>
      <div style={{ padding: "16px 20px", borderBottom: "1px solid #E5E5E5", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontFamily: '"Space Grotesk"', fontSize: 12, letterSpacing: "0.2em", color: "#1A1A1A", fontWeight: 500 }}>— TWEAKS —</div>
        <div style={{ fontFamily: '"Playfair Display"', fontStyle: "italic", fontSize: 14, color: "var(--purple)" }}>Live</div>
      </div>
      <div style={{ padding: 20, display: "flex", flexDirection: "column", gap: 20 }}>
        <div>
          <div style={{ fontFamily: '"Space Grotesk"', fontSize: 10, letterSpacing: "0.2em", color: "#6B6B6B", fontWeight: 500, marginBottom: 10 }}>ACCENT COLOR</div>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {["#7C5CFF", "#5B4CFF", "#E85CFF", "#FF5C7C", "#1A1530", "#0EA5A5"].map((c) => (
              <button key={c}
                onClick={() => update("accentColor", c)}
                style={{
                  width: 32, height: 32,
                  borderRadius: 8,
                  background: c,
                  border: values.accentColor === c ? "2px solid #1A1A1A" : "1px solid #E5E5E5",
                  cursor: "pointer",
                  padding: 0,
                }}
              />
            ))}
          </div>
        </div>
        <div>
          <div style={{ fontFamily: '"Space Grotesk"', fontSize: 10, letterSpacing: "0.2em", color: "#6B6B6B", fontWeight: 500, marginBottom: 10 }}>TYPOGRAPHY</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {Object.entries(FONT_PAIRS).map(([k, v]) => (
              <button key={k}
                onClick={() => update("fontPair", k)}
                style={{
                  textAlign: "left",
                  padding: "10px 12px",
                  background: values.fontPair === k ? "#FAF8F5" : "#fff",
                  border: "1px solid " + (values.fontPair === k ? "var(--purple)" : "#E5E5E5"),
                  borderRadius: 8,
                  cursor: "pointer",
                  fontFamily: '"Noto Sans JP"',
                  fontSize: 12,
                  color: "#1A1A1A",
                }}
              >
                <div style={{ fontFamily: v.serif, fontSize: 15, fontWeight: 500 }}>{v.label}</div>
                <div style={{ fontSize: 10, color: "#6B6B6B", marginTop: 3, fontFamily: '"Space Grotesk"', letterSpacing: "0.1em" }}>{v.desc}</div>
              </button>
            ))}
          </div>
        </div>
        <div>
          <div style={{ fontFamily: '"Space Grotesk"', fontSize: 10, letterSpacing: "0.2em", color: "#6B6B6B", fontWeight: 500, marginBottom: 10 }}>SIDE RAIL</div>
          <button
            onClick={() => update("showSideRail", !values.showSideRail)}
            style={{
              width: "100%",
              padding: "10px 12px",
              background: values.showSideRail ? "var(--purple)" : "#fff",
              color: values.showSideRail ? "#fff" : "#1A1A1A",
              border: "1px solid " + (values.showSideRail ? "var(--purple)" : "#E5E5E5"),
              borderRadius: 8,
              cursor: "pointer",
              fontFamily: '"Noto Sans JP"',
              fontSize: 12,
              textAlign: "left",
            }}
          >
            {values.showSideRail ? "表示中 — MEET / RECRUIT" : "非表示"}
          </button>
        </div>
      </div>
    </div>
  );
}

const FONT_PAIRS = {
  default: {
    label: "Noto Serif × Noto Sans",
    desc: "DEFAULT — JAPANESE MODERN",
    serif: '"Noto Serif JP", "Playfair Display", serif',
    sans: '"Noto Sans JP", system-ui, sans-serif',
  },
  editorial: {
    label: "Playfair × Inter",
    desc: "EDITORIAL — WESTERN",
    serif: '"Playfair Display", "Noto Serif JP", serif',
    sans: '"Inter", "Noto Sans JP", sans-serif',
  },
  tech: {
    label: "IBM Plex Serif × Plex Sans",
    desc: "TECH — ENGINEERING FEEL",
    serif: '"IBM Plex Serif", "Noto Serif JP", serif',
    sans: '"IBM Plex Sans", "Noto Sans JP", sans-serif',
  },
};

// Simple color shade utility (hex only)
function shade(hex, amt) {
  const h = hex.replace("#", "");
  const num = parseInt(h, 16);
  let r = (num >> 16) & 0xff;
  let g = (num >> 8) & 0xff;
  let b = num & 0xff;
  if (amt < 0) {
    r = Math.round(r * (1 + amt));
    g = Math.round(g * (1 + amt));
    b = Math.round(b * (1 + amt));
  } else {
    r = Math.round(r + (255 - r) * amt);
    g = Math.round(g + (255 - g) * amt);
    b = Math.round(b + (255 - b) * amt);
  }
  return "#" + [r, g, b].map((v) => v.toString(16).padStart(2, "0")).join("");
}

Object.assign(window, { TweaksPanel });
