/* Composer — text area + tools row + mode pills + send */

const MODE_META = {
  chat:         { label: 'Conversar',    icon: 'chat',    desc: 'Resposta direta' },
  agent:        { label: 'Agêntico',     icon: 'bolt',    desc: 'Com ferramentas e skills' },
  deepresearch: { label: 'Deep Research',icon: 'search',  desc: 'Pesquisa na internet em tempo real (máx 3 rounds)' },
  pecas:        { label: 'Peças',        icon: 'process', desc: 'Criação de peças processuais de alto nível' },
  recursos:     { label: 'Recursos',     icon: 'scale',   desc: 'Recursos processuais com técnicas avançadas' },
  revisao:      { label: 'Revisão',      icon: 'check',   desc: 'Auditoria premium antes do protocolo' },
  calculos:     { label: 'Cálculos',     icon: 'calc',    desc: 'Liquidação cível e trabalhista' },
  adversarial:  { label: 'Adversarial',  icon: 'eye',     desc: 'Forças, fraquezas e riscos da tese' },
  sustentacao:  { label: 'Sustentação',  icon: 'mic',     desc: 'Roteiro de sustentação oral' },
  audiencia:    { label: 'Audiência',    icon: 'user',    desc: 'Perguntas para testemunhas e partes' },
  sentenca:     { label: 'Sentença',     icon: 'book',    desc: 'Simulação judicial provável' },
  quesitos:     { label: 'Quesitos',     icon: 'calc',    desc: 'Perícia e assistente técnico' },
  audio:        { label: 'Áudio',        icon: 'mic',     desc: 'Transcrição e análise com timestamps' },
  relatorio:    { label: 'Relatório',    icon: 'relatorio', desc: 'Resumo folha a folha ou ID a ID do processo' },
};

const ModePicker = ({ mode, onMode }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const current = MODE_META[mode] || MODE_META.chat;
  const CurIc = I[current.icon];

  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  return (
    <div className="mode-picker-wrap" ref={ref}>
      <button
        className={`mode-trigger ctool ${open ? 'open' : ''}`}
        onClick={() => setOpen(v => !v)}
        title="Selecionar modo"
      >
        <CurIc size={13}/>
        <span className="ctool-label mode-trigger-label">{current.label}</span>
        <svg width="9" height="9" viewBox="0 0 10 10" style={{marginLeft:1,opacity:.5,transform: open ? 'rotate(180deg)' : 'none', transition:'transform .18s'}}>
          <path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round"/>
        </svg>
      </button>
      {open && (
        <div className="mode-dropdown" role="menu">
          <div className="mode-dropdown-header">Modo de operação</div>
          {Object.entries(MODE_META).map(([k, m]) => {
            const Ic = I[m.icon];
            const active = mode === k;
            return (
              <button key={k} className={`mode-opt ${active ? 'active' : ''}`}
                      role="menuitem"
                      onClick={() => { onMode(k); setOpen(false); }}>
                <span className="mode-opt-icon"><Ic size={14}/></span>
                <span className="mode-opt-body">
                  <span className="mode-opt-label">{m.label}</span>
                  <span className="mode-opt-desc">{m.desc}</span>
                </span>
                {active && (
                  <svg width="14" height="14" viewBox="0 0 14 14" style={{marginLeft:'auto',flexShrink:0,color:'var(--ink)'}}>
                    <path d="M2.5 7L5.5 10L11.5 4" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
};

const Composer = ({ value, onChange, onSend, mode, onMode, busy, streaming, onStop, attachments, onRemoveAttach,
                    centered, onAttachClick, onMicClick, onRefineClick, onTemplateClick,
                    onPdfToolsClick, onImportBridgeClick, bridge, templateInfo, onFormattingClick, onStyleClick, styleInfo }) => {
  const taRef = React.useRef(null);
  React.useEffect(() => {
    const ta = taRef.current;
    if (!ta) return;
    ta.style.height = 'auto';
    ta.style.height = Math.min(220, ta.scrollHeight) + 'px';
  }, [value]);

  const handleKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (value.trim() && !busy && !streaming) onSend();
    }
  };

  return (
    <div className={`composer-wrap ${centered ? 'centered' : 'docked'}`}>
      <div className="composer">
        {attachments && attachments.length > 0 && (
          <div className="attach-row">
            {attachments.map((a, i) => (
              <span key={i} className="chip">
                <I.attach size={11}/>
                {a.name}
                <button onClick={() => onRemoveAttach(i)}><I.x size={10} sw={2}/></button>
              </span>
            ))}
          </div>
        )}
        <textarea
          ref={taRef}
          rows={1}
          value={value}
          placeholder="Pergunte algo ao SynapIA…  (Enter envia · Shift+Enter quebra linha · / para comandos)"
          onChange={e => onChange(e.target.value)}
          onKeyDown={handleKey}
        />
        <div className="composer-row">
          <div className="composer-tools">
            <ModePicker mode={mode} onMode={onMode}/>
            <span className="ctool-sep"/>
            <button className="ctool" title="Anexar arquivos" onClick={onAttachClick}>
              <I.attach size={13}/>
            </button>
            <button className="ctool" title="OCR / Ferramentas PDF" onClick={onPdfToolsClick}>
              <I.scan size={13}/>
            </button>
            <button className="ctool" title="Refinar prompt" onClick={onRefineClick}>
              <I.refine size={13}/>
            </button>
            <button className="ctool" title="Ditar por voz" onClick={onMicClick}>
              <I.mic size={13}/>
            </button>
            <button className="ctool" title={templateInfo ? 'Template ativo: ' + templateInfo.nome : 'Template Word (timbre e formatação)'} onClick={onTemplateClick}>
              <I.file size={13}/> <span className="ctool-label" style={templateInfo ? {color: 'var(--success)'} : {}}>{templateInfo ? 'Timbre ✓' : 'Timbre'}</span>
            </button>
            <button className="ctool" title={styleInfo?.profile_disponivel ? `Estilo aprendido: ${styleInfo.total || 0} amostra(s)` : 'Aprender e salvar estilo de escrita'} onClick={onStyleClick}>
              <I.brain size={13}/> <span className="ctool-label" style={styleInfo?.profile_disponivel ? {color: 'var(--success)'} : {}}>{styleInfo?.profile_disponivel ? 'Estilo ✓' : 'Estilo'}</span>
            </button>
            <button className="ctool" title="Fonte, espaçamento, margens" onClick={onFormattingClick}>
              <I.settings size={13}/> <span className="ctool-label">Formato</span>
            </button>
          </div>
          {streaming ? (
            <button className="btn-send ready" onClick={onStop} title="Parar geração">
              <div style={{width: 10, height: 10, background: 'currentColor', borderRadius: 1}} />
            </button>
          ) : (
            <button
              className={`btn-send ${value.trim() ? 'ready' : ''}`}
              onClick={onSend}
              disabled={!value.trim() || busy}
              title="Enviar"
            >
              {busy
                ? <span className="bs-dots"><span/><span/><span/></span>
                : <I.arrowUp size={15} sw={2.4}/>}
            </button>
          )}
        </div>
      </div>
      <div className="composer-foot">
        SynapIA pode errar. Verifique citações, prazos, súmulas e jurisprudências em fontes oficiais.
      </div>
    </div>
  );
};

window.Composer = Composer;
window.MODE_META = MODE_META;
