/* global React */
// Tweaks panel: dev-only floating UI for live-editing prototype state.
// Persists to localStorage (per-pathname). EDITMODE markers are handled
// by external tooling, not by this runtime.

const STORAGE_KEY = "tweaks:" + window.location.pathname;

// =============================================================
// Hook
// =============================================================
function useTweaks(defaults) {
  const [state, setState] = React.useState(() => {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (raw) return { ...defaults, ...JSON.parse(raw) };
    } catch (e) { /* ignore */ }
    return { ...defaults };
  });
  const setTweak = (key, value) => {
    setState(prev => {
      const next = { ...prev, [key]: value };
      try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } catch (e) {}
      return next;
    });
  };
  return [state, setTweak];
}

// =============================================================
// Panel chrome (inline styles -- isolated to this file)
// =============================================================
const PANEL_STYLE = {
  position: "fixed",
  bottom: 20,
  left: 20,
  zIndex: 90,
  background: "var(--surface)",
  border: "1px solid var(--line)",
  borderRadius: "var(--radius, 10px)",
  boxShadow: "var(--shadow-toast, 0 4px 12px rgba(0,0,0,0.12))",
  fontFamily: "var(--font-sans)",
  color: "var(--ink)",
  width: 300,
  overflow: "hidden",
};

const HEADER_STYLE = {
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  padding: "8px 12px",
  fontFamily: "var(--font-mono)",
  fontSize: 11,
  textTransform: "uppercase",
  letterSpacing: "0.08em",
  color: "var(--ink-3)",
  cursor: "pointer",
  userSelect: "none",
  borderBottom: "1px solid var(--line)",
  background: "var(--surface-2)",
};

const BODY_STYLE = {
  padding: 12,
  display: "flex",
  flexDirection: "column",
  gap: 10,
  maxHeight: "70vh",
  overflowY: "auto",
};

function TweaksPanel({ children }) {
  const [collapsed, setCollapsed] = React.useState(() => {
    try { return localStorage.getItem(STORAGE_KEY + ":collapsed") !== "0"; }
    catch (e) { return true; }
  });
  const toggle = () => {
    setCollapsed(c => {
      const next = !c;
      try { localStorage.setItem(STORAGE_KEY + ":collapsed", next ? "1" : "0"); } catch (e) {}
      return next;
    });
  };
  const containerStyle = collapsed
    ? { ...PANEL_STYLE, width: 140 }
    : PANEL_STYLE;
  return (
    <div style={containerStyle}>
      <div style={collapsed ? { ...HEADER_STYLE, borderBottom: "0" } : HEADER_STYLE} onClick={toggle}>
        <span>TWEAKS</span>
        <span aria-hidden="true">{collapsed ? "▸" : "▾"}</span>
      </div>
      {!collapsed && <div style={BODY_STYLE}>{children}</div>}
    </div>
  );
}

// =============================================================
// Primitives
// =============================================================
const LABEL_STYLE = {
  fontFamily: "var(--font-mono)",
  fontSize: 10.5,
  textTransform: "uppercase",
  letterSpacing: "0.08em",
  color: "var(--ink-3)",
  marginBottom: 4,
};

const FIELD_STYLE = { display: "flex", flexDirection: "column" };

function TweakSection({ label }) {
  return (
    <div style={{ marginTop: 6, paddingTop: 8, borderTop: "1px solid var(--line)" }}>
      <div style={{
        fontFamily: "var(--font-mono)",
        fontSize: 10.5,
        textTransform: "uppercase",
        letterSpacing: "0.1em",
        color: "var(--ink-2)",
        fontWeight: 600,
      }}>{label}</div>
    </div>
  );
}

function TweakRadio({ label, value, options, onChange }) {
  return (
    <div style={FIELD_STYLE}>
      {label && <div style={LABEL_STYLE}>{label}</div>}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 4, background: "var(--surface-2)", padding: 2, borderRadius: 6 }}>
        {options.map(opt => {
          const active = opt === value;
          return (
            <button
              key={opt}
              onClick={() => onChange(opt)}
              style={{
                flex: "1 1 auto",
                padding: "5px 8px",
                fontSize: 11.5,
                fontFamily: "var(--font-mono)",
                borderRadius: 4,
                border: 0,
                cursor: "pointer",
                background: active ? "var(--purple)" : "transparent",
                color: active ? "var(--ink)" : "var(--ink-2)",
                fontWeight: active ? 600 : 500,
                transition: "background 0.12s, color 0.12s",
                whiteSpace: "nowrap",
              }}
            >
              {opt}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function TweakToggle({ label, value, onChange }) {
  return (
    <div style={{ ...FIELD_STYLE, flexDirection: "row", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
      {label && <div style={{ ...LABEL_STYLE, marginBottom: 0 }}>{label}</div>}
      <button
        onClick={() => onChange(!value)}
        aria-pressed={!!value}
        style={{
          width: 32,
          height: 18,
          borderRadius: 999,
          border: "1px solid var(--line)",
          background: value ? "var(--purple)" : "var(--surface-2)",
          position: "relative",
          cursor: "pointer",
          transition: "background 0.15s",
          padding: 0,
          flexShrink: 0,
        }}
      >
        <span style={{
          position: "absolute",
          top: 1,
          left: value ? 15 : 1,
          width: 14,
          height: 14,
          borderRadius: "50%",
          background: "var(--ink)",
          boxShadow: "0 1px 2px rgba(0,0,0,0.2)",
          transition: "left 0.15s",
        }}/>
      </button>
    </div>
  );
}

function TweakSelect({ label, value, options, onChange }) {
  return (
    <div style={FIELD_STYLE}>
      {label && <div style={LABEL_STYLE}>{label}</div>}
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          padding: "6px 8px",
          border: "1px solid var(--line)",
          borderRadius: 6,
          background: "var(--surface)",
          color: "var(--ink)",
          fontFamily: "var(--font-mono)",
          fontSize: 12,
          cursor: "pointer",
        }}
      >
        {options.map(opt => <option key={opt} value={opt}>{opt}</option>)}
      </select>
    </div>
  );
}

function TweakButton({ label, onClick }) {
  return (
    <button
      onClick={onClick}
      className="btn btn-ghost"
      style={{
        width: "100%",
        justifyContent: "flex-start",
        fontFamily: "var(--font-mono)",
        fontSize: 11.5,
        padding: "6px 10px",
        border: "1px solid var(--line)",
        background: "var(--surface)",
      }}
    >
      {label}
    </button>
  );
}

// =============================================================
// Wire-up: expose on window so main.jsx and views can use them as globals
// =============================================================
Object.assign(window, {
  useTweaks,
  TweaksPanel,
  TweakSection,
  TweakRadio,
  TweakToggle,
  TweakSelect,
  TweakButton,
});
