/* global React */
const { useState, useEffect, useRef } = React;

// Custom Tweaks panel matching the gilded aesthetic.
// Ownsthe edit-mode protocol with the host.

const TweaksPanel = () => {
  const [open, setOpen] = useState(false);
  const [tweaks, setTweaks] = useState(window.__TWEAK_DEFAULTS);
  const announcedRef = useRef(false);

  // Register listener BEFORE announcing availability
  useEffect(() => {
    const handler = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setOpen(true);
      else if (e.data.type === "__deactivate_edit_mode") setOpen(false);
    };
    window.addEventListener("message", handler);

    if (!announcedRef.current) {
      announcedRef.current = true;
      window.parent.postMessage({type: "__edit_mode_available"}, "*");
    }
    return () => window.removeEventListener("message", handler);
  }, []);

  const update = (key, val) => {
    const next = {...tweaks, [key]: val};
    setTweaks(next);
    // Tell the app
    window.postMessage({type: "__sc_tweak_update", tweaks: next}, "*");
    // Persist to disk
    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 className="tw-head-title">
          <span className="tw-diamond">◆</span>
          <span>Tweaks</span>
        </div>
        <button className="tw-close" onClick={close} aria-label="Close">×</button>
      </div>

      <div className="tw-body">
        <Section label="Hero Variant" />
        <Radio
          value={tweaks.hero}
          options={[
            {v: "logo", label: "Logo"},
            {v: "typo", label: "Typographic"},
            {v: "image", label: "Image-led"}
          ]}
          onChange={(v) => update("hero", v)}
        />

        <Section label="Gold Tone" />
        <Radio
          value={tweaks.goldTone}
          options={[
            {v: "champagne", label: "Champagne", swatch: "#d8c47c"},
            {v: "rich", label: "Rich Gold", swatch: "#d4a64a"},
            {v: "amber", label: "Amber", swatch: "#cc7a1f"}
          ]}
          onChange={(v) => update("goldTone", v)}
        />

        <Section label="Density" />
        <Radio
          value={tweaks.density}
          options={[
            {v: "compact", label: "Compact"},
            {v: "default", label: "Default"},
            {v: "airy", label: "Airy"}
          ]}
          onChange={(v) => update("density", v)}
        />
      </div>

      <style>{TW_CSS}</style>
    </div>
  );
};

const Section = ({label}) => (
  <div className="tw-section">
    <span>{label}</span>
    <span className="tw-sec-line"/>
  </div>
);

const Radio = ({value, options, onChange}) => (
  <div className="tw-radio">
    {options.map(o => (
      <button
        key={o.v}
        className={"tw-opt" + (value === o.v ? " is-on" : "")}
        onClick={() => onChange(o.v)}
      >
        {o.swatch && <span className="tw-swatch" style={{background: o.swatch}}/>}
        <span>{o.label}</span>
      </button>
    ))}
  </div>
);

const TW_CSS = `
  .tw-panel {
    position: fixed; right: 20px; bottom: 20px; z-index: 9999;
    width: 280px;
    background: linear-gradient(180deg, rgba(20, 16, 10, 0.96), rgba(10, 8, 6, 0.96));
    border: 1px solid rgba(212, 166, 74, 0.5);
    color: #f5ecd7;
    font-family: 'Inter', system-ui, sans-serif;
    backdrop-filter: blur(20px);
    box-shadow: 0 20px 60px rgba(0,0,0,0.6), 0 0 40px rgba(241, 210, 122, 0.08);
  }
  .tw-panel::before, .tw-panel::after {
    content: ""; position: absolute;
    width: 14px; height: 14px;
    border: 1px solid #d4a64a;
    pointer-events: none;
  }
  .tw-panel::before { top: -1px; left: -1px; border-right: 0; border-bottom: 0; }
  .tw-panel::after  { bottom: -1px; right: -1px; border-left: 0; border-top: 0; }

  .tw-head {
    display: flex; align-items: center; justify-content: space-between;
    padding: 14px 16px;
    border-bottom: 1px solid rgba(212, 166, 74, 0.22);
  }
  .tw-head-title {
    display: flex; align-items: center; gap: 10px;
    font-family: 'Cinzel', serif;
    font-size: 13px;
    letter-spacing: 0.24em;
    text-transform: uppercase;
    color: #f1d27a;
  }
  .tw-diamond { color: #d4a64a; font-size: 9px; }
  .tw-close {
    background: transparent; border: 1px solid rgba(212, 166, 74, 0.3);
    color: #d4a64a;
    width: 24px; height: 24px;
    cursor: pointer;
    font-size: 16px; line-height: 1;
    transition: all 0.2s;
  }
  .tw-close:hover { background: #d4a64a; color: #0a0806; }

  .tw-body { padding: 6px 16px 18px; }

  .tw-section {
    display: flex; align-items: center; gap: 12px;
    margin: 18px 0 10px;
    font-size: 9px;
    letter-spacing: 0.3em;
    text-transform: uppercase;
    color: #a89878;
  }
  .tw-sec-line {
    flex: 1; height: 1px;
    background: linear-gradient(90deg, rgba(212,166,74,0.3), transparent);
  }

  .tw-radio { display: flex; flex-direction: column; gap: 4px; }
  .tw-opt {
    display: flex; align-items: center; gap: 10px;
    background: transparent;
    border: 1px solid rgba(212, 166, 74, 0.18);
    color: #f5ecd7;
    padding: 10px 12px;
    cursor: pointer;
    font-family: 'Cormorant Garamond', serif;
    font-size: 14px;
    letter-spacing: 0.06em;
    text-align: left;
    transition: all 0.2s;
  }
  .tw-opt:hover {
    border-color: rgba(212, 166, 74, 0.5);
    background: rgba(212, 166, 74, 0.04);
  }
  .tw-opt.is-on {
    border-color: #d4a64a;
    background: linear-gradient(180deg, rgba(212,166,74,0.18), rgba(212,166,74,0.06));
    color: #f1d27a;
  }
  .tw-swatch {
    width: 14px; height: 14px;
    border: 1px solid rgba(255,255,255,0.2);
    flex: none;
  }
`;

const tweaksRoot = document.getElementById("tweaks-root");
if (tweaksRoot) {
  ReactDOM.createRoot(tweaksRoot).render(<TweaksPanel />);
}
