// PAC Sistema — Biblioteca de Skills, Prompts e Scripts
// Compartilhada entre toda a equipe. Editar/excluir só o autor (ou socio_admin).

const KIND_META = {
  skill:  { label: 'Skills',  singular: 'Skill',  icon: 'sparkles', accent: '#C8FF00', tip: 'Habilidades plugáveis para o Claude. Inclui frontmatter (name, description) + corpo em markdown.' },
  prompt: { label: 'Prompts', singular: 'Prompt', icon: 'fileText', accent: '#8B5CF6', tip: 'Templates de instruções para usar no chat. Pode ter variáveis em chaves: {cliente}, {caso}.' },
  script: { label: 'Scripts', singular: 'Script', icon: 'terminal', accent: '#3B82F6', tip: 'Trechos de código, automações, snippets úteis para colar em qualquer lugar.' },
};

const fmtDateLib = (iso) => iso ? new Date(iso).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric' }) : '';
const fmtSize = (b) => !b ? '' : b < 1024 ? `${b} B` : b < 1024*1024 ? `${(b/1024).toFixed(0)} KB` : `${(b/(1024*1024)).toFixed(1)} MB`;

// ============================================================
// Modal: como instalar no Claude (web/desktop)
// ============================================================
const InstallHelpModal = ({ onClose }) => (
  <div className="scrim" onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(26,10,46,.55)', zIndex:420, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}>
    <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:14, width:'100%', maxWidth:620, maxHeight:'88vh', overflow:'auto', padding:26, boxShadow:'0 20px 60px rgba(0,0,0,.3)' }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18 }}>
        <div>
          <h2 style={{ fontSize:19, fontWeight:800, color:'var(--pac-navy)', fontFamily:'Georgia,serif', margin:0 }}>Como instalar uma Skill no Claude</h2>
          <p style={{ fontSize:12, color:'#888', margin:'3px 0 0' }}>Vale para Claude.ai (web) e Claude Desktop</p>
        </div>
        <button onClick={onClose} style={{ border:0, background:'transparent', fontSize:24, color:'#999', cursor:'pointer', lineHeight:1 }}>×</button>
      </div>

      <ol style={{ paddingLeft:18, fontSize:13.5, color:'#1a1a2e', lineHeight:1.65 }}>
        <li style={{ marginBottom:14 }}>
          <b>Baixe ou copie a skill</b> daqui da biblioteca:
          <ul style={{ marginTop:4, paddingLeft:18, color:'#666' }}>
            <li>Se houver arquivo anexado, clique em <b>Baixar</b> no card.</li>
            <li>Se for só texto, clique em <b>Copiar conteúdo</b>.</li>
          </ul>
        </li>
        <li style={{ marginBottom:14 }}>
          <b>Abra o Claude</b> em <a href="https://claude.ai" target="_blank" rel="noreferrer" style={{ color:'var(--pac-navy)' }}>claude.ai</a> (web ou app Desktop).
        </li>
        <li style={{ marginBottom:14 }}>
          No menu lateral esquerdo, vá em <b>Configurações</b> (ícone de engrenagem) → <b>Capabilities</b> → <b>Skills</b>.
          <div style={{ marginTop:4, fontSize:12, color:'#888' }}>No Desktop o caminho é igual. Em alguns planos pode aparecer como <i>“Capabilities → Skills”</i> na barra inferior do chat.</div>
        </li>
        <li style={{ marginBottom:14 }}>
          Clique em <b>Create Skill</b> (ou <b>Upload Skill</b>):
          <ul style={{ marginTop:4, paddingLeft:18, color:'#666' }}>
            <li><b>Se você copiou o conteúdo</b>: cole no campo de texto. O Claude lê o frontmatter (<code style={{ background:'#f4f4f8', padding:'1px 4px', borderRadius:3 }}>--- name: … ---</code>) e os passos do markdown.</li>
            <li><b>Se você baixou um .md</b>: arraste o arquivo para a área de upload.</li>
            <li><b>Se você baixou um .docx</b>: abra no Word/Pages, copie o texto e cole. O Claude não lê .docx direto em Skills.</li>
          </ul>
        </li>
        <li style={{ marginBottom:14 }}>
          <b>Salve a skill</b>. Ela aparecerá na lista de skills disponíveis e ficará ativa nos próximos chats.
        </li>
        <li style={{ marginBottom:14 }}>
          <b>Para usar:</b> mencione a skill no chat ("rode a skill X") ou ative-a no menu de capabilities. Para usar dentro do <b>Cowork</b>, abra a sessão Cowork e a skill já estará disponível pra você invocar.
        </li>
      </ol>

      <div style={{ background:'rgba(200,255,0,.13)', border:'1px solid rgba(200,255,0,.4)', borderRadius:8, padding:'12px 14px', fontSize:12.5, color:'#1a1a2e', marginTop:8 }}>
        <b>Para Prompts e Scripts</b> o caminho é diferente: <b>Prompts</b> você cola direto no chat (ou usa "Projects" se for recorrente). <b>Scripts</b> você usa no terminal/editor — não vão em Skills do Claude.
      </div>

      <div style={{ display:'flex', justifyContent:'flex-end', marginTop:18 }}>
        <button onClick={onClose} style={{ padding:'9px 18px', borderRadius:7, border:0, background:'var(--pac-navy)', color:'#fff', cursor:'pointer', fontSize:13, fontWeight:700 }}>Entendi</button>
      </div>
    </div>
  </div>
);

// ============================================================
// Modal: criar/editar item
// ============================================================
const LibItemModal = ({ item, defaultKind, onClose, onSaved }) => {
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [onClose]);
  const editing = !!item;
  const [kind, setKind] = React.useState(item?.kind || defaultKind || 'skill');
  const [title, setTitle] = React.useState(item?.title || '');
  const [description, setDescription] = React.useState(item?.description || '');
  const [content, setContent] = React.useState(item?.content_text || '');
  const [file, setFile] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [uploading, setUploading] = React.useState(false);
  const fileRef = React.useRef(null);

  const submit = async () => {
    if (!title.trim()) { setErr('Título é obrigatório.'); return; }
    setSaving(true); setErr('');
    try {
      const payload = {
        kind,
        title: title.trim(),
        description: description.trim() || null,
        content_text: content.trim() || null,
      };
      const saved = editing
        ? await window.PACApi.library.update(item.id, payload)
        : await window.PACApi.library.create(payload);
      if (file) {
        setUploading(true);
        try { await window.PACApi.library.uploadAttachment(saved.id, file); }
        catch (e) { setErr('Salvo, mas falhou ao anexar arquivo: ' + e.message); setUploading(false); setSaving(false); return; }
        setUploading(false);
      }
      onSaved(); onClose();
    } catch (e) {
      setErr(e.message || 'Erro ao salvar.');
    } finally {
      setSaving(false);
    }
  };

  const removeCurrentAttachment = () => setFile(null);

  const lbl = { display:'block', fontSize:11, fontWeight:700, color:'#666', marginBottom:5, textTransform:'uppercase', letterSpacing:'.06em' };
  const inp = { width:'100%', boxSizing:'border-box', padding:'10px 12px', border:'1.5px solid #ddd', borderRadius:8, fontSize:13, outline:'none' };

  return (
    <div className="scrim" onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(26,10,46,.55)', zIndex:410, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}>
      <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:14, width:'100%', maxWidth:640, maxHeight:'92vh', overflow:'auto', padding:24, boxShadow:'0 20px 60px rgba(0,0,0,.3)' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:18 }}>
          <h2 style={{ fontSize:18, fontWeight:800, color:'var(--pac-navy)', fontFamily:'Georgia,serif', margin:0 }}>
            {editing ? 'Editar item' : 'Novo item na biblioteca'}
          </h2>
          <button onClick={onClose} style={{ border:0, background:'transparent', fontSize:24, color:'#999', cursor:'pointer', lineHeight:1 }}>×</button>
        </div>

        {/* tipo */}
        <label style={lbl}>Tipo</label>
        <div style={{ display:'flex', gap:8, marginBottom:14 }}>
          {Object.entries(KIND_META).map(([k, m]) => (
            <button key={k} onClick={() => setKind(k)} style={{
              flex:1, padding:'10px 8px', borderRadius:7, fontSize:12.5, fontWeight:700, cursor:'pointer',
              border: kind === k ? '2px solid var(--pac-navy)' : '1px solid #ddd',
              background: kind === k ? 'rgba(13,13,107,.04)' : '#fff',
              color: kind === k ? 'var(--pac-navy)' : '#666',
            }}>{m.singular}</button>
          ))}
        </div>

        <label style={lbl}>Título</label>
        <input value={title} onChange={e => setTitle(e.target.value)} placeholder="Ex.: Geração de proposta PAC" autoFocus style={{ ...inp, marginBottom:14 }} />

        <label style={lbl}>Descrição / Explicação de uso</label>
        <textarea value={description} onChange={e => setDescription(e.target.value)} rows={3} placeholder="Para que serve, quando usar, com quais variáveis, etc." style={{ ...inp, resize:'vertical', fontFamily:'inherit', marginBottom:14 }} />

        <label style={lbl}>Conteúdo (opcional — texto/markdown)</label>
        <textarea value={content} onChange={e => setContent(e.target.value)} rows={8} placeholder={`Pode colar o conteúdo aqui (ou subir como arquivo abaixo).\n\nEx. de skill:\n---\nname: minha-skill\ndescription: ...\n---\n\n# Skill\nCorpo...`} style={{ ...inp, resize:'vertical', fontFamily:'ui-monospace, "SF Mono", Monaco, monospace', fontSize:12.5, marginBottom:14 }} />

        <label style={lbl}>Arquivo (opcional — .md, .docx, .pdf, .txt, .zip)</label>
        <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
          <button onClick={() => fileRef.current?.click()} style={{ padding:'9px 14px', borderRadius:7, border:'1.5px solid #ddd', background:'#fff', cursor:'pointer', fontSize:12.5, fontWeight:600 }}>Escolher arquivo</button>
          <input ref={fileRef} type="file" accept=".md,.markdown,.txt,.docx,.doc,.pdf,.zip" onChange={e => setFile(e.target.files?.[0] || null)} style={{ display:'none' }} />
          {file ? (
            <span style={{ fontSize:12.5, color:'#1a1a2e' }}>
              📎 {file.name} <span style={{ color:'#999' }}>· {fmtSize(file.size)}</span>
              {' '}<button onClick={removeCurrentAttachment} style={{ border:0, background:'transparent', color:'#C2253E', cursor:'pointer', fontSize:11.5, marginLeft:6 }}>remover</button>
            </span>
          ) : item?.attachment_filename ? (
            <span style={{ fontSize:12, color:'#888' }}>já existe um anexo: <b>{item.attachment_filename}</b> (subir novo substitui)</span>
          ) : (
            <span style={{ fontSize:12, color:'#999' }}>nenhum arquivo selecionado</span>
          )}
        </div>

        {err && <div style={{ padding:'9px 12px', borderRadius:6, fontSize:12.5, background:'rgba(194,37,62,.07)', border:'1px solid rgba(194,37,62,.2)', color:'#C2253E', marginBottom:12 }}>{err}</div>}

        <div style={{ display:'flex', justifyContent:'flex-end', gap:10, marginTop:6 }}>
          <button onClick={onClose} style={{ padding:'10px 16px', borderRadius:8, border:'1px solid #ddd', background:'#fff', cursor:'pointer', fontSize:13, fontWeight:600 }}>Cancelar</button>
          <button onClick={submit} disabled={saving || uploading} style={{ padding:'10px 20px', borderRadius:8, border:0, background:(saving||uploading)?'#555':'var(--pac-navy)', color:'#fff', cursor:(saving||uploading)?'not-allowed':'pointer', fontSize:13, fontWeight:700 }}>
            {uploading ? 'Enviando arquivo…' : saving ? 'Salvando…' : (editing ? 'Salvar alterações' : 'Criar item')}
          </button>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// View principal
// ============================================================
const Library = ({ currentUser }) => {
  const [tab, setTab] = React.useState('skill');
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState('');
  const [modalOpen, setModalOpen] = React.useState(false);
  const [editingItem, setEditingItem] = React.useState(null);
  const [installOpen, setInstallOpen] = React.useState(false);
  const [expanded, setExpanded] = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    try { setItems(await window.PACApi.library.list(tab)); }
    catch (e) { setItems([]); }
    finally { setLoading(false); }
  }, [tab]);
  React.useEffect(() => { load(); }, [load]);

  const filtered = items.filter(i =>
    !search || (i.title + ' ' + (i.description || '')).toLowerCase().includes(search.toLowerCase())
  );

  const canEdit = (item) => item.created_by === currentUser?.id || currentUser?.role === 'socio_admin';

  const download = (item) => {
    const a = document.createElement('a');
    a.href = `/api/library/${item.id}/download`;
    a.download = item.attachment_filename || 'download';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
  const copyContent = async (item) => {
    if (!item.content_text) return;
    try { await navigator.clipboard.writeText(item.content_text); alert('Conteúdo copiado.'); }
    catch (e) { alert('Não foi possível copiar.'); }
  };
  const remove = async (item) => {
    if (!confirm(`Remover "${item.title}"? Esta ação não pode ser desfeita.`)) return;
    try { await window.PACApi.library.remove(item.id); await load(); }
    catch (e) { alert('Erro ao remover: ' + e.message); }
  };

  const meta = KIND_META[tab];

  return (
    <div style={{ padding:'20px 24px', height:'100%', display:'flex', flexDirection:'column', boxSizing:'border-box', overflow:'auto' }}>
      {/* header */}
      <div style={{ display:'flex', alignItems:'flex-start', gap:14, marginBottom:18, flexWrap:'wrap' }}>
        <div style={{ flex:1, minWidth:240 }}>
          <h1 style={{ fontSize:22, fontWeight:800, color:'var(--pac-navy)', fontFamily:'Georgia, serif', margin:0 }}>Biblioteca</h1>
          <p style={{ fontSize:13, color:'#888', margin:'2px 0 0' }}>Skills, prompts e scripts do escritório · compartilhada com a equipe</p>
        </div>
        <button onClick={() => setInstallOpen(true)} title="Tutorial passo-a-passo" style={{ padding:'9px 14px', borderRadius:8, border:'1.5px solid var(--pac-navy)', background:'#fff', color:'var(--pac-navy)', cursor:'pointer', fontSize:12.5, fontWeight:700, display:'flex', alignItems:'center', gap:6 }}>
          <Icon name="info" size={13} /> Como instalar no Claude
        </button>
        <button onClick={() => { setEditingItem(null); setModalOpen(true); }} style={{ padding:'10px 16px', borderRadius:8, border:0, background:'var(--pac-navy)', color:'#fff', fontWeight:700, fontSize:13, cursor:'pointer', display:'flex', alignItems:'center', gap:6 }}>
          <Icon name="plus" size={13} /> Novo item
        </button>
      </div>

      {/* tabs */}
      <div style={{ display:'flex', gap:4, borderBottom:'1px solid var(--border)', marginBottom:14 }}>
        {Object.entries(KIND_META).map(([k, m]) => (
          <button key={k} onClick={() => setTab(k)} style={{
            padding:'10px 16px', border:0, background:'transparent', cursor:'pointer',
            borderBottom: tab === k ? '2px solid var(--pac-navy)' : '2px solid transparent',
            fontSize:13, fontWeight: tab === k ? 700 : 500, color: tab === k ? 'var(--pac-navy)' : '#777',
            display:'flex', alignItems:'center', gap:7,
          }}>
            <span>{m.label}</span>
            <span style={{ fontSize:10, fontWeight:700, color:'#888', background:'#eee', padding:'1px 7px', borderRadius:99 }}>
              {items.length}
            </span>
          </button>
        ))}
      </div>

      <div style={{ fontSize:12, color:'#888', marginBottom:12 }}>{meta.tip}</div>

      <input
        value={search}
        onChange={e => setSearch(e.target.value)}
        placeholder={`Buscar em ${meta.label.toLowerCase()}…`}
        style={{ padding:'9px 13px', border:'1.5px solid #ddd', borderRadius:8, fontSize:13, width:'100%', maxWidth:380, marginBottom:14, outline:'none' }}
      />

      {/* grid */}
      {loading ? (
        <div style={{ display:'flex', alignItems:'center', gap:10, color:'#999', fontSize:13 }}>
          <span className="spinner" style={{ borderColor:'rgba(13,13,107,.15)', borderTopColor:'var(--pac-navy)' }} /> Carregando…
        </div>
      ) : filtered.length === 0 ? (
        <div style={{ color:'#999', fontSize:14, textAlign:'center', padding:'40px 0' }}>
          {search ? `Nenhum item para "${search}".` : `Nenhum${meta.singular === 'Skill' ? 'a' : ''} ${meta.singular.toLowerCase()} ainda. Clique em "Novo item" para começar.`}
        </div>
      ) : (
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(290px, 1fr))', gap:12 }}>
          {filtered.map(it => {
            const ex = expanded === it.id;
            return (
              <div key={it.id} style={{ background:'#fff', border:'1px solid var(--border)', borderLeft:`3px solid ${meta.accent}`, borderRadius:9, padding:'14px 15px', display:'flex', flexDirection:'column', gap:8 }}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:8 }}>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:13.5, fontWeight:700, color:'#1a1a2e', lineHeight:1.3 }}>{it.title}</div>
                    <div style={{ fontSize:11, color:'#999', marginTop:3 }}>
                      por <b>{it.users?.name || '—'}</b> · {fmtDateLib(it.created_at)}
                    </div>
                  </div>
                </div>

                {it.description && (
                  <div style={{ fontSize:12, color:'#555', lineHeight:1.5, whiteSpace:'pre-wrap', maxHeight: ex ? 'none' : 60, overflow:'hidden', position:'relative' }}>
                    {it.description}
                    {!ex && it.description.length > 120 && <div style={{ position:'absolute', bottom:0, left:0, right:0, height:20, background:'linear-gradient(transparent, #fff)' }} />}
                  </div>
                )}

                {it.content_text && (
                  <details style={{ fontSize:11.5 }} open={ex} onToggle={e => setExpanded(e.target.open ? it.id : null)}>
                    <summary style={{ cursor:'pointer', color:'var(--pac-navy)', fontWeight:600, fontSize:11.5 }}>Ver conteúdo</summary>
                    <pre style={{ fontSize:11, fontFamily:'ui-monospace, monospace', background:'#f7f7fb', padding:10, borderRadius:6, marginTop:6, maxHeight:280, overflow:'auto', whiteSpace:'pre-wrap' }}>{it.content_text}</pre>
                  </details>
                )}

                {it.attachment_filename && (
                  <div style={{ fontSize:11.5, color:'#666', display:'flex', alignItems:'center', gap:5, background:'#f7f7fb', padding:'5px 9px', borderRadius:5 }}>
                    📎 {it.attachment_filename} <span style={{ color:'#aaa' }}>· {fmtSize(it.attachment_size)}</span>
                  </div>
                )}

                <div style={{ display:'flex', gap:6, marginTop:'auto', paddingTop:6, borderTop:'1px solid #f0f0f5', flexWrap:'wrap' }}>
                  {it.content_text && (
                    <button onClick={() => copyContent(it)} className="btn ghost sm" style={{ fontSize:11.5 }}>
                      <Icon name="copy" size={11} /> Copiar
                    </button>
                  )}
                  {it.attachment_filename && (
                    <button onClick={() => download(it)} className="btn ghost sm" style={{ fontSize:11.5 }}>
                      <Icon name="download" size={11} /> Baixar
                    </button>
                  )}
                  {canEdit(it) && (
                    <>
                      <button onClick={() => { setEditingItem(it); setModalOpen(true); }} className="btn ghost sm icon" title="Editar">
                        <Icon name="pen" size={11} />
                      </button>
                      <button onClick={() => remove(it)} className="btn ghost sm icon" title="Remover" style={{ color:'var(--danger, #C2253E)' }}>
                        <Icon name="trash" size={11} />
                      </button>
                    </>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {modalOpen && (
        <LibItemModal
          item={editingItem}
          defaultKind={tab}
          onClose={() => { setModalOpen(false); setEditingItem(null); }}
          onSaved={load}
        />
      )}
      {installOpen && <InstallHelpModal onClose={() => setInstallOpen(false)} />}
    </div>
  );
};

window.Library = Library;
