// FeaturesSection.jsx — toggle feature flags. Writes localStorage('ff.<name>') so
// shared/config/features.js picks them up on reload.

const FeaturesSection = ({ onBanner }) => {
  const defaults = window.FEATURE_DEFAULTS || {};
  const initial = window.FEATURES || {};
  const [state, setState] = useState({ ...initial });

  const set = (key, value) => {
    try {
      localStorage.setItem('ff.' + key, value ? 'true' : 'false');
      setState(prev => ({ ...prev, [key]: value }));
      onBanner({ kind: 'ok', msg: `ff.${key} set to ${value}. Reload site to see it.` });
    } catch (e) {
      onBanner({ kind: 'err', msg: 'localStorage blocked: ' + e.message });
    }
  };

  const clearOverride = (key) => {
    try {
      localStorage.removeItem('ff.' + key);
      setState(prev => ({ ...prev, [key]: defaults[key] }));
      onBanner({ kind: 'ok', msg: `ff.${key} reset to default (${defaults[key]}).` });
    } catch (e) {
      onBanner({ kind: 'err', msg: 'localStorage blocked: ' + e.message });
    }
  };

  const copyDefaults = () => {
    const lines = Object.entries(state).map(([k, v]) => `    ${k}: ${v},`).join('\n');
    const snippet = `const defaults = {\n${lines}\n  };`;
    navigator.clipboard?.writeText(snippet).then(
      () => onBanner({ kind: 'ok', msg: 'Copied. Paste into shared/config/features.js.' }),
      () => onBanner({ kind: 'err', msg: 'Clipboard blocked.' })
    );
  };

  const keys = Object.keys(defaults);

  return (
    <>
      <PageHero eyebrow="Admin · Features" title={<>Feature <span style={{ color: 'var(--wbbq-flame)' }}>Flags.</span></>} subtitle="Toggles are stored per-browser. Use Copy Defaults to persist a flip into source." mascot="robot-cat-fish.svg" />
      <div style={{ marginTop: 28 }}>
        {keys.length === 0 && (
          <div style={{ color: 'var(--fg3)' }}>No flags defined. Add them to <code>shared/config/features.js</code>.</div>
        )}
        {keys.map((key) => {
          const value = !!state[key];
          const defaultVal = !!defaults[key];
          const overridden = value !== defaultVal;
          return (
            <div key={key} style={{
              display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 20, alignItems: 'center',
              padding: '16px 18px', marginBottom: 12,
              background: 'var(--wbbq-ink)', border: '2px solid var(--border)',
            }}>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: 'var(--wbbq-bone)' }}>{key}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)', marginTop: 4 }}>
                  default: <span style={{ color: defaultVal ? 'var(--wbbq-slime)' : 'var(--fg3)' }}>{String(defaultVal)}</span>
                  {overridden && <span style={{ color: 'var(--wbbq-flame)', marginLeft: 8 }}>· OVERRIDDEN</span>}
                </div>
              </div>
              {overridden && (
                <button onClick={() => clearOverride(key)} className="btn" style={{ fontSize: 10, padding: '6px 10px', background: 'transparent', color: 'var(--fg2)', border: '1.5px solid var(--border)', letterSpacing: '0.1em' }}>Reset</button>
              )}
              <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 12, letterSpacing: '0.1em', color: value ? 'var(--wbbq-slime)' : 'var(--fg3)' }}>
                  {value ? 'ON' : 'OFF'}
                </span>
                <input type="checkbox" checked={value} onChange={(e) => set(key, e.target.checked)} style={{ width: 22, height: 22, accentColor: 'var(--wbbq-slime)' }} />
              </label>
            </div>
          );
        })}
        <div style={{ marginTop: 20, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <button onClick={copyDefaults} className="btn btn-ghost" style={{ fontSize: 12 }}>Copy as defaults</button>
          <button onClick={() => location.reload()} className="btn btn-primary" style={{ fontSize: 12 }}>Reload</button>
        </div>
        <p style={{ marginTop: 16, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)' }}>
          Toggles live in <code>localStorage</code> of this browser only. For a permanent flip, Copy Defaults and paste into <code>shared/config/features.js</code>.
        </p>
      </div>
    </>
  );
};
window.FeaturesSection = FeaturesSection;
