/* ===================== TWEAKS PANEL ===================== */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "navMode": "multi",
  "accentTone": "green-dominant",
  "heroChips": true,
  "density": "comfortable",
  "ctaCopy": "Find your starting point"
}/*EDITMODE-END*/;

function TweaksPanel() {
  const [open, setOpen] = React.useState(false);
  const [available, setAvailable] = React.useState(false);
  const [t, setT] = React.useState(TWEAK_DEFAULTS);

  // Apply tweaks live
  React.useEffect(() => {
    const root = document.documentElement;
    // accent tone
    if (t.accentTone === "navy-dominant") {
      root.style.setProperty("--green-deep", "#1b3f73");
      root.style.setProperty("--green", "#2a558f");
      root.style.setProperty("--green-spring", "#3d77c4");
      root.style.setProperty("--green-bright", "#8ab4e3");
    } else if (t.accentTone === "orange-dominant") {
      root.style.setProperty("--green-deep", "#c66a14");
      root.style.setProperty("--green", "#ed7b1f");
      root.style.setProperty("--green-spring", "#f39c20");
      root.style.setProperty("--green-bright", "#fbd28a");
    } else {
      root.style.removeProperty("--green-deep");
      root.style.removeProperty("--green");
      root.style.removeProperty("--green-spring");
      root.style.removeProperty("--green-bright");
    }
    // density
    document.body.dataset.density = t.density;
    // nav mode
    try { localStorage.setItem("smbe_nav_mode", t.navMode); } catch (e) {}
    // hero chips
    document.querySelectorAll(".hc-chip").forEach((el) => {
      el.style.display = t.heroChips ? "" : "none";
    });
    // cta copy
    const ctas = document.querySelectorAll('[data-cta-find]');
    ctas.forEach((el) => { el.textContent = t.ctaCopy; });

    // single-page mode: convert internal nav links to anchors
    if (t.navMode === "single") {
      document.querySelectorAll('a[href*="tiers/"], a[href*="case-studies/"], a[href*="contact.html"]').forEach((a) => {
        const href = a.getAttribute("href");
        if (href.includes("tiers/")) a.setAttribute("href", "#tiers");
        else if (href.includes("case-studies/")) a.setAttribute("href", "#cases");
        else if (href.includes("contact.html")) a.setAttribute("href", "#contact");
      });
    }
  }, [t]);

  // Edit mode protocol
  React.useEffect(() => {
    const onMsg = (e) => {
      if (!e.data) return;
      if (e.data.type === "__activate_edit_mode") setOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    setAvailable(true);
    return () => window.removeEventListener("message", onMsg);
  }, []);

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

  const close = () => {
    setOpen(false);
    window.parent.postMessage({ type: "__edit_mode_dismissed" }, "*");
  };

  if (!open) return null;

  return (
    <div className="tw-panel">
      <div className="tw-head">
        <div>
          <div className="tw-title">Tweaks</div>
          <div className="tw-sub">Try variations live</div>
        </div>
        <button className="tw-close" onClick={close} aria-label="Close">×</button>
      </div>

      <div className="tw-section">
        <div className="tw-label">Navigation</div>
        <div className="tw-radio">
          {[
            { v: "multi", l: "Multi-page", s: "Tiers, cases, contact as separate pages" },
            { v: "single", l: "Single page", s: "Everything on this scroll" },
          ].map((o) => (
            <button key={o.v} className={"tw-radio-opt" + (t.navMode === o.v ? " on" : "")} onClick={() => update("navMode", o.v)}>
              <div className="tw-radio-l">{o.l}</div>
              <div className="tw-radio-s">{o.s}</div>
            </button>
          ))}
        </div>
      </div>

      <div className="tw-section">
        <div className="tw-label">Accent palette</div>
        <div className="tw-swatches">
          {[
            { v: "green-dominant", colors: ["#0e7a3d", "#5bba42", "#f39c20"] },
            { v: "navy-dominant", colors: ["#1b3f73", "#3d77c4", "#f39c20"] },
            { v: "orange-dominant", colors: ["#c66a14", "#f39c20", "#fbd28a"] },
          ].map((s) => (
            <button key={s.v} className={"tw-swatch" + (t.accentTone === s.v ? " on" : "")} onClick={() => update("accentTone", s.v)}>
              <div className="tw-swatch-dots">
                {s.colors.map((c, i) => <span key={i} style={{ background: c }} />)}
              </div>
              <div className="tw-swatch-l">{s.v.replace("-dominant", "")}</div>
            </button>
          ))}
        </div>
      </div>

      <div className="tw-section">
        <div className="tw-label">Hero floating chips</div>
        <div className="tw-toggle-row">
          <span>{t.heroChips ? "Showing" : "Hidden"}</span>
          <button className={"tw-toggle" + (t.heroChips ? " on" : "")} onClick={() => update("heroChips", !t.heroChips)}>
            <span className="tw-toggle-knob" />
          </button>
        </div>
      </div>

      <div className="tw-section">
        <div className="tw-label">Hero CTA copy</div>
        <input
          className="tw-input"
          value={t.ctaCopy}
          onChange={(e) => update("ctaCopy", e.target.value)}
        />
        <div className="tw-help">Try: "Take the 30-sec quiz", "See our work", "Let's chat"</div>
      </div>

      <div className="tw-section">
        <div className="tw-label">Density</div>
        <div className="tw-radio compact">
          {["compact", "comfortable", "spacious"].map((o) => (
            <button key={o} className={"tw-radio-opt" + (t.density === o ? " on" : "")} onClick={() => update("density", o)}>
              <div className="tw-radio-l">{o}</div>
            </button>
          ))}
        </div>
      </div>

      <div className="tw-foot">Tweaks save automatically.</div>
    </div>
  );
}

/* styles for the panel inline */
const tweakStyleEl = document.createElement("style");
tweakStyleEl.textContent = `
  .tw-panel {
    position: fixed;
    right: 20px;
    bottom: 20px;
    width: 340px;
    max-height: 80vh;
    overflow-y: auto;
    background: white;
    border: 1px solid var(--line-strong);
    border-radius: 18px;
    box-shadow: 0 24px 60px rgba(11,31,58,0.2);
    z-index: 1000;
    padding: 22px;
    font-family: var(--font-body);
    font-size: 14px;
    color: var(--ink);
  }
  .tw-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 18px; padding-bottom: 16px; border-bottom: 1px solid var(--line); }
  .tw-title { font-family: var(--font-display); font-size: 20px; font-weight: 600; }
  .tw-sub { font-size: 12px; color: var(--ink-3); margin-top: 2px; }
  .tw-close { width: 28px; height: 28px; border-radius: 50%; background: var(--paper-2); font-size: 20px; line-height: 1; color: var(--ink-3); }
  .tw-close:hover { background: var(--paper-3); color: var(--ink); }
  .tw-section { margin-bottom: 22px; }
  .tw-label { font-family: var(--font-mono); font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-3); margin-bottom: 10px; }
  .tw-radio { display: flex; flex-direction: column; gap: 6px; }
  .tw-radio.compact { flex-direction: row; }
  .tw-radio.compact .tw-radio-opt { text-align: center; padding: 8px 10px; flex: 1; }
  .tw-radio-opt { text-align: left; padding: 10px 14px; background: var(--paper); border: 1.5px solid var(--line); border-radius: 10px; transition: border-color 0.2s; }
  .tw-radio-opt:hover { border-color: var(--line-strong); }
  .tw-radio-opt.on { border-color: var(--green-deep); background: rgba(91,186,66,0.06); }
  .tw-radio-l { font-weight: 600; font-size: 13px; text-transform: capitalize; }
  .tw-radio-s { font-size: 11px; color: var(--ink-3); margin-top: 2px; }
  .tw-swatches { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
  .tw-swatch { padding: 10px; border: 1.5px solid var(--line); border-radius: 10px; background: var(--paper); transition: border-color 0.2s; }
  .tw-swatch:hover { border-color: var(--line-strong); }
  .tw-swatch.on { border-color: var(--green-deep); background: rgba(91,186,66,0.06); }
  .tw-swatch-dots { display: flex; gap: 4px; justify-content: center; margin-bottom: 6px; }
  .tw-swatch-dots span { width: 14px; height: 14px; border-radius: 50%; display: inline-block; }
  .tw-swatch-l { font-size: 10px; color: var(--ink-3); text-align: center; text-transform: capitalize; }
  .tw-toggle-row { display: flex; justify-content: space-between; align-items: center; }
  .tw-toggle { width: 40px; height: 22px; border-radius: 12px; background: var(--line-strong); position: relative; transition: background 0.2s; }
  .tw-toggle.on { background: var(--green-deep); }
  .tw-toggle-knob { position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: white; transition: transform 0.2s; }
  .tw-toggle.on .tw-toggle-knob { transform: translateX(18px); }
  .tw-input { width: 100%; padding: 10px 12px; font-family: inherit; font-size: 13px; background: var(--paper); border: 1.5px solid var(--line); border-radius: 10px; outline: none; }
  .tw-input:focus { border-color: var(--green-deep); background: white; }
  .tw-help { font-size: 11px; color: var(--ink-3); margin-top: 6px; }
  .tw-foot { font-size: 11px; color: var(--ink-3); text-align: center; padding-top: 12px; border-top: 1px solid var(--line); }

  body[data-density="compact"] section { padding-top: 80px !important; padding-bottom: 80px !important; }
  body[data-density="spacious"] section.hero, body[data-density="spacious"] section.journey,
  body[data-density="spacious"] section.industries, body[data-density="spacious"] section.cases,
  body[data-density="spacious"] section.process, body[data-density="spacious"] section.proof-band,
  body[data-density="spacious"] section.contact-teaser { padding-top: 160px !important; padding-bottom: 160px !important; }
`;
document.head.appendChild(tweakStyleEl);

window.TweaksPanel = TweaksPanel;
