// aerOS Superadmin — Platform Settings: shared AI (Anthropic) API key.
// One key, used by every tenant whose plan includes the AI feature.
function SaSettings({ t }) {
  const { useState, useEffect } = React;
  const toast = useToast();
  const [data, setData] = useState({ anthropic_api_key_set: false, anthropic_api_key_masked: null, anthropic_model: '', ai_plans: [] });
  const [key, setKey] = useState('');
  const [model, setModel] = useState('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [result, setResult] = useState(null);  // {ok, message}
  // SMTP
  const [smtp, setSmtp] = useState({ host: '', port: '587', user: '', password: '', from: '', tls: true });
  const [smtpTo, setSmtpTo] = useState('');
  const [smtpTesting, setSmtpTesting] = useState(false);
  const [smtpResult, setSmtpResult] = useState(null);
  const sset = (k, v) => setSmtp(s => ({ ...s, [k]: v }));

  const load = async () => {
    setLoading(true);
    try {
      const d = await window.SA_API.getSettings(); setData(d); setModel(d.anthropic_model || '');
      setSmtp({ host: d.smtp_host || '', port: d.smtp_port || '587', user: d.smtp_user || '', password: '', from: d.smtp_from || '', tls: d.smtp_tls !== false });
    } catch (e) {}
    setLoading(false);
  };
  useEffect(() => { load(); }, []);

  const save = async () => {
    setSaving(true);
    try {
      await window.SA_API.setSettings({
        anthropic_api_key: key || null, anthropic_model: model || null,
        smtp_host: smtp.host, smtp_port: String(smtp.port || ''), smtp_user: smtp.user,
        smtp_password: smtp.password || null, smtp_from: smtp.from, smtp_tls: !!smtp.tls,
      });
      setKey(''); setSmtp(s => ({ ...s, password: '' })); await load(); toast.ok('Ayarlar kaydedildi', 'Platform ayarları güncellendi');
    } catch (e) { toast.error(e.message || 'Hata'); }
    setSaving(false);
  };
  const testSmtp = async () => {
    setSmtpTesting(true); setSmtpResult(null);
    try { setSmtpResult(await window.SA_API.testSmtp(smtpTo || null)); }
    catch (e) { setSmtpResult({ ok: false, message: e.message || 'Hata' }); }
    setSmtpTesting(false);
  };
  const test = async () => {
    setTesting(true); setResult(null);
    try { const r = await window.SA_API.testApiKey(key || null, model || null); setResult(r); }
    catch (e) { setResult({ ok: false, message: e.message || 'Hata' }); }
    setTesting(false);
  };

  const placeholder = data.anthropic_api_key_set ? (data.anthropic_api_key_masked || 'Kayıtlı anahtar var') : 'sk-ant-...';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 720 }}>
      <Card title="Yapay Zeka API Anahtarı" subtitle="Tüm tenant'ların paylaştığı Anthropic anahtarı" icon={Icon.sparkles || Icon.creditcard}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 'var(--r-sm)', background: data.anthropic_api_key_set ? 'var(--ok-soft, #ecfdf5)' : 'var(--bg-2)', border: '1px solid var(--border)' }}>
            <span style={{ width: 9, height: 9, borderRadius: 5, background: data.anthropic_api_key_set ? 'var(--ok)' : 'var(--fg-3)' }} />
            <span style={{ fontSize: 13, color: 'var(--fg-2)' }}>{data.anthropic_api_key_set ? `Anahtar kayıtlı: ${data.anthropic_api_key_masked}` : 'Henüz anahtar girilmedi'}</span>
          </div>

          <Field label="Anthropic API Key">
            <Input type="password" value={key} onChange={setKey} placeholder={placeholder} />
          </Field>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: -8 }}>Boş bırakırsanız mevcut anahtar korunur. console.anthropic.com → API Keys.</div>

          <Field label="Model">
            <Select value={model || 'claude-haiku-4-5'} onChange={setModel} options={[
              { value: 'claude-haiku-4-5', label: 'Claude Haiku 4.5 (hızlı, ucuz)' },
              { value: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6 (dengeli)' },
              { value: 'claude-opus-4-8', label: 'Claude Opus 4.8 (en güçlü)' },
            ]} />
          </Field>

          {result && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px', borderRadius: 'var(--r-sm)', background: result.ok ? 'var(--ok-soft, #ecfdf5)' : 'var(--danger-soft, #fef2f2)', border: `1px solid ${result.ok ? 'var(--ok)' : 'var(--danger)'}` }}>
              <span style={{ color: result.ok ? 'var(--ok)' : 'var(--danger)', display: 'flex' }}>{(result.ok ? (Icon.checkCircle || Icon.check) : (Icon.alert || Icon.x))({ size: 17 })}</span>
              <span style={{ fontSize: 13, color: 'var(--fg-1)' }}>{result.message}</span>
            </div>
          )}

          <div style={{ display: 'flex', gap: 10, paddingTop: 4 }}>
            <Button variant="secondary" icon={Icon.zap || Icon.bolt || Icon.check} onClick={test} disabled={testing || (!key && !data.anthropic_api_key_set)}>{testing ? 'Test ediliyor…' : 'Bağlantıyı Test Et'}</Button>
            <Button variant="primary" brand icon={Icon.save} onClick={save} disabled={saving}>{saving ? 'Kaydediliyor…' : 'Kaydet'}</Button>
          </div>
        </div>
      </Card>

      <Card title="SMTP (E-posta) Ayarları" subtitle="Kullanıcı davet / bildirim e-postaları için" icon={Icon.mail || Icon.creditcard}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 'var(--r-sm)', background: data.smtp_host ? 'var(--ok-soft, #ecfdf5)' : 'var(--bg-2)', border: '1px solid var(--border)' }}>
            <span style={{ width: 9, height: 9, borderRadius: 5, background: data.smtp_host ? 'var(--ok)' : 'var(--fg-3)' }} />
            <span style={{ fontSize: 13, color: 'var(--fg-2)' }}>{data.smtp_host ? `Yapılandırıldı: ${data.smtp_host}:${data.smtp_port}` : 'SMTP henüz tanımlı değil'}</span>
          </div>
          <Grid cols={2} gap={16}>
            <Field label="Sunucu (host)"><Input value={smtp.host} onChange={v => sset('host', v)} placeholder="smtp.gmail.com" /></Field>
            <Field label="Port"><Input type="number" align="right" value={smtp.port} onChange={v => sset('port', v)} placeholder="587" /></Field>
            <Field label="Kullanıcı"><Input value={smtp.user} onChange={v => sset('user', v)} placeholder="user@domain.com" /></Field>
            <Field label="Parola"><Input type="password" value={smtp.password} onChange={v => sset('password', v)} placeholder={data.smtp_password_set ? '••••••• (kayıtlı)' : ''} /></Field>
            <Field label="Gönderen (from)"><Input value={smtp.from} onChange={v => sset('from', v)} placeholder="aerOS <noreply@domain.com>" /></Field>
            <Field label="TLS"><div style={{ display: 'flex', alignItems: 'center', height: 38 }}><Switch checked={smtp.tls} onChange={v => sset('tls', v)} /></div></Field>
          </Grid>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: -8 }}>İpucu: Port <b>465</b> = SSL, Port <b>587</b> = STARTTLS. Yandex/Gmail için TLS açık olmalı (587'de otomatik uygulanır).</div>
          {smtpResult && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px', borderRadius: 'var(--r-sm)', background: smtpResult.ok ? 'var(--ok-soft, #ecfdf5)' : 'var(--danger-soft, #fef2f2)', border: `1px solid ${smtpResult.ok ? 'var(--ok)' : 'var(--danger)'}` }}>
              <span style={{ color: smtpResult.ok ? 'var(--ok)' : 'var(--danger)', display: 'flex' }}>{(smtpResult.ok ? (Icon.checkCircle || Icon.check) : (Icon.alert || Icon.x))({ size: 17 })}</span>
              <span style={{ fontSize: 13, color: 'var(--fg-1)' }}>{smtpResult.message}</span>
            </div>
          )}
          <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end', flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: 180 }}><Field label="Test e-posta adresi (opsiyonel)"><Input value={smtpTo} onChange={setSmtpTo} placeholder="test@domain.com" /></Field></div>
            <Button variant="secondary" icon={Icon.send || Icon.check} onClick={testSmtp} disabled={smtpTesting || !smtp.host}>{smtpTesting ? 'Test ediliyor…' : 'SMTP Test Et'}</Button>
            <Button variant="primary" brand icon={Icon.save} onClick={save} disabled={saving}>{saving ? '...' : 'Kaydet'}</Button>
          </div>
        </div>
      </Card>

      <Card title="Plan Erişimi" subtitle="AI özelliklerini hangi paketler kullanabilir" icon={Icon.layers}>
        <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.6 }}>
          Bu anahtar platform genelindedir; <b>her tenant</b> AI çeviri ve AI upsell önerileri için bunu kullanır —
          ancak yalnızca paketleri AI'yı içeriyorsa. AI içeren paketler:
          <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
            {(data.ai_plans || []).length
              ? data.ai_plans.map(p => <Badge key={p} tone="brand" size="sm">{p}</Badge>)
              : <span style={{ color: 'var(--fg-3)' }}>Hiçbir pakette AI etkin değil</span>}
          </div>
          <div style={{ marginTop: 10, color: 'var(--fg-3)', fontSize: 12 }}>AI içermeyen paketteki tenant'lar AI butonlarını kullanmak isterse "paketinize dahil değil" uyarısı alır.</div>
        </div>
      </Card>
    </div>
  );
}
window.SaSettings = SaSettings;
