// admin-ai.jsx — Gestionare AI Chat (Knowledge Base, Config, Playground, Conversații, Stats)

const { useState: useStateAI, useEffect: useEffectAI, useRef: useRefAI } = React;

const KB_DOCS = [
  { id: 1, title: 'Ghid TikTok Live 2026', type: 'pdf', icon: '📄', size: '2.4 MB', pages: 42, status: 'ok', date: '12 apr 2026', tags: ['live', 'strategii', 'începători'] },
  { id: 2, title: 'Regulament 4U Agency', type: 'docx', icon: '📝', size: '180 KB', pages: 8, status: 'ok', date: '5 apr 2026', tags: ['regulament', 'oficial'] },
  { id: 3, title: 'FAQ Module', type: 'txt', icon: '📃', size: '24 KB', pages: 1, status: 'ok', date: '3 apr 2026', tags: ['module', 'faq'] },
  { id: 4, title: 'Strategii Live Battles', type: 'pdf', icon: '📄', size: '5.1 MB', pages: 68, status: 'ok', date: '28 mar 2026', tags: ['battles', 'meciuri', 'avansat'] },
  { id: 5, title: 'Catalog produse Shop', type: 'pdf', icon: '📄', size: '12.3 MB', pages: 124, status: 'processing', date: '21 apr 2026', tags: ['shop', 'produse'] },
  { id: 6, title: 'Tutorial OBS Studio', type: 'link', icon: '🔗', size: 'web', pages: '—', status: 'ok', date: '14 mar 2026', tags: ['tehnic', 'streaming'] },
  { id: 7, title: 'Scheme bonus diamante', type: 'docx', icon: '📝', size: '95 KB', pages: 4, status: 'ok', date: '10 mar 2026', tags: ['diamante', 'puncte'] },
  { id: 8, title: 'Branduri partenere campanii', type: 'pdf', icon: '📄', size: '3.8 MB', pages: 32, status: 'error', date: '8 mar 2026', tags: ['campanii', 'branduri'] },
];

const AI_CONVOS = [
  { id: 1, name: 'Andra Mihăescu', user: '@andra.m', avatar: 'AM', subj: 'Cum cresc audiența pentru Live?', time: '14:32', count: 8, rating: 'good' },
  { id: 2, name: 'Răzvan Popescu', user: '@razvan.live', avatar: 'RP', subj: 'Cât trebuie să fac live ca să ating BRONZE?', time: '13:58', count: 5, rating: 'good' },
  { id: 3, name: 'Maria Iancu', user: '@maria.iancu', avatar: 'MI', subj: 'Probleme cu meciul de azi seară', time: '13:21', count: 12, rating: 'bad' },
  { id: 4, name: 'Sophia Lloyd', user: '@sophia_l', avatar: 'SL', subj: 'How do I redeem 4U points?', time: '12:48', count: 4, rating: 'good' },
  { id: 5, name: 'Lukas Schmidt', user: '@lukas.s', avatar: 'LS', subj: 'Modulul Charisma este disponibil în germană?', time: '12:15', count: 3, rating: null },
  { id: 6, name: 'Elena Petrescu', user: '@elena.p', avatar: 'EP', subj: 'Strategii diamante săptămânale', time: '11:42', count: 9, rating: 'good' },
  { id: 7, name: 'Marco Rossi', user: '@marco.r', avatar: 'MR', subj: 'Quanto è il bonus per 100 ore live?', time: '11:08', count: 6, rating: 'good' },
  { id: 8, name: 'Tom Jenkins', user: '@tomj_uk', avatar: 'TJ', subj: 'Why was my campaign rejected?', time: '10:34', count: 7, rating: 'bad' },
];

function AdminAiPage({ onNav, user }) {
  const adminUser = { name: user?.name || 'Andrei Popescu' };
  const [tab, setTab] = useStateAI('kb');
  const [Toast, toast] = useToast();

  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: '100vh', background: 'linear-gradient(135deg, #0A0A0F, #0E0E0E)' }}>
      <DashSidebar active="admin-ai" onNav={onNav} user={adminUser} admin />
      <main style={{ padding: '32px 48px 80px', overflowY: 'auto' }} className="dash-main">
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16, marginBottom: 24 }}>
          <div>
            <div className="pill" style={{ background: 'rgba(255,215,0,.08)', borderColor: 'rgba(255,215,0,.4)', color: 'var(--accent-2)', display: 'inline-flex', marginBottom: 12 }}>
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.15em' }}>● GESTIONARE AI CHAT</span>
            </div>
            <h1 className="display" style={{ fontSize: 32, margin: 0 }}>Knowledge Base & Setări AI Assistant</h1>
            <p style={{ fontSize: 13, color: 'var(--txt-2)', marginTop: 6 }}>Antrenează 4U Assistant cu documente, prompt-uri și exemple</p>
          </div>
          <button className="btn btn-primary btn-sm" onClick={() => setTab('play')}>🧪 Test playground →</button>
        </div>

        {/* Tabs */}
        <div style={{ position: 'sticky', top: 0, zIndex: 5, padding: '8px 0 16px', background: 'linear-gradient(180deg, #0A0A0F 50%, transparent)' }}>
          <div className="card-glass" style={{ padding: 6, display: 'flex', gap: 4, overflowX: 'auto' }}>
            {[
              ['kb', '📚 Knowledge Base'], ['cfg', '⚙️ Configurare'], ['play', '🧪 Playground'],
              ['conv', '💬 Conversații'], ['stats', '📊 Statistici'],
            ].map(([k, l]) => (
              <button key={k} onClick={() => setTab(k)} style={{
                padding: '8px 14px', borderRadius: 8, fontSize: 13, fontWeight: tab === k ? 600 : 400,
                background: tab === k ? 'var(--accent-1)' : 'transparent',
                color: tab === k ? '#000' : 'var(--txt-2)',
                border: 'none', cursor: 'default', whiteSpace: 'nowrap',
              }}>{l}</button>
            ))}
          </div>
        </div>

        {tab === 'kb' && <KbTab toast={toast} />}
        {tab === 'cfg' && <CfgTab toast={toast} />}
        {tab === 'play' && <PlayTab />}
        {tab === 'conv' && <ConvTab />}
        {tab === 'stats' && <StatsTab />}

        {Toast}
      </main>
    </div>
  );
}

// ─── TAB 1: Knowledge Base ───
function KbTab({ toast }) {
  const [sel, setSel] = useStateAI(KB_DOCS[0]);
  const [q, setQ] = useStateAI('');
  const [filter, setFilter] = useStateAI('all');
  const [showAdd, setShowAdd] = useStateAI(false);

  let list = KB_DOCS;
  if (filter !== 'all') list = list.filter(d => d.type === filter);
  if (q) list = list.filter(d => d.title.toLowerCase().includes(q.toLowerCase()));

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: 20 }} className="ai-2col">
      {/* Left: list */}
      <div style={{ display: 'grid', gap: 12, alignContent: 'start' }}>
        <button className="btn btn-primary" onClick={() => setShowAdd(true)}>+ Adaugă document nou</button>
        <div style={{ display: 'flex', gap: 8 }}>
          <input className="input" placeholder="🔍 Caută document..." value={q} onChange={(e) => setQ(e.target.value)} style={{ flex: 1 }} />
          <select className="input" value={filter} onChange={(e) => setFilter(e.target.value)} style={{ width: 'auto' }}>
            <option value="all">Toate</option>
            <option value="pdf">PDF</option>
            <option value="docx">DOCX</option>
            <option value="txt">TXT</option>
            <option value="link">Link</option>
          </select>
        </div>
        <div style={{ display: 'grid', gap: 8, maxHeight: 700, overflowY: 'auto', paddingRight: 4 }}>
          {list.map(d => {
            const active = sel.id === d.id;
            return (
              <div key={d.id} onClick={() => setSel(d)} className="card" style={{
                padding: 14, cursor: 'default', borderColor: active ? 'var(--accent-1)' : 'rgba(255,255,255,.06)',
                background: active ? 'rgba(82,242,15,.04)' : undefined,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ fontSize: 20 }}>{d.icon}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.title}</div>
                    <div style={{ fontSize: 10, color: 'var(--txt-3)', fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>
                      {d.size} · {d.pages !== '—' ? `${d.pages} pag` : 'web'} · {d.date}
                    </div>
                  </div>
                  <span style={{
                    padding: '3px 8px', borderRadius: 6, fontSize: 10, fontWeight: 600,
                    background: d.status === 'ok' ? 'rgba(82,242,15,.15)' : d.status === 'processing' ? 'rgba(255,215,0,.15)' : 'rgba(239,68,68,.15)',
                    color: d.status === 'ok' ? 'var(--accent-1)' : d.status === 'processing' ? '#FFD700' : '#ef4444',
                  }}>
                    {d.status === 'ok' ? '✓' : d.status === 'processing' ? '⏳' : '❌'}
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Right: detail */}
      <div className="card" style={{ padding: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
          <div style={{ fontSize: 36 }}>{sel.icon}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 20, fontWeight: 600 }}>{sel.title}</div>
            <div style={{ fontSize: 11, color: 'var(--txt-3)', fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>
              {sel.type.toUpperCase()} · {sel.size} · Upload: {sel.date}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn-glass btn-sm">👁 Vezi</button>
            <button className="btn btn-glass btn-sm">🔄 Reprocesează</button>
            <button className="btn btn-glass btn-sm">🗑</button>
          </div>
        </div>

        <div style={{ background: 'rgba(255,255,255,.02)', borderRadius: 12, padding: 16, fontSize: 12, color: 'var(--txt-2)', lineHeight: 1.7, marginBottom: 20, maxHeight: 220, overflowY: 'auto', fontFamily: 'JetBrains Mono, monospace' }}>
          # {sel.title}<br /><br />
          Ghid complet pentru creatorii 4U Agency. Acest document acoperă strategiile esențiale pentru a-ți crește audiența pe TikTok Live, optimiza orele de transmisie și maximiza câștigurile din diamante.<br /><br />
          ## Capitolul 1 — Pregătirea înainte de live<br />
          Înainte de a porni o sesiune live, asigură-te că ai pregătit: setup tehnic (lumini, microfon, stabilitate net), conținut (3-5 idei discuții/jocuri), schedule (anunță audiența cu 24h înainte)...<br /><br />
          ## Capitolul 2 — Timing optim<br />
          Conform datelor 4U pe 5.000+ creatori, ferestrele optime sunt 19:00-22:00 (RO) pentru audiență locală și 21:00-00:00 pentru audiență internațională...
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 20 }} className="ai-stats">
          {[
            ['Chunks', '142'], ['Tokens', '38.4K'], ['Embeddings', '142'], ['Update', '12 apr'],
          ].map(([l, v]) => (
            <div key={l} style={{ background: 'rgba(255,255,255,.02)', padding: 12, borderRadius: 8, textAlign: 'center' }}>
              <div style={{ fontSize: 10, color: 'var(--txt-3)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '.08em' }}>{l.toUpperCase()}</div>
              <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--accent-1)', fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>{v}</div>
            </div>
          ))}
        </div>

        <div style={{ marginBottom: 20 }}>
          <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'JetBrains Mono, monospace', marginBottom: 8 }}>TAGS</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {sel.tags.map(t => (
              <span key={t} style={{ padding: '4px 10px', borderRadius: 999, background: 'rgba(82,242,15,.1)', color: 'var(--accent-1)', fontSize: 11, fontFamily: 'JetBrains Mono, monospace' }}>#{t} ✕</span>
            ))}
            <button style={{ padding: '4px 10px', borderRadius: 999, background: 'rgba(255,255,255,.04)', border: '1px dashed rgba(255,255,255,.2)', color: 'var(--txt-3)', fontSize: 11 }}>+ tag</button>
          </div>
        </div>

        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'JetBrains Mono, monospace', marginBottom: 8 }}>NOTE PENTRU AI</div>
          <textarea className="input" rows="3" defaultValue="Folosește acest document când userii întreabă despre strategii live, timing optim sau pregătire înainte de transmisie. Conține date oficiale 4U." style={{ resize: 'vertical', minHeight: 80 }} />
        </div>

        <button className="btn btn-primary" onClick={() => toast('Modificări salvate')}>💾 Salvează modificări</button>
      </div>

      {showAdd && (
        <div onClick={() => setShowAdd(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.7)', zIndex: 100, display: 'grid', placeItems: 'center', padding: 20 }}>
          <div onClick={(e) => e.stopPropagation()} className="card" style={{ padding: 28, maxWidth: 560, width: '100%' }}>
            <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 16 }}>+ Adaugă document nou</div>
            <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
              {['📄 Upload fișier', '🔗 Link URL', '✏️ Text direct'].map((l, i) => (
                <button key={i} className={i === 0 ? 'btn btn-primary btn-sm' : 'btn btn-glass btn-sm'} style={{ flex: 1 }}>{l}</button>
              ))}
            </div>
            <div style={{ border: '2px dashed rgba(82,242,15,.3)', borderRadius: 12, padding: 32, textAlign: 'center', marginBottom: 16, background: 'rgba(82,242,15,.02)' }}>
              <div style={{ fontSize: 36, marginBottom: 8 }}>📤</div>
              <div style={{ fontSize: 13 }}>Drag & drop sau click pentru fișier</div>
              <div style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 4 }}>PDF, DOCX, TXT · Max 50MB</div>
            </div>
            <input className="input" placeholder="Titlu document" style={{ marginBottom: 8 }} />
            <select className="input" style={{ marginBottom: 8 }}><option>Categorie...</option></select>
            <input className="input" placeholder="Tags (separate prin virgulă)" style={{ marginBottom: 16 }} />
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button className="btn btn-glass" onClick={() => setShowAdd(false)}>Anulează</button>
              <button className="btn btn-primary" onClick={() => { setShowAdd(false); toast('Document adăugat — în procesare'); }}>Procesează & adaugă</button>
            </div>
          </div>
        </div>
      )}
      <style>{`@media (max-width: 1100px) { .ai-2col { grid-template-columns: 1fr !important; } } @media (max-width: 700px) { .ai-stats { grid-template-columns: repeat(2, 1fr) !important; } }`}</style>
    </div>
  );
}

// ─── TAB 2: Config ───
function CfgTab({ toast }) {
  const [prompt, setPrompt] = useStateAI(`Ești 4U Assistant, asistentul oficial al 4U Agency — agenția #1 de TikTok Live din România.

Ajuti creatorii cu:
- Strategii de creștere pe TikTok Live
- Întrebări despre module, meciuri, campanii
- Răspunsuri din knowledge base 4U

Stil: prietenos, direct, în română (sau limba userului).
Nu inventa informații. Dacă nu știi, redirecționează la suport uman.`);
  const [model, setModel] = useStateAI('sonnet');
  const [temp, setTemp] = useStateAI(0.7);
  const [maxTok, setMaxTok] = useStateAI(1000);
  const [chips, setChips] = useStateAI(['Cum cresc audiența?', 'Ore optime live', 'Strategii diamante', 'Pregătire meci', 'Înscriere module', 'Cum câștig 4U Points']);
  const [tg1, setTg1] = useStateAI(true), [tg2, setTg2] = useStateAI(true), [tg3, setTg3] = useStateAI(true);

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      <div className="card" style={{ padding: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>System prompt (instrucțiuni AI)</div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn-glass btn-sm" onClick={() => { navigator.clipboard?.writeText(prompt); toast('Copiat'); }}>📋 Copiază</button>
            <button className="btn btn-glass btn-sm">💡 Exemple</button>
          </div>
        </div>
        <textarea className="input" rows="14" value={prompt} onChange={(e) => setPrompt(e.target.value)} style={{ resize: 'vertical', minHeight: 280, fontFamily: 'JetBrains Mono, monospace', fontSize: 12, lineHeight: 1.6 }} />
        <div style={{ fontSize: 11, color: 'var(--txt-3)', fontFamily: 'JetBrains Mono, monospace', marginTop: 8, textAlign: 'right' }}>{prompt.length} / 4000 caractere</div>
      </div>

      <div className="card" style={{ padding: 24 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 16 }}>Setări tehnice</div>
        <div style={{ display: 'grid', gap: 18 }}>
          <div>
            <div style={{ fontSize: 12, color: 'var(--txt-2)', marginBottom: 8 }}>Model AI</div>
            <div style={{ display: 'flex', gap: 8 }} className="ai-models">
              {[['sonnet','Claude Sonnet 4.7','RECOMANDAT'], ['opus','Claude Opus 4.7'], ['haiku','Claude Haiku 4.5']].map(([k, l, badge]) => (
                <button key={k} onClick={() => setModel(k)} className="card" style={{
                  padding: 14, cursor: 'default', flex: 1,
                  borderColor: model === k ? 'var(--accent-1)' : 'rgba(255,255,255,.06)',
                  background: model === k ? 'rgba(82,242,15,.04)' : undefined,
                  textAlign: 'left',
                }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{l}</div>
                  {badge && <div style={{ fontSize: 9, color: 'var(--accent-2)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '.1em', marginTop: 4 }}>● {badge}</div>}
                </button>
              ))}
            </div>
          </div>
          <SliderRow label="Temperature (creativitate vs precizie)" v={temp} set={setTemp} min={0} max={1} step={0.05} fmt={v => v.toFixed(2)} />
          <SliderRow label="Max response tokens" v={maxTok} set={setMaxTok} min={100} max={4000} step={100} fmt={v => v.toString()} />
          <SliderRow label="Frecvența penalty" v={0} set={() => {}} min={-2} max={2} step={0.1} fmt={v => v.toFixed(1)} />
          <button className="btn btn-glass" style={{ alignSelf: 'flex-start' }}>🔄 Resetează la defaults</button>
        </div>
        <style>{`@media (max-width: 800px) { .ai-models { flex-direction: column !important; } }`}</style>
      </div>

      <div className="card" style={{ padding: 24 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Răspunsuri rapide (chips de sugestii)</div>
        <div style={{ fontSize: 12, color: 'var(--txt-3)', marginBottom: 12 }}>Apar în interfața de chat ca sugestii rapide pentru creatori</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {chips.map((c, i) => (
            <span key={i} style={{ padding: '8px 14px', borderRadius: 999, background: 'rgba(82,242,15,.1)', color: 'var(--accent-1)', fontSize: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
              {c}
              <button onClick={() => setChips(chips.filter((_, j) => j !== i))} style={{ background: 'none', border: 'none', color: 'var(--accent-1)', cursor: 'default', padding: 0, fontSize: 14 }}>✕</button>
            </span>
          ))}
          <button style={{ padding: '8px 14px', borderRadius: 999, background: 'rgba(255,255,255,.04)', border: '1px dashed rgba(255,255,255,.2)', color: 'var(--txt-3)', fontSize: 12 }}>+ chip nou</button>
        </div>
      </div>

      <div className="card" style={{ padding: 24 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>🛡 Filtre conținut (safety)</div>
        <div style={{ display: 'grid', gap: 10 }}>
          {[
            ['Blocare conținut adult', tg1, setTg1],
            ['Blocare informații confidențiale 4U', tg2, setTg2],
            ['Avertizare la conținut sensibil', tg3, setTg3],
          ].map(([l, v, set]) => (
            <div key={l} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 14px', background: 'rgba(255,255,255,.02)', borderRadius: 8 }}>
              <span style={{ fontSize: 13 }}>{l}</span>
              <button onClick={() => set(!v)} style={{ width: 40, height: 22, borderRadius: 999, background: v ? 'var(--accent-1)' : 'rgba(255,255,255,.1)', border: 'none', cursor: 'default', position: 'relative' }}>
                <div style={{ position: 'absolute', top: 2, left: v ? 20 : 2, width: 18, height: 18, borderRadius: '50%', background: v ? '#000' : '#fff', transition: 'left .2s' }} />
              </button>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 14, fontSize: 11, color: 'var(--txt-3)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '.08em', marginBottom: 8 }}>CUSTOM BLOCKED KEYWORDS</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {['parolă', 'admin@4u.ro', 'baza_de_date'].map(t => (
            <span key={t} style={{ padding: '4px 10px', borderRadius: 999, background: 'rgba(239,68,68,.1)', color: '#ef4444', fontSize: 11, fontFamily: 'JetBrains Mono, monospace' }}>#{t} ✕</span>
          ))}
        </div>
      </div>

      <button className="btn btn-primary" style={{ alignSelf: 'flex-start', position: 'sticky', bottom: 20, boxShadow: '0 8px 24px rgba(82,242,15,.3)' }} onClick={() => toast('Toate setările salvate')}>💾 Salvează toate setările</button>
    </div>
  );
}

function SliderRow({ label, v, set, min, max, step, fmt }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--txt-2)', marginBottom: 6 }}>
        <span>{label}</span>
        <span style={{ color: 'var(--accent-1)', fontFamily: 'JetBrains Mono, monospace', fontWeight: 600 }}>{fmt(v)}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={v} onChange={(e) => set(parseFloat(e.target.value))} style={{ width: '100%', accentColor: 'var(--accent-1)' }} />
    </div>
  );
}

// ─── TAB 3: Playground ───
function PlayTab() {
  const [msgs, setMsgs] = useStateAI([
    { role: 'user', text: 'Cum cresc audiența pe TikTok Live ca începător?' },
    { role: 'ai', text: 'Salut! Pentru un începător, recomand 3 lucruri concrete:\n\n1. **Consistență** — minim 5 zile/săptămână, aceleași ore (ex: 19:00-21:00)\n2. **Hook în primele 30s** — anunță ce faci, de ce să rămână\n3. **Interacțiune activă** — răspunde la comentarii, folosește numele lor\n\nDin datele 4U, creatorii care urmează schema asta cresc 3x mai rapid în primele 60 zile. Vrei să aprofundăm vreo strategie?' },
    { role: 'user', text: 'Ce ore sunt cele mai bune pentru audiența din România?' },
    { role: 'ai', text: 'Pentru audiența RO, ferestrele optime sunt:\n\n🔥 **19:00-22:00** — peak primary (familii, după muncă)\n⭐ **21:30-00:30** — peak secondary (Gen Z, weekend)\n☀️ **12:00-14:00** — pauza de prânz (conținut scurt, 30-45min)\n\nEvită 06:00-11:00 și 15:00-18:00 — engagement scade cu ~60%.' },
  ]);
  const [input, setInput] = useStateAI('');
  const send = () => {
    if (!input.trim()) return;
    setMsgs([...msgs, { role: 'user', text: input }, { role: 'ai', text: 'Mulțumesc pentru întrebare! [răspuns simulat în mediul de test]' }]);
    setInput('');
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '0.7fr 1fr', gap: 20 }} className="ai-2col">
      <div style={{ display: 'grid', gap: 16, alignContent: 'start' }}>
        <div className="card" style={{ padding: 20 }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Setări test</div>
          <div style={{ display: 'grid', gap: 12 }}>
            <div>
              <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'JetBrains Mono, monospace', marginBottom: 4 }}>Versiune</div>
              <select className="input"><option>Setări curente (production)</option><option>Setări test</option><option>Setări istorice — 5 apr</option></select>
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'JetBrains Mono, monospace', marginBottom: 4 }}>Persona test</div>
              <select className="input"><option>Creator începător</option><option>Creator avansat</option><option>Brand</option><option>Custom</option></select>
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'JetBrains Mono, monospace', marginBottom: 4 }}>Override system prompt (opțional)</div>
              <textarea className="input" rows="3" placeholder="Lasă gol pentru default..." style={{ resize: 'vertical', minHeight: 70, fontSize: 11, fontFamily: 'JetBrains Mono, monospace' }} />
            </div>
            <button className="btn btn-primary">🚀 Începe sesiune test</button>
          </div>
        </div>

        <div className="card" style={{ padding: 20 }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Note din testare</div>
          <div style={{ display: 'grid', gap: 8, fontSize: 12 }}>
            <div style={{ padding: 10, background: 'rgba(82,242,15,.06)', borderRadius: 8, borderLeft: '3px solid var(--accent-1)' }}>
              <div style={{ fontSize: 10, color: 'var(--accent-1)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '.08em' }}>👍 BUN</div>
              <div style={{ marginTop: 4 }}>Răspunsul despre ore optime e perfect — date clare, format scanabil</div>
            </div>
            <div style={{ padding: 10, background: 'rgba(239,68,68,.06)', borderRadius: 8, borderLeft: '3px solid #ef4444' }}>
              <div style={{ fontSize: 10, color: '#ef4444', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '.08em' }}>👎 SLAB</div>
              <div style={{ marginTop: 4 }}>Începutul e prea generic — sări direct la valoare</div>
            </div>
          </div>
          <button className="btn btn-glass" style={{ marginTop: 12, width: '100%' }}>Aplică învățămintele la production →</button>
        </div>
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column', minHeight: 600 }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid rgba(255,255,255,.06)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ padding: '3px 10px', borderRadius: 6, background: 'rgba(255,215,0,.15)', color: '#FFD700', fontSize: 11, fontWeight: 600, fontFamily: 'JetBrains Mono, monospace' }}>🧪 TEST MODE</span>
            <span style={{ fontSize: 13, fontWeight: 500 }}>Sesiune playground</span>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn-glass btn-sm">🗑</button>
            <button className="btn btn-glass btn-sm">💾 Salvează preset</button>
          </div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 20, display: 'grid', gap: 14, alignContent: 'start' }}>
          {msgs.map((m, i) => (
            <div key={i}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', flexDirection: m.role === 'user' ? 'row-reverse' : 'row' }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, display: 'grid', placeItems: 'center', background: m.role === 'user' ? 'var(--accent-2)' : 'var(--accent-1)', color: '#000', fontSize: 14, fontWeight: 700, flexShrink: 0 }}>
                  {m.role === 'user' ? '👤' : '🤖'}
                </div>
                <div style={{
                  padding: '10px 14px', borderRadius: 12, maxWidth: '80%',
                  background: m.role === 'user' ? 'rgba(255,215,0,.08)' : 'rgba(82,242,15,.06)',
                  fontSize: 13, lineHeight: 1.6, whiteSpace: 'pre-wrap',
                }}>{m.text}</div>
              </div>
              {m.role === 'ai' && (
                <div style={{ display: 'flex', gap: 6, marginTop: 6, marginLeft: 42 }}>
                  <button className="btn btn-glass btn-sm" style={{ fontSize: 10, padding: '3px 8px' }}>👍 Bun</button>
                  <button className="btn btn-glass btn-sm" style={{ fontSize: 10, padding: '3px 8px' }}>👎 Slab</button>
                  <button className="btn btn-glass btn-sm" style={{ fontSize: 10, padding: '3px 8px' }}>📌 Salvează exemplu</button>
                  <button className="btn btn-glass btn-sm" style={{ fontSize: 10, padding: '3px 8px' }}>🔁 Regenerează</button>
                </div>
              )}
            </div>
          ))}
        </div>
        <div style={{ padding: 16, borderTop: '1px solid rgba(255,255,255,.06)', display: 'flex', gap: 8 }}>
          <input className="input" placeholder="Scrie un mesaj de test..." value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()} style={{ flex: 1 }} />
          <button className="btn btn-primary" onClick={send}>↑ Trimite</button>
        </div>
      </div>
    </div>
  );
}

// ─── TAB 4: Conversații ───
function ConvTab() {
  const [sel, setSel] = useStateAI(null);
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 12 }}>
        <div style={{ fontSize: 13, color: 'var(--txt-2)' }}>
          <strong style={{ color: 'var(--accent-1)' }}>342</strong> conversații azi · <strong style={{ color: 'var(--accent-2)' }}>1.847</strong> săptămâna asta · <strong>8.421</strong> total
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-glass btn-sm">📥 Export CSV</button>
        </div>
      </div>
      <div className="card" style={{ padding: 14, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <input className="input" placeholder="🔍 Caută în conținut..." style={{ flex: 1, minWidth: 200 }} />
        <input type="date" className="input" style={{ width: 'auto' }} />
        <select className="input" style={{ width: 'auto' }}><option>Toate ratings</option><option>👍 Bun</option><option>👎 Slab</option><option>Fără rating</option></select>
      </div>
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 800 }}>
            <thead>
              <tr style={{ background: 'rgba(255,255,255,.03)' }}>
                {['Creator', 'Subiect', 'Mesaje', 'Rating', 'Timp', ''].map(h => (
                  <th key={h} style={{ padding: '12px 14px', textAlign: 'left', fontSize: 10, color: 'var(--txt-3)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '.08em' }}>{h.toUpperCase()}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {AI_CONVOS.map(c => (
                <tr key={c.id} style={{ borderTop: '1px solid rgba(255,255,255,.04)', cursor: 'default' }} onClick={() => setSel(c)}>
                  <td style={{ padding: '12px 14px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{ width: 32, height: 32, borderRadius: 8, background: 'rgba(82,242,15,.15)', color: 'var(--accent-1)', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700 }}>{c.avatar}</div>
                      <div>
                        <div style={{ fontWeight: 500 }}>{c.name}</div>
                        <div style={{ fontSize: 11, color: 'var(--txt-3)', fontFamily: 'JetBrains Mono, monospace' }}>{c.user}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: '12px 14px', color: 'var(--txt-2)' }}>{c.subj}</td>
                  <td style={{ padding: '12px 14px', fontFamily: 'JetBrains Mono, monospace' }}>{c.count}</td>
                  <td style={{ padding: '12px 14px' }}>
                    <span style={{ fontSize: 16 }}>{c.rating === 'good' ? '👍' : c.rating === 'bad' ? '👎' : '—'}</span>
                  </td>
                  <td style={{ padding: '12px 14px', fontFamily: 'JetBrains Mono, monospace', color: 'var(--txt-3)' }}>{c.time}</td>
                  <td style={{ padding: '12px 14px' }}><button className="btn btn-glass btn-sm">Deschide →</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      {sel && (
        <div onClick={() => setSel(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.7)', zIndex: 100, display: 'grid', placeItems: 'center', padding: 20 }}>
          <div onClick={(e) => e.stopPropagation()} className="card" style={{ padding: 0, maxWidth: 640, width: '100%', maxHeight: '85vh', display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: 20, borderBottom: '1px solid rgba(255,255,255,.06)' }}>
              <div style={{ fontSize: 16, fontWeight: 600 }}>{sel.name} · {sel.subj}</div>
              <div style={{ fontSize: 11, color: 'var(--txt-3)', fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>{sel.count} mesaje · {sel.time}</div>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: 20, display: 'grid', gap: 12 }}>
              {Array.from({ length: sel.count }).map((_, i) => (
                <div key={i} style={{ display: 'flex', gap: 8, flexDirection: i % 2 === 0 ? 'row' : 'row-reverse' }}>
                  <div style={{ width: 28, height: 28, borderRadius: 7, background: i % 2 === 0 ? 'var(--accent-2)' : 'var(--accent-1)', color: '#000', display: 'grid', placeItems: 'center', fontSize: 13 }}>{i % 2 === 0 ? '👤' : '🤖'}</div>
                  <div style={{ padding: '8px 12px', borderRadius: 10, background: 'rgba(255,255,255,.04)', maxWidth: '75%', fontSize: 12 }}>
                    {i % 2 === 0 ? 'Întrebare creator #' + (i + 1) + '...' : 'Răspuns AI cu detalii relevante despre subiect...'}
                  </div>
                </div>
              ))}
            </div>
            <div style={{ padding: 16, borderTop: '1px solid rgba(255,255,255,.06)', display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button className="btn btn-glass btn-sm">📌 Adaugă în KB</button>
              <button className="btn btn-glass btn-sm">⚠ Trimite la review</button>
              <button className="btn btn-glass" onClick={() => setSel(null)}>Închide</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── TAB 5: Stats AI ───
function StatsTab() {
  return (
    <div style={{ display: 'grid', gap: 20 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }} className="ai-kpi">
        {[
          ['💬', 'Conversații luna', '8.421', 'var(--accent-1)'],
          ['👥', 'Creatori unici', '1.247', 'var(--accent-2)'],
          ['⏱', 'Durată medie', '5m 23s', 'var(--accent-1)'],
          ['⭐', 'Rating mediu', '4.6/5', '#FFD700'],
        ].map(([i, l, v, c]) => (
          <div key={l} className="card" style={{ padding: 16 }}>
            <div style={{ fontSize: 22 }}>{i}</div>
            <div style={{ fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '.08em', fontFamily: 'JetBrains Mono, monospace', marginTop: 6 }}>{l}</div>
            <div style={{ fontSize: 24, fontWeight: 700, color: c, fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>{v}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }} className="ai-2col">
        <div className="card" style={{ padding: 20 }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Top 10 întrebări frecvente</div>
          <div style={{ display: 'grid', gap: 6 }}>
            {[
              ['Cum cresc audiența?', 421],
              ['Ce ore sunt optime pentru live?', 387],
              ['Cum câștig 4U Points?', 342],
              ['Strategii diamante săptămânale', 298],
              ['Cum mă înscriu la module?', 267],
              ['Pregătire înainte de meci', 231],
              ['Reguli campanii branduri', 198],
              ['Cum schimb tier-ul?', 172],
              ['Plata diamantelor luna asta', 154],
              ['Echipament recomandat live', 138],
            ].map(([q, n], i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '24px 1fr 60px 80px', gap: 10, alignItems: 'center', padding: '8px 0', fontSize: 12, borderBottom: i < 9 ? '1px solid rgba(255,255,255,.04)' : 'none' }}>
                <span style={{ color: 'var(--txt-3)', fontFamily: 'JetBrains Mono, monospace' }}>#{i + 1}</span>
                <span>{q}</span>
                <div style={{ height: 6, background: 'rgba(255,255,255,.05)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: (n / 421 * 100) + '%', background: 'var(--accent-1)' }} />
                </div>
                <span style={{ fontFamily: 'JetBrains Mono, monospace', textAlign: 'right', color: 'var(--accent-1)' }}>{n}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="card" style={{ padding: 20 }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Heatmap utilizare</div>
          <div style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 14 }}>Most active: Joi 19:00-22:00</div>
          <Heatmap />
        </div>
      </div>

      <div className="card" style={{ padding: 20 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Evoluție conversații (90 zile)</div>
        <ConvLineChart />
      </div>

      <div>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Probleme detectate</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }} className="ai-prob">
          {[
            ['🔴', '12 conversații fără răspuns satisfăcător săptămâna asta', '#ef4444', 'rgba(239,68,68,.06)'],
            ['🟡', 'Creatorii întreabă des despre "live battles 1v1", dar topic lipsește din KB', '#FFD700', 'rgba(255,215,0,.06)'],
            ['🟢', 'Topic "meciuri" are rating mediu 4.9/5 — top performer', 'var(--accent-1)', 'rgba(82,242,15,.06)'],
          ].map(([i, t, c, b], k) => (
            <div key={k} className="card" style={{ padding: 16, background: b, borderColor: c }}>
              <div style={{ fontSize: 20 }}>{i}</div>
              <div style={{ fontSize: 12, color: 'var(--txt-2)', marginTop: 8, lineHeight: 1.5 }}>{t}</div>
            </div>
          ))}
        </div>
      </div>
      <style>{`@media (max-width: 900px) { .ai-kpi { grid-template-columns: repeat(2, 1fr) !important; } .ai-prob { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

function Heatmap() {
  const days = ['L', 'Ma', 'Mi', 'J', 'V', 'S', 'D'];
  return (
    <div style={{ overflowX: 'auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '24px repeat(24, 1fr)', gap: 2, minWidth: 480 }}>
        <div></div>
        {Array.from({ length: 24 }).map((_, h) => (
          <div key={h} style={{ fontSize: 8, color: 'var(--txt-3)', textAlign: 'center', fontFamily: 'JetBrains Mono, monospace' }}>{h % 4 === 0 ? h : ''}</div>
        ))}
        {days.map((d, di) => (
          <React.Fragment key={di}>
            <div style={{ fontSize: 10, color: 'var(--txt-3)', display: 'flex', alignItems: 'center', fontFamily: 'JetBrains Mono, monospace' }}>{d}</div>
            {Array.from({ length: 24 }).map((_, h) => {
              let intensity = 0;
              if (h >= 19 && h <= 22) intensity = di === 3 ? 1 : 0.7;
              else if (h >= 17 && h <= 23) intensity = 0.4 + Math.random() * 0.3;
              else if (h >= 12 && h <= 14) intensity = 0.3;
              else if (h >= 6 && h <= 11) intensity = 0.1;
              return <div key={h} style={{ aspectRatio: '1', background: `rgba(82,242,15,${intensity})`, borderRadius: 2, border: intensity > 0 ? 'none' : '1px solid rgba(255,255,255,.03)' }} title={`${d} ${h}:00`} />;
            })}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

function ConvLineChart() {
  const data = Array.from({ length: 90 }, (_, i) => ({
    total: 80 + Math.sin(i / 8) * 30 + Math.random() * 20 + i * 0.5,
    good: 60 + Math.sin(i / 8) * 25 + Math.random() * 15 + i * 0.4,
    bad: 8 + Math.cos(i / 12) * 4 + Math.random() * 3,
  }));
  const max = 180;
  const W = 800, H = 220;
  const path = (key, color) => {
    const pts = data.map((d, i) => `${(i / 89) * W},${H - (d[key] / max) * H}`).join(' L ');
    return <path d={`M ${pts}`} fill="none" stroke={color} strokeWidth="2" />;
  };
  return (
    <div style={{ overflowX: 'auto' }}>
      <svg viewBox={`0 0 ${W} ${H + 20}`} style={{ width: '100%', minWidth: 600, height: 240 }}>
        {[0, 0.25, 0.5, 0.75, 1].map(p => <line key={p} x1="0" y1={H * p} x2={W} y2={H * p} stroke="rgba(255,255,255,.05)" />)}
        {path('total', '#52F20F')}
        {path('good', '#FFD700')}
        {path('bad', '#ef4444')}
      </svg>
      <div style={{ display: 'flex', gap: 16, fontSize: 11, marginTop: 8 }}>
        <span><span style={{ display: 'inline-block', width: 10, height: 10, background: '#52F20F', borderRadius: 2, marginRight: 6 }}></span>Total</span>
        <span><span style={{ display: 'inline-block', width: 10, height: 10, background: '#FFD700', borderRadius: 2, marginRight: 6 }}></span>Cu rating bun</span>
        <span><span style={{ display: 'inline-block', width: 10, height: 10, background: '#ef4444', borderRadius: 2, marginRight: 6 }}></span>Cu rating slab</span>
      </div>
    </div>
  );
}

window.AdminAiPage = AdminAiPage;
