// settings.tsx — BYOK + UI settings modal

const { useState: setUseState } = (window as any).React;

function SettingsModal({ onClose, settings, onSave, providerCfg, onProviderSave, onClearKey, onClearAll, t }: any) {
  const [draft, setDraft] = setUseState({ ...settings });
  const [provider, setProvider] = setUseState({ ...providerCfg });
  const [showKey, setShowKey] = setUseState(false);

  const LLM = (window as any).LLM;
  const modelOptions = LLM.options[provider.provider] || [];

  return (
    <div className="jc-modal-overlay">
      <div className="jc-modal" style={{ maxWidth: 640 }}>
        <div className="jc-modal-header">
          <div className="jc-modal-title">⚙ Settings · BYOK key management</div>
          <button className="jc-close-btn" onClick={onClose}>×</button>
        </div>
        <div className="jc-modal-body">
          <h3 style={{ fontSize: 13, marginTop: 0 }}>API key (Bring Your Own)</h3>
          <p className="jc-small jc-muted" style={{ margin: '4px 0 12px' }}>
            Your key is sent <strong>directly</strong> from your browser to the provider. It never touches a server controlled by us. By design — pursuant to Article 17 GDPR (right to erasure) — you may delete it at any time.
          </p>

          <label className="jc-small" style={{ display: 'block', marginBottom: 4, fontWeight: 600 }}>Provider</label>
          <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
            {(['openai', 'anthropic', 'gemini'] as const).map((p) => (
              <button
                key={p}
                className={`jc-btn ${provider.provider === p ? 'primary' : ''}`}
                onClick={() => setProvider({ ...provider, provider: p, model: LLM.defaults[p] })}
                style={{ flex: 1 }}
              >
                {p === 'openai' ? 'OpenAI' : p === 'anthropic' ? 'Anthropic' : 'Google Gemini'}
              </button>
            ))}
          </div>

          <label className="jc-small" style={{ display: 'block', marginBottom: 4, fontWeight: 600 }}>Model</label>
          <select
            value={provider.model}
            onChange={(e: any) => setProvider({ ...provider, model: e.target.value })}
            style={{ width: '100%', padding: '6px 8px', border: '1px solid var(--rule)', borderRadius: 4, marginBottom: 12, fontSize: 12 }}
          >
            {modelOptions.map((m: string) => <option key={m} value={m}>{m}</option>)}
          </select>

          <label className="jc-small" style={{ display: 'block', marginBottom: 4, fontWeight: 600 }}>API key</label>
          <div style={{ display: 'flex', gap: 6, marginBottom: 4 }}>
            <input
              type={showKey ? 'text' : 'password'}
              value={provider.apiKey}
              onChange={(e: any) => setProvider({ ...provider, apiKey: e.target.value })}
              placeholder={
                provider.provider === 'openai' ? 'sk-...' :
                provider.provider === 'anthropic' ? 'sk-ant-...' : 'AIza...'
              }
              style={{ flex: 1, padding: '6px 8px', border: '1px solid var(--rule)', borderRadius: 4, fontFamily: 'monospace', fontSize: 12 }}
              autoComplete="off"
              spellCheck={false}
            />
            <button className="jc-btn" onClick={() => setShowKey(!showKey)}>{showKey ? 'Hide' : 'Show'}</button>
          </div>
          <p className="jc-small jc-muted" style={{ margin: '4px 0 14px' }}>
            Get keys: <a href="https://platform.openai.com/api-keys" target="_blank" rel="noreferrer">OpenAI</a> ·
            {' '}<a href="https://console.anthropic.com/settings/keys" target="_blank" rel="noreferrer">Anthropic</a> ·
            {' '}<a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noreferrer">Google AI Studio</a>
          </p>

          <hr className="jc-hr"/>

          <h3 style={{ fontSize: 13 }}>Storage of your key</h3>
          <div style={{ display: 'flex', gap: 6, marginBottom: 8 }}>
            <button
              className={`jc-btn ${draft.storage === 'local' ? 'primary' : ''}`}
              onClick={() => setDraft({ ...draft, storage: 'local' })}
              style={{ flex: 1 }}
            >
              localStorage <span className="jc-small">(persists across sessions)</span>
            </button>
            <button
              className={`jc-btn ${draft.storage === 'session' ? 'primary' : ''}`}
              onClick={() => setDraft({ ...draft, storage: 'session' })}
              style={{ flex: 1 }}
            >
              sessionStorage <span className="jc-small">(cleared on tab close)</span>
            </button>
          </div>

          <hr className="jc-hr"/>

          <h3 style={{ fontSize: 13 }}>Citizenship declaration</h3>
          <p className="jc-small jc-muted" style={{ margin: '4px 0 8px' }}>
            Declared pursuant to Recommendation (EO) 2024/0008. Service quality may differ.
          </p>
          <select
            value={draft.citizenship}
            onChange={(e: any) => setDraft({ ...draft, citizenship: e.target.value })}
            style={{ width: '100%', padding: '6px 8px', border: '1px solid var(--rule)', borderRadius: 4, marginBottom: 12, fontSize: 12 }}
          >
            <optgroup label="EO / EU member states">
              {(window as any).Util.COUNTRIES_EO.map((c: any) => <option key={c.code} value={c.code}>{c.name}</option>)}
            </optgroup>
            <optgroup label="Third countries">
              {(window as any).Util.COUNTRIES_OTHER.map((c: any) => <option key={c.code} value={c.code}>{c.name}</option>)}
            </optgroup>
          </select>

          <h3 style={{ fontSize: 13 }}>Language</h3>
          <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
            {(['en', 'fr', 'de', 'it'] as const).map((l) => (
              <button
                key={l}
                className={`jc-btn ${draft.language === l ? 'primary' : ''}`}
                onClick={() => setDraft({ ...draft, language: l })}
                style={{ flex: 1 }}
              >
                {l.toUpperCase()}
              </button>
            ))}
          </div>

          <h3 style={{ fontSize: 13 }}>Satire dial — bureaucracy intensity</h3>
          <input
            type="range" min={0} max={100} step={5}
            value={draft.satireDial}
            onChange={(e: any) => setDraft({ ...draft, satireDial: +e.target.value })}
            style={{ width: '100%' }}
          />
          <div className="jc-small jc-muted" style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span>Subtle</span>
            <span>{draft.satireDial}/100</span>
            <span>Maximum</span>
          </div>

          <hr className="jc-hr"/>

          <h3 style={{ fontSize: 13, color: 'var(--eo-red)' }}>Forget my key (Art. 17 GDPR)</h3>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="jc-btn" onClick={() => { onClearKey(); setProvider({ ...provider, apiKey: '' }); }}>
              Forget API key only
            </button>
            <button className="jc-btn danger" onClick={onClearAll}>
              Erase ALL local data
            </button>
          </div>
        </div>
        <div className="jc-modal-footer">
          <button className="jc-btn" onClick={onClose}>Cancel</button>
          <button className="jc-btn primary" onClick={() => { onProviderSave(provider); onSave(draft); onClose(); }}>
            Save
          </button>
        </div>
      </div>
    </div>
  );
}

(window as any).Settings = { SettingsModal };
