// SylenProspec — FLUXO · Templates library
const { useState: uT, useEffect: eT, useMemo: mT } = React;
const T = window.SYLEN_DATA;

const CH_LABEL = { wpp: 'WhatsApp', email: 'E-mail', ig: 'Instagram DM', linkedin: 'LinkedIn', x: 'X / Twitter' };
const CH_SHORT = { wpp: 'WPP', email: 'EML', ig: 'IG', linkedin: 'LI', x: 'X' };

function Templates({ leads }) {
  const [list, setList] = uT(T.loadTemplates());
  const [activeId, setActiveId] = uT(list[0]?.id);
  const [filterSeg, setFseg] = uT('');
  const [filterCh, setFch] = uT('');
  const [savedAt, setSavedAt] = uT(null);
  const [previewIdx, setPv] = uT(0);

  const active = list.find(t => t.id === activeId) || list[0];

  const filtered = list
    .filter(t => !filterSeg || t.segmento === filterSeg)
    .filter(t => !filterCh || t.canal === filterCh);

  // Pick a preview lead from matching segment
  const candidates = leads.filter(l => active && l.segmento === active.segmento);
  const previewLead = candidates[previewIdx % Math.max(candidates.length, 1)] || leads[0];

  eT(() => {
    const it = setInterval(() => setPv(i => i + 1), 4500);
    return () => clearInterval(it);
  }, []);

  function persist(next) {
    setList(next);
    T.saveTemplates(next);
    setSavedAt(Date.now());
    setTimeout(() => setSavedAt(null), 2000);
  }

  function update(patch) {
    persist(list.map(t => t.id === active.id ? { ...t, ...patch } : t));
  }

  function createNew() {
    const id = 'tpl-' + Date.now();
    const novo = {
      id, nome: 'Novo template',
      segmento: 'hotel', tipo: 'email', canal: 'email',
      assunto: 'Assunto do e-mail — {{nome_empresa}}',
      corpo: 'Hi {{nome_empresa}}, sou da {{minha_empresa}}…',
      texto: '',
    };
    const next = [novo, ...list];
    persist(next);
    setActiveId(id);
  }

  function duplicate() {
    if (!active) return;
    const id = 'tpl-' + Date.now();
    const copy = { ...active, id, nome: active.nome + ' (cópia)' };
    const next = [copy, ...list];
    persist(next);
    setActiveId(id);
  }

  function remove() {
    if (!active) return;
    if (!confirm('Excluir este template?')) return;
    const next = list.filter(t => t.id !== active.id);
    persist(next);
    setActiveId(next[0]?.id);
  }

  const activeText = active ? (active.corpo || active.texto || '') : '';
  const activeAsunto = active ? (active.assunto || '') : '';
  const isEmail = active && (active.tipo === 'email' || active.canal === 'email');

  const previewBody = active
    ? T.renderTemplate(activeText, previewLead).split(/(\{\{\w+\}\})/g).map((p, i) =>
        p.match(/^\{\{\w+\}\}$/) ? <span key={i} className="var">{p}</span> : <React.Fragment key={i}>{p}</React.Fragment>
      )
    : null;

  return (
    <div className="tpl-page">

      {/* LEFT: library */}
      <div className="tpl-lib">
        <div className="tpl-lib-top">
          <div>
            <div className="cp-h" style={{ marginBottom: 4 }}>Biblioteca</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>
              {list.length} templates
            </div>
          </div>
          <button className="btn btn-primary tpl-new-btn" onClick={createNew}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14 }}>+</span>
            Novo
          </button>
        </div>

        <div className="tpl-filter">
          <select className="setup-input" value={filterSeg} onChange={e => setFseg(e.target.value)}>
            <option value="">Todos segmentos</option>
            {Object.entries(T.SEGMENTS).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
          </select>
          <select className="setup-input" value={filterCh} onChange={e => setFch(e.target.value)}>
            <option value="">Todos canais</option>
            {Object.entries(CH_LABEL).map(([k, l]) => <option key={k} value={k}>{l}</option>)}
          </select>
        </div>

        <div className="tpl-list-scroll">
          {filtered.map(t => {
            const used = Math.floor(Math.random() * 80 + 5); // mock usage count
            return (
              <div
                key={t.id}
                className={`tpl-row ${activeId === t.id ? 'on' : ''}`}
                onClick={() => setActiveId(t.id)}
              >
                <div className="tpl-row-h">
                  <div className="tpl-row-name">{t.nome}</div>
                  <div className="tpl-row-ch mono">{CH_SHORT[t.canal]}</div>
                </div>
                <div className="tpl-row-meta mono">
                  {T.SEGMENTS[t.segmento]?.label || '—'} · usado {used}x
                </div>
                <div className="tpl-row-snip">{(t.corpo || t.texto || '').split('\n')[0].slice(0, 60)}…</div>
              </div>
            );
          })}
          {filtered.length === 0 && (
            <div className="empty">Nenhum template encontrado nos filtros.</div>
          )}
        </div>
      </div>

      {/* CENTER: editor */}
      <div className="tpl-editor">
        {active ? (
          <React.Fragment>
            <div className="tpl-editor-head">
              <input
                className="tpl-name-input"
                value={active.nome}
                onChange={e => update({ nome: e.target.value })}
                placeholder="Nome do template…"
              />
              <div className="tpl-actions">
                <button className="btn btn-ghost" onClick={duplicate} title="Duplicar">⎘ Duplicar</button>
                <button className="btn btn-ghost" onClick={remove} title="Excluir" style={{ color: 'var(--text-muted)' }}>✕ Excluir</button>
                {savedAt && (
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ok)' }}>
                    ✓ salvo
                  </span>
                )}
              </div>
            </div>

            <div className="tpl-meta-row">
              <div className="tpl-meta-field">
                <label className="setup-label">Segmento alvo</label>
                <select
                  className="setup-input"
                  value={active.segmento}
                  onChange={e => update({ segmento: e.target.value })}
                >
                  {Object.entries(T.SEGMENTS).map(([k, v]) => (
                    <option key={k} value={k}>{v.label}</option>
                  ))}
                </select>
              </div>
              <div className="tpl-meta-field">
                <label className="setup-label">Canal preferido</label>
                <div className="chan-row">
                  {[
                    { id: 'email', l: 'E-mail', tipo: 'email' },
                    { id: 'wpp',   l: 'WhatsApp', tipo: 'whatsapp' },
                    { id: 'ig',    l: 'Instagram DM', tipo: 'instagram' },
                  ].map(c => (
                    <div
                      key={c.id}
                      className={`chan-pill ${active.canal === c.id ? 'on' : ''}`}
                      onClick={() => update({ canal: c.id, tipo: c.tipo })}
                    >
                      {c.l}
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {isEmail && (
              <div>
                <label className="setup-label">Assunto do e-mail</label>
                <input
                  className="setup-input"
                  value={activeAsunto}
                  onChange={e => update({ assunto: e.target.value })}
                  placeholder="Subject — {{nome_empresa}}"
                  style={{ width: '100%', fontSize: 14 }}
                />
              </div>
            )}

            <div className="tpl-textarea-wrap">
              <label className="setup-label" style={{ marginBottom: 6 }}>
                {isEmail ? 'Corpo do e-mail' : 'Mensagem'}
              </label>
              <textarea
                className="compose-editor tpl-textarea"
                value={activeText}
                onChange={e => update({ corpo: e.target.value })}
                placeholder="Comece a escrever sua mensagem aqui…"
              />
              <div className="tpl-meta-foot">
                <span className="mono">{activeText.length} caracteres</span>
                <span className="mono">·</span>
                <span className="mono">{(activeText.match(/\{\{\w+\}\}/g) || []).length} variáveis</span>
              </div>
            </div>

            <div className="tpl-vars">
              <div className="setup-label" style={{ marginBottom: 8 }}>Variáveis disponíveis</div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {['{{nome_empresa}}', '{{localizacao}}', '{{data_chegada}}', '{{data_saida}}', '{{minha_empresa}}', '{{meu_pitch}}'].map(v => (
                  <span
                    key={v}
                    className="var-chip"
                    onClick={() => update({ corpo: activeText + ' ' + v })}
                  >
                    {v}
                  </span>
                ))}
              </div>
              <div className="setup-hint mono" style={{ marginTop: 10 }}>
                → variáveis são substituídas no envio com dados do lead + campanha + operação
              </div>
            </div>
          </React.Fragment>
        ) : (
          <div className="empty" style={{ padding: 60 }}>
            Nenhum template selecionado.<br />
            Clique em <b>+ Novo</b> para criar.
          </div>
        )}
      </div>

      {/* RIGHT: preview */}
      <div className="tpl-preview">
        {active && (
          <React.Fragment>
            <div className="cp-h">Preview com dados reais</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)', marginBottom: 14 }}>
              Trocando lead a cada 4.5s · {candidates.length} leads matcham
            </div>

            <div className="preview-card">
              <div className="preview-meta">
                <span>{CH_SHORT[active.canal]}</span><span>→</span>
                <span style={{ color: 'var(--accent-bright)' }}>{previewLead?.nome}</span>
              </div>
              <div className="preview-body">{previewBody}</div>
            </div>

            <div className="cp-h" style={{ marginTop: 24 }}>Outros leads desse segmento</div>
            {candidates.slice(0, 5).map(l => (
              <div key={l.id} className="queue-mini" onClick={() => setPv(candidates.indexOf(l))} style={{ cursor: 'pointer' }}>
                <span>{l.nome}</span>
                <span className="mono">{l.cidade} · {l.uf}</span>
              </div>
            ))}
            {candidates.length === 0 && (
              <div className="setup-hint mono">
                Nenhum lead nesse segmento ainda. Importe leads ou ajuste o segmento alvo.
              </div>
            )}
          </React.Fragment>
        )}
      </div>

    </div>
  );
}

window.Templates = Templates;
