// TweaksPanel — runtime UI customization controls
const { useState, useCallback, useEffect, useRef } = React;

// useTweaks hook — manages tweak state with persistence
function useTweaks(defaults) {
  const [tweaks, setTweaks] = useState(() => {
    try {
      const saved = localStorage.getItem('aeq-tweaks');
      return saved ? { ...defaults, ...JSON.parse(saved) } : defaults;
    } catch {
      return defaults;
    }
  });

  const setTweak = useCallback((key, value) => {
    setTweaks(prev => {
      const next = { ...prev, [key]: value };
      try {
        localStorage.setItem('aeq-tweaks', JSON.stringify(next));
      } catch {}
      return next;
    });
  }, []);

  return [tweaks, setTweak];
}

// TweaksPanel — collapsible side panel
function TweaksPanel({ title = 'Tweaks', children }) {
  const [open, setOpen] = useState(false);
  const panelRef = useRef(null);

  // Close on escape
  useEffect(() => {
    const handleKey = (e) => {
      if (e.key === 'Escape' && open) setOpen(false);
    };
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [open]);

  // Close on outside click
  useEffect(() => {
    const handleClick = (e) => {
      if (open && panelRef.current && !panelRef.current.contains(e.target)) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [open]);

  return (
    <React.Fragment>
      <button
        className="tweaks-toggle"
        onClick={() => setOpen(!open)}
        aria-label={open ? 'Close tweaks panel' : 'Open tweaks panel'}
        aria-expanded={open}
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="3" />
          <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
        </svg>
      </button>

      <div ref={panelRef} className={`tweaks-panel ${open ? 'tweaks-panel--open' : ''}`}>
        <div className="tweaks-panel__header">
          <h3 className="tweaks-panel__title">{title}</h3>
          <button className="tweaks-panel__close" onClick={() => setOpen(false)} aria-label="Close panel">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="tweaks-panel__body">
          {children}
        </div>
      </div>

      <style>{`
        .tweaks-toggle {
          position: fixed;
          bottom: 24px;
          right: 24px;
          z-index: 1000;
          width: 48px;
          height: 48px;
          border-radius: 50%;
          background: linear-gradient(135deg, var(--cyan) 0%, var(--sky) 100%);
          color: #030712;
          border: none;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 4px 20px rgba(6,182,212,.4), 0 0 40px rgba(6,182,212,.2);
          transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        .tweaks-toggle:hover {
          transform: scale(1.08);
          box-shadow: 0 6px 28px rgba(6,182,212,.5), 0 0 60px rgba(6,182,212,.3);
        }

        .tweaks-panel {
          position: fixed;
          top: 0;
          right: 0;
          bottom: 0;
          width: 320px;
          max-width: 90vw;
          background: var(--bg-elev);
          border-left: 1px solid var(--line);
          z-index: 1001;
          transform: translateX(100%);
          transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          display: flex;
          flex-direction: column;
          box-shadow: -8px 0 40px rgba(0,0,0,.5);
        }
        .tweaks-panel--open {
          transform: translateX(0);
        }

        .tweaks-panel__header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 20px 24px;
          border-bottom: 1px solid var(--line);
        }
        .tweaks-panel__title {
          font-size: 16px;
          font-weight: 600;
          margin: 0;
          color: var(--ink);
        }
        .tweaks-panel__close {
          background: none;
          border: none;
          padding: 4px;
          cursor: pointer;
          color: var(--ink-mute);
          transition: color 0.2s;
        }
        .tweaks-panel__close:hover {
          color: var(--ink);
        }

        .tweaks-panel__body {
          flex: 1;
          overflow-y: auto;
          padding: 24px;
          display: flex;
          flex-direction: column;
          gap: 20px;
        }

        .tweak-section {
          font-size: 11px;
          font-weight: 600;
          text-transform: uppercase;
          letter-spacing: 0.1em;
          color: var(--ink-mute);
          padding-top: 8px;
          border-top: 1px solid var(--line);
        }
        .tweak-section:first-child {
          padding-top: 0;
          border-top: none;
        }

        .tweak-control {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }
        .tweak-control__label {
          font-size: 13px;
          font-weight: 500;
          color: var(--ink-soft);
        }

        .tweak-slider {
          display: flex;
          align-items: center;
          gap: 12px;
        }
        .tweak-slider input[type="range"] {
          flex: 1;
          height: 6px;
          -webkit-appearance: none;
          appearance: none;
          background: var(--line-strong);
          border-radius: 3px;
          outline: none;
        }
        .tweak-slider input[type="range"]::-webkit-slider-thumb {
          -webkit-appearance: none;
          appearance: none;
          width: 16px;
          height: 16px;
          border-radius: 50%;
          background: var(--cyan);
          cursor: pointer;
          box-shadow: 0 2px 8px rgba(6,182,212,.5), 0 0 20px rgba(6,182,212,.3);
        }
        .tweak-slider__value {
          font-family: var(--font-mono);
          font-size: 12px;
          color: var(--ink-mute);
          min-width: 48px;
          text-align: right;
        }

        .tweak-toggle {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        .tweak-toggle__switch {
          position: relative;
          width: 44px;
          height: 24px;
          background: var(--line-strong);
          border-radius: 12px;
          cursor: pointer;
          transition: background 0.2s;
        }
        .tweak-toggle__switch--active {
          background: var(--cyan);
          box-shadow: 0 0 20px rgba(6,182,212,.4);
        }
        .tweak-toggle__switch::after {
          content: '';
          position: absolute;
          top: 2px;
          left: 2px;
          width: 20px;
          height: 20px;
          background: #fff;
          border-radius: 50%;
          transition: transform 0.2s;
          box-shadow: 0 2px 4px rgba(0,0,0,.2);
        }
        .tweak-toggle__switch--active::after {
          transform: translateX(20px);
        }

        .tweak-radio__options {
          display: flex;
          gap: 8px;
          flex-wrap: wrap;
        }
        .tweak-radio__option {
          padding: 8px 14px;
          font-size: 13px;
          font-weight: 500;
          background: var(--bg);
          border: 1px solid var(--line);
          border-radius: 8px;
          cursor: pointer;
          transition: all 0.2s;
          color: var(--ink-soft);
        }
        .tweak-radio__option:hover {
          border-color: var(--line-strong);
        }
        .tweak-radio__option--active {
          background: var(--cyan);
          border-color: var(--cyan);
          color: #030712;
          box-shadow: 0 0 20px rgba(6,182,212,.3);
        }
      `}</style>
    </React.Fragment>
  );
}

// TweakSection — section divider with label
function TweakSection({ label }) {
  return <div className="tweak-section">{label}</div>;
}

// TweakSlider — range slider control
function TweakSlider({ label, value, min = 0, max = 100, step = 1, unit = '', onChange }) {
  return (
    <div className="tweak-control">
      <label className="tweak-control__label">{label}</label>
      <div className="tweak-slider">
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={value}
          onChange={(e) => onChange(Number(e.target.value))}
        />
        <span className="tweak-slider__value">{value}{unit}</span>
      </div>
    </div>
  );
}

// TweakToggle — on/off switch
function TweakToggle({ label, value, onChange }) {
  return (
    <div className="tweak-control tweak-toggle">
      <label className="tweak-control__label">{label}</label>
      <div
        className={`tweak-toggle__switch ${value ? 'tweak-toggle__switch--active' : ''}`}
        onClick={() => onChange(!value)}
        role="switch"
        aria-checked={value}
        tabIndex={0}
        onKeyDown={(e) => e.key === 'Enter' && onChange(!value)}
      />
    </div>
  );
}

// TweakRadio — radio button group
function TweakRadio({ label, value, options, onChange }) {
  return (
    <div className="tweak-control">
      <label className="tweak-control__label">{label}</label>
      <div className="tweak-radio__options">
        {options.map((opt) => (
          <button
            key={opt.value}
            className={`tweak-radio__option ${value === opt.value ? 'tweak-radio__option--active' : ''}`}
            onClick={() => onChange(opt.value)}
          >
            {opt.label}
          </button>
        ))}
      </div>
    </div>
  );
}

// Export to window for global access
window.useTweaks = useTweaks;
window.TweaksPanel = TweaksPanel;
window.TweakSection = TweakSection;
window.TweakSlider = TweakSlider;
window.TweakToggle = TweakToggle;
window.TweakRadio = TweakRadio;
