// chat.jsx — AI Chat page

const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

function ChatPage({ onNav, user }) {
  const [convs, setConvs] = useStateC([
    { id: 1, title: 'Strategii pentru ore peak', last: 'Acum 2h', msgs: [
      { role: 'user', text: 'Care sunt cele mai bune ore pentru a face live în România?' },
      { role: 'ai', text: 'Pentru audiența RO, ferestrele cele mai active sunt: 19:00–22:00 (peak prime-time), 12:00–14:00 (pauza de prânz), și 22:30–01:00 (audiență tânără, engagement mai ridicat). Recomand să rulezi 2–3 sloturi diferite o săptămână și să compari diamantele/oră — vei găsi sweet-spot-ul tău personal.' },
    ]},
    { id: 2, title: 'Cum cresc retenția în primele 60s', last: 'Ieri', msgs: [] },
    { id: 3, title: 'Pachet pentru un brand de cosmetice', last: '3 zile', msgs: [] },
  ]);
  const [active, setActive] = useStateC(1);
  const [input, setInput] = useStateC('');
  const [typing, setTyping] = useStateC(false);
  const scrollRef = useRefC(null);

  const conv = convs.find(c => c.id === active);
  const empty = !conv || conv.msgs.length === 0;

  useEffectC(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [conv?.msgs?.length, typing]);

  const send = (text) => {
    const t = (text || input).trim(); if (!t) return;
    const newMsg = { role: 'user', text: t };
    setConvs(cs => cs.map(c => c.id === active ? { ...c, msgs: [...c.msgs, newMsg] } : c));
    setInput('');
    setTyping(true);
    setTimeout(() => {
      const reply = generateReply(t);
      setConvs(cs => cs.map(c => c.id === active ? { ...c, msgs: [...c.msgs, { role: 'ai', text: reply }] } : c));
      setTyping(false);
    }, 1400);
  };

  const newConv = () => {
    const id = Date.now();
    setConvs(cs => [{ id, title: 'Conversație nouă', last: 'acum', msgs: [] }, ...cs]);
    setActive(id);
  };

  const suggestions = [
    { ico: '📈', label: 'Cum cresc audiența mea?' },
    { ico: '⏰', label: 'Cele mai bune ore de live' },
    { ico: '💎', label: 'Cum maximizez diamantele' },
    { ico: '🎯', label: 'Strategii pentru meciuri' },
  ];

  return (
    <div className="page" style={{ display: 'grid', gridTemplateColumns: '260px 280px 1fr', minHeight: '100vh', height: '100vh' }} className="chat-layout">
      <DashSidebar active="chat" onNav={onNav} user={user} />

      {/* Conversations sidebar */}
      <aside style={{ background: '#0B0B10', borderRight: '.5px solid var(--line-soft)', padding: 20, display: 'flex', flexDirection: 'column', gap: 12, overflowY: 'auto' }}>
        <button onClick={newConv} className="btn btn-primary" style={{ width: '100%' }}>+ Conversație nouă</button>
        <input className="input" placeholder="Caută în conversații..." style={{ height: 36 }}/>
        <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginTop: 8 }}>RECENTE</div>
        {convs.map(c => (
          <button key={c.id} onClick={() => setActive(c.id)} style={{
            textAlign: 'left', padding: '12px 14px', borderRadius: 10, border: 0, cursor: 'pointer',
            background: active === c.id ? 'rgba(82,242,15,.08)' : 'transparent',
            color: 'var(--txt-1)', fontFamily: 'inherit', transition: 'background .18s',
          }} onMouseEnter={(e) => { if (active !== c.id) e.currentTarget.style.background = 'rgba(255,255,255,.03)'; }}
             onMouseLeave={(e) => { if (active !== c.id) e.currentTarget.style.background = 'transparent'; }}>
            <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.title}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', marginTop: 4 }}>{c.last}</div>
          </button>
        ))}
      </aside>

      {/* Chat zone */}
      <main style={{ display: 'flex', flexDirection: 'column', background: 'var(--bg-1)', minHeight: 0 }}>
        <div style={{ padding: '20px 32px', borderBottom: '.5px solid var(--line-soft)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: 'linear-gradient(135deg, var(--accent-1), var(--accent-2))', display: 'grid', placeItems: 'center', fontSize: 20, color: '#0A0A0F', fontWeight: 700 }}>✦</div>
            <div>
              <div style={{ fontWeight: 600 }}>4U Assistant</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: 'var(--txt-3)' }}>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--success)', boxShadow: '0 0 8px var(--success)', animation: 'pulse 1.6s infinite' }}/>
                Online · Claude Sonnet · trained pe knowledge base 4U
              </div>
            </div>
          </div>
          <button className="btn btn-glass btn-sm">Setări conversație</button>
        </div>

        <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '32px 0' }}>
          {empty ? (
            <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 48, position: 'relative' }}>
              <Mesh />
              <div style={{ position: 'relative', zIndex: 2, textAlign: 'center', maxWidth: 720 }}>
                <div style={{ width: 72, height: 72, borderRadius: 18, background: 'linear-gradient(135deg, var(--accent-1), var(--accent-2))', display: 'grid', placeItems: 'center', fontSize: 36, color: '#0A0A0F', fontWeight: 700, margin: '0 auto 24px', boxShadow: '0 0 60px rgba(82,242,15,.4)' }}>✦</div>
                <h2 className="display" style={{ fontSize: 40, margin: 0 }}>Cu ce te pot ajuta astăzi?</h2>
                <p style={{ color: 'var(--txt-2)', fontSize: 15, marginTop: 12 }}>Întreabă-mă orice despre TikTok Live, strategii, monetizare, sau procesele din 4U.</p>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, marginTop: 40 }}>
                  {suggestions.map((s, i) => (
                    <button key={i} onClick={() => send(s.label)} className="card" style={{ padding: 18, textAlign: 'left', cursor: 'pointer', border: '.5px solid var(--line)', background: 'var(--bg-2)' }}>
                      <div style={{ fontSize: 20, marginBottom: 8 }}>{s.ico}</div>
                      <div style={{ fontSize: 14 }}>{s.label}</div>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          ) : (
            <div style={{ maxWidth: 760, margin: '0 auto', padding: '0 24px', display: 'flex', flexDirection: 'column', gap: 20 }}>
              {conv.msgs.map((m, i) => <ChatBubble key={i} {...m} />)}
              {typing && <ChatBubble role="ai" typing />}
            </div>
          )}
        </div>

        <div style={{ padding: '20px 32px 24px', borderTop: '.5px solid var(--line-soft)' }}>
          <div style={{ maxWidth: 760, margin: '0 auto' }}>
            {!empty && (
              <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
                {['Detalii →', 'Dă-mi exemple', 'Cum o aplic?'].map(s => (
                  <button key={s} onClick={() => send(s)} className="pill" style={{ cursor: 'pointer' }}>{s}</button>
                ))}
              </div>
            )}
            <form onSubmit={(e) => { e.preventDefault(); send(); }} style={{ position: 'relative' }}>
              <textarea
                rows={1} value={input} onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }}}
                placeholder="Scrie un mesaj..."
                style={{
                  width: '100%', resize: 'none', padding: '16px 60px 16px 20px',
                  background: 'var(--bg-2)', border: '.5px solid var(--line)', borderRadius: 14,
                  color: 'var(--txt-0)', fontSize: 15, fontFamily: 'inherit', outline: 'none',
                  minHeight: 54, maxHeight: 200,
                }}
                onFocus={(e) => e.target.style.borderColor = 'var(--accent-1)'}
                onBlur={(e) => e.target.style.borderColor = 'var(--line)'}
              />
              <button type="submit" className="btn btn-primary" style={{ position: 'absolute', right: 8, bottom: 8, width: 38, height: 38, padding: 0, borderRadius: 10 }}>↑</button>
            </form>
            <div className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', marginTop: 8, textAlign: 'center' }}>4U Assistant poate face greșeli. Verifică info importantă.</div>
          </div>
        </div>
      </main>
      <style>{`@media (max-width: 1100px) { .chat-layout { grid-template-columns: 0 280px 1fr !important; } .dash-sidebar { display: none !important; }}`}</style>
    </div>
  );
}

function ChatBubble({ role, text, typing }) {
  const isUser = role === 'user';
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', justifyContent: isUser ? 'flex-end' : 'flex-start' }}>
      {!isUser && (
        <div style={{ width: 32, height: 32, borderRadius: 8, background: 'linear-gradient(135deg, var(--accent-1), var(--accent-2))', display: 'grid', placeItems: 'center', fontSize: 14, color: '#0A0A0F', fontWeight: 700, flexShrink: 0 }}>✦</div>
      )}
      <div style={{
        maxWidth: '78%', padding: '14px 18px', borderRadius: 14,
        background: isUser ? 'rgba(82,242,15,.1)' : 'var(--bg-2)',
        border: isUser ? '.5px solid rgba(82,242,15,.25)' : '.5px solid var(--line)',
        color: 'var(--txt-0)', fontSize: 14.5, lineHeight: 1.6,
      }}>
        {typing ? (
          <div style={{ display: 'flex', gap: 4, padding: '4px 0' }}>
            {[0, 1, 2].map(i => <span key={i} style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--accent-1)', animation: `tdot 1.4s ${i * 0.2}s infinite` }}/>)}
            <style>{`@keyframes tdot { 0%, 60%, 100% { opacity: 0.3; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-3px); }}`}</style>
          </div>
        ) : text}
      </div>
      {isUser && <div style={{ width: 32, height: 32, borderRadius: 999, background: 'linear-gradient(135deg, var(--accent-2), var(--accent-1))', flexShrink: 0 }}/>}
    </div>
  );
}

function generateReply(prompt) {
  const p = prompt.toLowerCase();
  if (p.includes('audien') || p.includes('cre')) return 'Trei pârghii principale pentru creșterea audienței: (1) Consistență — minim 5 zile/săptămână în același slot orar, (2) Hook în primele 30s — promite ceva specific care reține (ex: "În următoarele 10 minute îți arăt cum am făcut 50K diamante într-o noapte"), (3) Cross-promo cu alți creatori 4U — fă duete și colab live cu cei din nivelul tău. Vrei să detaliez vreuna?';
  if (p.includes('or')) return 'Ferestrele optime pentru audiența RO sunt 19:00–22:00 (peak), 12:00–14:00 și 22:30–01:00. Recomand să testezi 2–3 sloturi pentru o săptămână și să măsori diamantele/oră.';
  if (p.includes('diamant')) return 'Diamantele cresc cu retenție + tip-uri. Ce funcționează best: provocări vizibile pe ecran ("La 1.000 de diamante fac X"), countere live, și interacțiune directă cu top tipperii (răspunde-le pe nume, mulțumește pe loc).';
  if (p.includes('meci')) return 'Pentru meciuri oficiale: (1) Cunoaște-ți slot-ul advers înainte, (2) Mobilizează core-ul cu 24h înainte (story + push), (3) Ține o rezervă de "tip booster" (cineva care intră masiv la 80% din timp). Vrei să te conectez cu un coach de meciuri?';
  if (p.includes('exempl') || p.includes('detal')) return 'Dă-mi un context: ce nivel ești, câte ore live faci în prezent și care e obiectivul tău pe luna asta? Pot să-ți dau exemple mult mai relevante așa.';
  return 'Bună observație. Dă-mi puțin mai mult context — de când ești pe TikTok, ce nișă, și care e cel mai mare blocaj acum? Răspund mult mai precis cu detaliile astea.';
}

window.ChatPage = ChatPage;
