// AI Asistent — chat layout so zachovaním všetkých sekcií z existujúceho nástroja

function AiSidebar() {
  const main = [
    { id:'chat', label:'Chat', ico:<Ico.ai className="ico"/> },
    { id:'new',  label:'Nový chat', ico:<Ico.plus className="ico"/> },
    { id:'overview', label:'Prehľad', ico:<Ico.dashboard className="ico"/> },
  ];
  const admin = [
    { id:'skills-b', label:'Skill Builder', ico:<Ico.sparkles className="ico"/> },
    { id:'tasks',    label:'Plánované úlohy', ico:<Ico.construction className="ico"/> },
    { id:'skills',   label:'Skills', ico:<Ico.check className="ico"/>, badge:'24' },
    { id:'fns',      label:'Funkcie AI', ico:<Ico.modules className="ico"/> },
    { id:'know',     label:'Znalosti', ico:<Ico.datasheet className="ico"/> },
    { id:'users',    label:'Používatelia', ico:<Ico.users className="ico"/> },
    { id:'stats',    label:'Štatistiky', ico:<Ico.dashboard className="ico"/> },
    { id:'int',      label:'Integrácie', ico:<Ico.grid className="ico"/>, badge:'8' },
    { id:'cfg',      label:'Nastavenia', ico:<Ico.settings className="ico"/> },
  ];
  return (
    <aside className="sidebar" style={{width:220}}>
      <div className="sb-logo"><Logo/><div className="sb-logo-text">D&amp;D Energy<small>AI Asistent</small></div></div>
      <div style={{padding:'8px 8px 0'}}>
        <a style={{display:'flex', alignItems:'center', gap:8, padding:'7px 10px', borderRadius:6, fontSize:12, color:'#b8c9e0', cursor:'pointer', border:'1px solid rgba(255,255,255,0.1)', background:'rgba(255,255,255,0.03)'}}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"/></svg>
          <span>Späť na prehľad CRM</span>
        </a>
      </div>
      <div className="sb-nav">
        <div className="sb-section">Konverzácie</div>
        {main.map(it => (
          <a key={it.id} className={it.id==='chat'?'active':''}>{it.ico}<span>{it.label}</span></a>
        ))}
        <div style={{padding:'8px 14px 4px'}}>
          <div className="small" style={{color:'#6a8bb3', fontWeight:600, letterSpacing:'0.14em', textTransform:'uppercase', fontSize:10}}>Nedávne</div>
          <div className="vstack" style={{gap:2, marginTop:4}}>
            {['Cenová analýza Huawei','Export FV zostáv CSV','Servisný plán apríl','Správa B2B partnerov'].map(t=>(
              <a key={t} style={{fontSize:12, color:'#b8c9e0', padding:'5px 10px', borderRadius:6, cursor:'pointer'}} onMouseEnter={e=>e.currentTarget.style.background='rgba(255,255,255,0.04)'} onMouseLeave={e=>e.currentTarget.style.background='transparent'}>{t}</a>
            ))}
          </div>
        </div>
        <div className="sb-section" style={{marginTop:8}}>Administrácia</div>
        {admin.map(it => (
          <a key={it.id}>{it.ico}<span>{it.label}</span>{it.badge && <span className="badge" style={{background:'rgba(246,191,71,0.2)', color:'#f6bf47'}}>{it.badge}</span>}</a>
        ))}
      </div>
      <div className="sb-user">
        <div className="sb-avatar">DK</div>
        <div style={{minWidth:0, flex:1}}><div className="sb-user-name">Dávid K.</div><div className="sb-user-role">Administrátor</div></div>
        <Ico.logout style={{color:'#8ea8c9', cursor:'pointer'}}/>
      </div>
    </aside>
  );
}

function AiAssistant() {
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [tier, setTier] = React.useState('auto');
  const [lastModel, setLastModel] = React.useState(null);
  const [pickedBy, setPickedBy] = React.useState(null);
  const [notConfigured, setNotConfigured] = React.useState(false);
  const scrollRef = React.useRef(null);

  const canChat = window.hasPerm ? window.hasPerm('ai.view') : true;

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, sending]);

  const suggestions = [
    { t: 'Zhrň mi dnešné objednávky.',             hint: 'fast' },
    { t: 'Ktoré produkty sú vypredané?',           hint: 'fast' },
    { t: 'Analyzuj pokles predaja batérií v marci a navrhni, čo urobiť.', hint: 'best' },
    { t: 'Porovnaj marže Huawei a GoodWe meničov.', hint: 'balanced' },
    { t: 'Napíš krátky e-mail zákazníkovi s pripomenutím platby.', hint: 'fast' },
    { t: 'Sprav mi detailný plán obsahu webu na Q2.', hint: 'best' },
  ];

  async function send(promptText) {
    const text = (promptText ?? input).trim();
    if (!text || sending) return;

    const userMsg = { role: 'user', content: text };
    const history = [...messages, userMsg];
    setMessages(history);
    setInput('');
    setSending(true);

    const payload = {
      messages: history,
      system: 'Si interný asistent pre D&D Energy (solárne systémy, e-shop na WooCommerce). Odpovedaj v slovenčine, stručne a presne. Ak ide o otázku ohľadom dát z WooCommerce/WordPress/SuperFaktúry, uveď, že reálne nástroje pre volanie týchto API doplníme v ďalšom kroku — zatiaľ pracuj s kontextom, ktorý máš.',
      maxTokens: 1024,
    };
    if (tier !== 'auto') payload.speedHint = tier;

    const r = await API.aiChat(payload);
    setSending(false);

    if (r.status === 200 && r.body.ok) {
      setLastModel(r.body.modelLabel || r.body.model);
      setPickedBy(r.body.pickedBy || 'auto');
      setMessages([...history, { role: 'assistant', content: r.body.text, model: r.body.modelLabel }]);
    } else if (r.body.error === 'anthropic_not_configured') {
      setNotConfigured(true);
      setMessages([...history, { role: 'assistant', content: '⚠️ Anthropic API kľúč nie je nakonfigurovaný. Otvorte Integrácie a pridajte ho.', error: true }]);
    } else if (r.body.error === 'forbidden') {
      setMessages([...history, { role: 'assistant', content: 'Nemáte oprávnenie používať AI asistenta (potrebné `ai.view`).', error: true }]);
    } else {
      setMessages([...history, { role: 'assistant', content: 'Chyba: ' + (r.body.message || r.body.error || 'neznáma'), error: true }]);
    }
  }

  function onKey(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  }

  return (
    <div className="app">
      <AiSidebar/>
      <div className="main">
        <div className="topbar" style={{gap:10}}>
          <div className="crumbs">
            <span style={{color:'var(--navy-700)'}}>CRM</span>
            <span className="sep">/</span>
            <span>AI Asistent</span>
            <span className="sep">/</span>
            <b>{messages.length ? 'Chat' : 'Nový chat'}</b>
          </div>
          <div className="hstack" style={{marginLeft:14}}>
            <div className="seg" title="Tier — Auto vyberie model podľa obsahu otázky">
              <button className={tier === 'auto'     ? 'active' : ''} onClick={() => setTier('auto')}>Auto</button>
              <button className={tier === 'fast'     ? 'active' : ''} onClick={() => setTier('fast')}>Haiku</button>
              <button className={tier === 'balanced' ? 'active' : ''} onClick={() => setTier('balanced')}>Sonnet</button>
              <button className={tier === 'best'     ? 'active' : ''} onClick={() => setTier('best')}>Opus</button>
            </div>
            {lastModel && (
              <span className="small muted" title={`Posledná odpoveď — vybratý ${pickedBy === 'auto' ? 'automaticky' : pickedBy}`}>
                → <b style={{color:'var(--navy-700)'}}>{lastModel}</b>
              </span>
            )}
          </div>
          <div style={{marginLeft:'auto'}} className="hstack">
            <button className="btn btn-sm" onClick={() => { setMessages([]); setLastModel(null); setPickedBy(null); }}><Ico.plus/>Nový chat</button>
          </div>
        </div>

        <div className="content" style={{display:'flex', flexDirection:'column', padding:0, background:'var(--bg)'}}>
          <div ref={scrollRef} style={{flex:1, overflow:'auto', padding:'24px 20px'}}>
            {messages.length === 0 ? (
              <div style={{maxWidth:760, margin:'40px auto 0', textAlign:'center'}}>
                <div style={{width:64, height:64, borderRadius:16, background:'linear-gradient(135deg, var(--navy-800), var(--navy-500))', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 18px', boxShadow:'0 8px 30px rgba(19,50,88,0.3)', color:'#fff'}}>
                  <Ico.sparkles style={{width:28, height:28}}/>
                </div>
                <h2 style={{margin:0, fontSize:24, fontWeight:700}}>Ako vám dnes pomôžem?</h2>
                <p style={{fontSize:13.5, color:'var(--ink-500)', margin:'6px 0 24px'}}>
                  Režim <b>Auto</b> sám vyberie Haiku/Sonnet/Opus podľa zložitosti otázky.
                  Pre rýchle odpovede (jednovetové otázky, klasifikácia, preklad) použije Haiku.
                  Pre bežné úlohy Sonnet, pre hlbokú analýzu Opus.
                </p>
                {notConfigured && (
                  <div style={{background:'var(--red-100)', border:'1px solid #fecaca', color:'#7c1d1d', padding:'12px 16px', borderRadius:10, marginBottom:20}}>
                    Anthropic API nie je nastavené. <a href="#/integrations" style={{color:'#7c1d1d', fontWeight:600}}>Otvorte Integrácie</a> a pridajte API kľúč.
                  </div>
                )}
                <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))', gap:10, maxWidth:760}}>
                  {suggestions.map((x, i) => (
                    <button key={i} className="card" style={{padding:'10px 12px', textAlign:'left', cursor:'pointer', borderColor:'var(--border)', background:'#fff'}} onClick={() => send(x.t)}>
                      <div style={{fontSize:12.5, fontWeight:500, color:'var(--ink-900)'}}>{x.t}</div>
                      <div className="small muted" style={{marginTop:3}}>Očakávaný model: <b>{x.hint === 'fast' ? 'Haiku' : x.hint === 'best' ? 'Opus' : 'Sonnet'}</b></div>
                    </button>
                  ))}
                </div>
              </div>
            ) : (
              <div style={{maxWidth:820, margin:'0 auto'}}>
                {messages.map((m, i) => (
                  <div key={i} style={{display:'flex', gap:12, marginBottom:16, alignItems:'flex-start'}}>
                    <div style={{
                      width:32, height:32, borderRadius:8, flexShrink:0,
                      background: m.role === 'user' ? 'var(--navy-700)' : 'linear-gradient(135deg, var(--amber-500), var(--amber-400))',
                      color: m.role === 'user' ? '#fff' : '#1a1200',
                      display:'flex', alignItems:'center', justifyContent:'center',
                      fontWeight:700, fontSize:12,
                    }}>{m.role === 'user' ? 'JA' : 'AI'}</div>
                    <div style={{flex:1}}>
                      <div className="small muted" style={{marginBottom:2}}>
                        {m.role === 'user' ? 'Vy' : 'Asistent'}{m.model && <> · <b style={{color:'var(--navy-700)'}}>{m.model}</b></>}
                      </div>
                      <div style={{
                        background:'#fff', border:'1px solid var(--border)', borderRadius:10, padding:'10px 14px',
                        whiteSpace:'pre-wrap', fontSize:13.5, lineHeight:1.55,
                        color: m.error ? 'var(--red-500)' : 'var(--ink-900)',
                      }}>{m.content}</div>
                    </div>
                  </div>
                ))}
                {sending && (
                  <div style={{display:'flex', gap:12, alignItems:'flex-start'}}>
                    <div style={{width:32, height:32, borderRadius:8, background:'linear-gradient(135deg, var(--amber-500), var(--amber-400))', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:12, color:'#1a1200'}}>AI</div>
                    <div style={{flex:1}}>
                      <div className="small muted" style={{marginBottom:2}}>Asistent premýšľa…</div>
                      <div style={{background:'#fff', border:'1px solid var(--border)', borderRadius:10, padding:'10px 14px', color:'var(--ink-500)'}}>
                        <span className="typing">● ● ●</span>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>

          <div style={{padding:'12px 20px 18px', background:'var(--bg)', borderTop:'1px solid var(--border)'}}>
            <div style={{maxWidth:820, margin:'0 auto', background:'#fff', border:'1px solid var(--border-strong)', borderRadius:12, padding:10, boxShadow:'var(--shadow-sm)'}}>
              <textarea
                placeholder={canChat ? "Napíšte správu… (Enter = odoslať, Shift+Enter = nový riadok)" : "Pre použitie AI potrebujete oprávnenie ai.view"}
                style={{width:'100%', border:'none', outline:'none', resize:'none', fontFamily:'var(--font)', fontSize:13.5, minHeight:42, padding:'4px 6px'}}
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={onKey}
                disabled={!canChat || sending}
              />
              <div className="hstack" style={{marginTop:6}}>
                <span className="small muted">Tier: <b style={{color:'var(--navy-700)'}}>{tier === 'auto' ? 'Auto' : tier}</b></span>
                <div style={{marginLeft:'auto'}} className="hstack">
                  <button
                    className="btn btn-primary btn-sm"
                    style={{width:32, padding:0, justifyContent:'center'}}
                    onClick={() => send()}
                    disabled={!canChat || sending || !input.trim()}
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
                  </button>
                </div>
              </div>
            </div>
            <div className="small muted" style={{textAlign:'center', marginTop:6}}>
              Odpovede môžu byť nepresné. Dôležité údaje overte v zdrojovom systéme.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AiAssistant });
