// ============================================================
// MOORE AI v13 — SETTINGS TAB
// Requires: shared/utils.js, shared/components.jsx loaded first
// ============================================================

const SettingsView = () => {
  const { useState } = React;
  const [testResult, setTestResult] = useState('');

  const testGemini = async () => {
    setTestResult('Testing Gemini direct from browser...');
    try {
      const cfg = await API.fetchConfig();
      const key = cfg.geminiKey;
      if (!key) { setTestResult('✗ GEMINI_API_KEY not set in .env'); return; }
      const models = ['gemini-2.5-flash', 'gemini-2.0-flash-001', 'gemini-2.0-flash', 'gemini-1.5-flash'];
      for (const model of models) {
        try {
          const r = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${key}`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ contents: [{ parts: [{ text: 'Reply with: GEMINI OK' }] }] })
          });
          const data = await r.json();
          if (data.error) throw new Error(data.error.message);
          const text = data.candidates?.[0]?.content?.parts?.[0]?.text;
          if (text) { setTestResult(`✓ ${model}: ${text.substring(0,60)}`); return; }
        } catch(e) { setTestResult(`Trying next model... ${e.message}`); }
      }
      setTestResult('✗ All models failed — check key at console.cloud.google.com');
    } catch (e) { setTestResult(`✗ ${e.message}`); }
  };

  const testElevenLabs = async () => {
    setTestResult('Testing ElevenLabs...');
    try {
      const res = await fetch('/api/elevenlabs/tts', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: 'Moore AI online. Neural systems operational.' })
      });
      if (res.ok) {
        const blob = await res.blob();
        const url = URL.createObjectURL(blob);
        new Audio(url).play();
        setTestResult('✓ ElevenLabs TTS working — audio playing');
      } else {
        const err = await res.json();
        setTestResult(`✗ ${err.error}`);
      }
    } catch (e) { setTestResult(`✗ ${e.message}`); }
  };

  const logout = () => {
    sessionStorage.removeItem('moore_auth');
    window.location.href = '/login';
  };

  const apiItems = [
    { label: 'GHL Access Token', env: 'GHL_ACCESS_TOKEN', desc: 'GoHighLevel Private Integration Token' },
    { label: 'Bland AI Key', env: 'BLAND_API_KEY', desc: 'For AI outbound calls — get at bland.ai' },
    { label: 'Calendar ID', env: 'CALENDAR_ID', desc: 'GHL Calendar ID for scheduling appointments' },
    { label: 'GHL Location ID', env: 'GHL_LOCATION_ID', desc: 'Your GHL sub-account location ID' },
    { label: 'Gemini API Key', env: 'GEMINI_API_KEY', desc: 'Google Gemini for AI chat and text generation' },
    { label: 'ElevenLabs API Key', env: 'ELEVENLABS_API_KEY', desc: 'ElevenLabs for Jake\'s voice synthesis' },
    { label: 'ElevenLabs Voice ID', env: 'ELEVENLABS_VOICE_ID', desc: 'Specific voice ID (default: Rachel)' },
    { label: 'SMTP User', env: 'SMTP_USER', desc: 'Gmail address for OTP emails (login system)' },
    { label: 'SMTP Pass', env: 'SMTP_PASS', desc: 'Gmail app password for OTP emails' },
    { label: 'Admin Password', env: 'ADMIN_PASSWORD', desc: 'Internal team login password' },
  ];

  return (
    <div className="p-6 max-w-3xl space-y-8">
      <div>
        <div className="text-xs mono text-slate-500 uppercase tracking-widest mb-1">Configuration</div>
        <h2 className="font-black text-white text-2xl italic tracking-tight">Settings</h2>
      </div>

      <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-800/50 font-bold text-white text-sm">API Keys (.env)</div>
        <div className="p-6 space-y-4">
          <div className="text-xs text-slate-500 bg-slate-900/60 border border-slate-800 rounded-xl p-4 mono leading-relaxed">
            These keys are loaded from your <span className="text-blue-400">.env</span> file on the server.<br />
            To change them, edit <span className="text-blue-400">.env</span> and restart the server.
          </div>
          {apiItems.map((item, i) => (
            <div key={i} className="flex items-start gap-4 py-3 border-b border-slate-800/30 last:border-0">
              <div className="flex-1">
                <div className="font-bold text-white text-sm">{item.label}</div>
                <div className="text-xs text-slate-500 mt-0.5">{item.desc}</div>
              </div>
              <div className="text-xs mono text-slate-600 bg-slate-900 border border-slate-800 rounded-lg px-3 py-1.5 shrink-0">{item.env}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-800/50 font-bold text-white text-sm">Connection Tests</div>
        <div className="p-6 space-y-3">
          <div className="flex gap-3 flex-wrap">
            <button onClick={testGemini} className="px-4 py-2.5 bg-blue-600/10 border border-blue-500/20 rounded-xl text-sm font-bold text-blue-400 hover:bg-blue-600/20 transition-all flex items-center gap-2">
              <Icon name="brain-circuit" size={14} /> Test Gemini AI
            </button>
            <button onClick={async () => {
              setTestResult('Fetching available models...');
              try {
                const res = await fetch('/api/gemini/models');
                const data = await res.json();
                if (data.models) setTestResult('Available models:\n' + data.models.filter(m => m.includes('gemini')).join('\n'));
                else setTestResult('✗ ' + data.error);
              } catch(e) { setTestResult('✗ ' + e.message); }
            }} className="px-4 py-2.5 bg-slate-700/40 border border-slate-600/40 rounded-xl text-sm font-bold text-slate-400 hover:bg-slate-700/60 transition-all flex items-center gap-2">
              <Icon name="list" size={14} /> List Models
            </button>
            <button onClick={testElevenLabs} className="px-4 py-2.5 bg-violet-600/10 border border-violet-500/20 rounded-xl text-sm font-bold text-violet-400 hover:bg-violet-600/20 transition-all flex items-center gap-2">
              <Icon name="mic" size={14} /> Test ElevenLabs
            </button>
            <button onClick={() => fetch('/api/ghl/sync', { method: 'POST' }).then(() => setTestResult('✓ GHL sync successful'))} className="px-4 py-2.5 bg-emerald-600/10 border border-emerald-500/20 rounded-xl text-sm font-bold text-emerald-400 hover:bg-emerald-600/20 transition-all flex items-center gap-2">
              <Icon name="database" size={14} /> Test GHL Sync
            </button>
          </div>
          {testResult && (
            <div className={`text-xs mono p-3 rounded-xl border whitespace-pre-wrap max-h-48 overflow-y-auto leading-relaxed ${testResult.startsWith('✓') || testResult.includes('Available') ? 'bg-emerald-950/30 border-emerald-800/40 text-emerald-400' : 'bg-red-950/30 border-red-800/40 text-red-400'}`}>
              {testResult}
            </div>
          )}
        </div>
      </div>

      <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl p-6">
        <div className="font-bold text-white text-sm mb-3">System Info</div>
        <div className="space-y-2 text-xs mono">
          {[
            ['Version', 'Moore AI v13.0 Enterprise'],
            ['Architecture', 'Multi-module React (CDN) + Express backend'],
            ['Gemini Models', 'gemini-2.5-flash → gemini-2.0-flash → gemini-1.5-flash'],
            ['TTS Engine', 'Gemini TTS (primary) → Browser Speech Synthesis (fallback)'],
            ['Voice Input', 'Web Speech API (Chrome/Edge)'],
            ['CRM', 'GoHighLevel API v2021-07-28'],
            ['Frontend', 'React 18 (UMD) + Tailwind CSS + JetBrains Mono'],
          ].map(([k, v], i) => (
            <div key={i} className="flex gap-3">
              <span className="text-slate-600 w-36 shrink-0">{k}</span>
              <span className="text-slate-400">{v}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="bg-red-950/20 border border-red-800/30 rounded-2xl p-6">
        <div className="font-bold text-white text-sm mb-2">Session</div>
        <div className="text-xs text-slate-500 mb-4">You are logged in as admin. Click below to sign out and return to the login page.</div>
        <button onClick={logout} className="px-4 py-2.5 bg-red-600/20 border border-red-500/30 rounded-xl text-sm font-bold text-red-400 hover:bg-red-600/30 transition-all flex items-center gap-2">
          <Icon name="log-out" size={14} /> Sign Out
        </button>
      </div>
    </div>
  );
};
