// SettingsModal — per-user settings stored on the Supabase user_data row.
// For now: just the Anthropic API key (separate api_key column, doesn't
// touch the chapters/quizzes blob). Reuses the global <Modal/> from
// ChapterLibrary.jsx and the LexStoreNew loadApiKey/saveApiKey helpers
// from cloudStore.js.

const { useState: useSettingsState } = React;

function SettingsModal({ onClose }) {
  const t = window.LexTokens;
  const initialKey = (window.LexStoreNew.loadApiKey?.() || '');
  const [key,     setKey]     = useSettingsState(initialKey);
  const [showKey, setShowKey] = useSettingsState(false);
  const [saved,   setSaved]   = useSettingsState(false);

  const trimmed = key.trim();
  const dirty   = trimmed !== initialKey;
  const looksValid = !trimmed || /^sk-ant-/.test(trimmed);

  function onSave() {
    window.LexStoreNew.saveApiKey(trimmed);
    setSaved(true);
    setTimeout(() => setSaved(false), 1800);
  }

  return (
    <Modal title="Settings" onClose={onClose}>
      <div style={smS.section}>
        <div style={smS.label}>Anthropic API key</div>
        <div style={smS.helper}>
          Used to generate quiz questions from your chapter text. Get one from{' '}
          <a
            href="https://console.anthropic.com/settings/keys"
            target="_blank"
            rel="noopener noreferrer"
            style={smS.link}
          >console.anthropic.com</a>. Stored on your LexBible account and synced
          across devices — never sent anywhere except Anthropic.
        </div>

        <div style={smS.row}>
          <input
            type={showKey ? 'text' : 'password'}
            value={key}
            onChange={e => setKey(e.target.value)}
            placeholder="sk-ant-…"
            spellCheck={false}
            autoComplete="off"
            style={smS.input}
          />
          <button
            type="button"
            onClick={() => setShowKey(s => !s)}
            style={smS.ghost}
          >{showKey ? 'Hide' : 'Show'}</button>
        </div>

        {!looksValid && (
          <div style={smS.warn}>That doesn't look like an Anthropic key (should start with <code>sk-ant-</code>).</div>
        )}
        {!initialKey && !trimmed && (
          <div style={smS.warn}>No key set — quiz generation will fail until you add one.</div>
        )}

        <div style={smS.actions}>
          <button
            onClick={onSave}
            disabled={!dirty}
            style={{ ...smS.primary, ...(!dirty ? smS.primaryDisabled : {}) }}
          >{saved ? 'Saved ✓' : (initialKey ? 'Update' : 'Save')}</button>
          <button onClick={onClose} style={smS.ghost}>Close</button>
        </div>
      </div>
    </Modal>
  );
}

const _t = window.LexTokens;
const smS = {
  section: { padding: '6px 2px 2px' },
  label:   { fontSize: 12.5, fontWeight: 700, color: _t.forest, letterSpacing: '1.6px', textTransform: 'uppercase', marginBottom: 8 },
  helper:  { fontSize: 13.5, color: _t.muted, lineHeight: 1.55, marginBottom: 14 },
  link:    { color: _t.forest, textDecoration: 'underline' },
  row:     { display: 'flex', gap: 8, alignItems: 'stretch', marginBottom: 8 },
  input:   {
    flex: 1, padding: '10px 12px', fontSize: 13, fontFamily: 'ui-monospace, Menlo, Consolas, monospace',
    border: `1px solid ${_t.rule}`, borderRadius: 6, background: '#FFF', color: _t.ink,
  },
  ghost:   {
    padding: '8px 12px', fontSize: 12.5, fontWeight: 500, fontFamily: 'inherit',
    background: 'none', color: _t.muted, border: `1px solid ${_t.rule}`,
    borderRadius: 6, cursor: 'pointer',
  },
  warn:    { fontSize: 12.5, color: _t.crimson || '#9B2335', marginTop: 6, marginBottom: 6 },
  actions: { display: 'flex', gap: 10, marginTop: 18 },
  primary: {
    padding: '9px 16px', fontSize: 13.5, fontWeight: 600, fontFamily: 'inherit',
    background: _t.forest, color: '#FFF', border: 'none', borderRadius: 6, cursor: 'pointer',
  },
  primaryDisabled: { opacity: 0.5, cursor: 'not-allowed' },
};

window.SettingsModal = SettingsModal;
