/* ==========================================================================
   Tweaks.jsx | Developer-only preview panel
   A small, low-contrast "Tweaks" pill in the bottom corner. Changes are
   previews only: nothing is saved, so every page load starts from the
   official identity. Hide it for production with MC_CONFIG.showTweaks.
   ========================================================================== */

const MC_ACCENT_SETS = [
  { id: 'official', name: 'Official', note: 'Default', swatches: ['#9ca8ef', '#ff6622', '#2e896d'] },
  { id: 'greenhouse', name: 'Greenhouse', note: 'Green lead', swatches: ['#2e896d', '#ff6622', '#9ca8ef'] },
  { id: 'citrus', name: 'Citrus', note: 'Orange lead', swatches: ['#ff6622', '#9ca8ef', '#2e896d'] },
  { id: 'midnight', name: 'Midnight', note: 'Black lead', swatches: ['#1e1e1e', '#ff6622', '#9ca8ef'] },
  { id: 'moonlit', name: 'Moonlit', note: 'Purple actions', swatches: ['#1e1e1e', '#9ca8ef', '#2e896d'] },
];
const MC_DECO_LEVELS = [
  { id: 'subtle', label: 'Subtle' },
  { id: 'standard', label: 'Standard' },
  { id: 'bold', label: 'Bold' },
];

function MCTweaks() {
  const [twOpen, setTwOpen] = React.useState(false);
  const [twAccent, setTwAccent] = React.useState('official');
  const [twTheme, setTwTheme] = React.useState('light');
  const [twMotion, setTwMotion] = React.useState(true);
  const [twDeco, setTwDeco] = React.useState(1);
  const twToggleRef = React.useRef(null);

  React.useEffect(() => {
    const root = document.documentElement;
    if (twAccent === 'official') root.removeAttribute('data-accent');
    else root.setAttribute('data-accent', twAccent);
    if (twTheme === 'light') root.removeAttribute('data-theme');
    else root.setAttribute('data-theme', twTheme);
    const level = MC_DECO_LEVELS[twDeco].id;
    if (level === 'standard') root.removeAttribute('data-deco');
    else root.setAttribute('data-deco', level);
    root.classList.toggle('mc-motion-off', !twMotion);
  }, [twAccent, twTheme, twMotion, twDeco]);

  React.useEffect(() => {
    if (!twOpen) return undefined;
    const handleKey = (event) => {
      if (event.key === 'Escape') {
        setTwOpen(false);
        if (twToggleRef.current) twToggleRef.current.focus();
      }
    };
    document.addEventListener('keydown', handleKey);
    return () => document.removeEventListener('keydown', handleKey);
  }, [twOpen]);

  const reset = () => {
    setTwAccent('official');
    setTwTheme('light');
    setTwMotion(true);
    setTwDeco(1);
  };

  const photoKeys = Object.keys(MC_ASSETS.photos);
  const photosAdded = photoKeys.filter((key) => MC_ASSETS.photos[key]).length;
  const assetRows = [
    { label: 'Logo', ok: Boolean(MC_ASSETS.logo) },
    { label: 'Dusty artwork', ok: Boolean(MC_ASSETS.dusty) },
    { label: `Photos (${photosAdded}/${photoKeys.length})`, ok: photosAdded === photoKeys.length },
    { label: 'Form endpoint', ok: Boolean(MC_CONFIG.formEndpoint) },
  ];
  const decoLabel = MC_DECO_LEVELS[twDeco].label;

  return (
    <div className="mc-tweaks">
      <div
        className="mc-tweaks__panel mc-on-base"
        id="mc-tweaks-panel"
        role="dialog"
        aria-labelledby="mc-tweaks-title"
        hidden={!twOpen}
      >
        <div className="mc-tweaks__head">
          <p className="mc-tweaks__title" id="mc-tweaks-title">
            Tweaks
          </p>
          <span className="mc-tweaks__badge">Developer preview</span>
        </div>
        <p className="mc-tweaks__intro">Previews only. Reloading always returns to the official identity.</p>

        <fieldset className="mc-tweaks__group">
          <legend>Accent combination</legend>
          <div className="mc-tweaks__accents">
            {MC_ACCENT_SETS.map((set) => (
              <label key={set.id} className={`mc-tweaks__accent${twAccent === set.id ? ' is-checked' : ''}`}>
                <input
                  type="radio"
                  name="mc-tw-accent"
                  value={set.id}
                  checked={twAccent === set.id}
                  onChange={() => setTwAccent(set.id)}
                />
                <span className="mc-tweaks__sw" aria-hidden="true">
                  {set.swatches.map((colour) => (
                    <i key={colour} style={{ background: colour }} />
                  ))}
                </span>
                <span className="mc-tweaks__aname">{set.name}</span>
                <span className="mc-tweaks__anote">{set.note}</span>
              </label>
            ))}
          </div>
        </fieldset>

        <fieldset className="mc-tweaks__group">
          <legend>Preview mode</legend>
          <div className="mc-tweaks__seg">
            {['light', 'dark'].map((theme) => (
              <label key={theme} className={twTheme === theme ? 'is-checked' : ''}>
                <input
                  type="radio"
                  name="mc-tw-theme"
                  value={theme}
                  checked={twTheme === theme}
                  onChange={() => setTwTheme(theme)}
                />
                <span>{theme === 'light' ? 'Light' : 'Dark'}</span>
              </label>
            ))}
          </div>
        </fieldset>

        <div className="mc-tweaks__group">
          <label className="mc-tweaks__switch">
            <span>Decorative animations</span>
            <input type="checkbox" checked={twMotion} onChange={(event) => setTwMotion(event.target.checked)} />
          </label>
        </div>

        <div className="mc-tweaks__group">
          <label className="mc-tweaks__label" htmlFor="mc-tw-deco">
            Decoration intensity: {decoLabel}
          </label>
          <input
            id="mc-tw-deco"
            className="mc-tweaks__range"
            type="range"
            min="0"
            max="2"
            step="1"
            value={twDeco}
            aria-valuetext={decoLabel}
            onChange={(event) => setTwDeco(Number(event.target.value))}
          />
          <div className="mc-tweaks__scale" aria-hidden="true">
            {MC_DECO_LEVELS.map((level) => (
              <span key={level.id}>{level.label}</span>
            ))}
          </div>
        </div>

        <div className="mc-tweaks__group mc-tweaks__assets">
          <p className="mc-tweaks__label">Official assets and setup</p>
          <ul role="list">
            {assetRows.map((row) => (
              <li key={row.label}>
                <span>{row.label}</span>
                <span className={`mc-tweaks__state${row.ok ? '' : ' is-missing'}`}>{row.ok ? 'Added' : 'Missing'}</span>
              </li>
            ))}
          </ul>
        </div>

        <button type="button" className="mc-tweaks__reset" onClick={reset}>
          Reset to official
        </button>
      </div>

      <button
        ref={twToggleRef}
        type="button"
        className="mc-tweaks__toggle"
        aria-expanded={twOpen}
        aria-controls="mc-tweaks-panel"
        onClick={() => setTwOpen((open) => !open)}
      >
        <MCIcon name="sparkle" />
        Tweaks
      </button>
    </div>
  );
}

Object.assign(window, { MCTweaks, MC_ACCENT_SETS, MC_DECO_LEVELS });
