/* history.jsx — Histórico de Envios */

const histStatus = {
  enviado: { kind: "mute", label: "Enviado" },
  aberto:  { kind: "ok",   label: "Aberto" },
  erro:    { kind: "err",  label: "Erro" },
};

const HistSample = [
  { title: "Ecoporto Santos amplia capacidade de armazenagem de grãos no cais", source: "A Tribuna", time: "07:42", midia: true },
  { title: "Ecopátio registra movimento recorde de caminhões durante a safra", source: "Diário do Litoral", time: "06:58", midia: true },
  { title: "Porto de Santos bate recorde na exportação de soja em maio", source: "Valor Econômico", time: "08:15", paid: true },
  { title: "CONAB revisa estimativa da safra de grãos 2025/26", source: "Globo Rural", time: "07:30" },
  { title: "STS 10: leilão do novo terminal de contêineres é remarcado", source: "A Tribuna", time: "07:05" },
  { title: "Pátio de triagem reduz fila de caminhões na via Anchieta", source: "G1 Santos", time: "06:49" },
];

const HistoryPage = ({ history, onToast }) => {
  const [open, setOpen] = React.useState(null);
  const [filter, setFilter] = React.useState("Todos");
  const [clientFilter, setClientFilter] = React.useState("Todos");

  const clientOptions = Array.from(new Set(history.map(h => h.client)));

  const visible = history.filter(h => {
    if (filter !== "Todos" && h.status !== filter) return false;
    if (clientFilter !== "Todos" && h.client !== clientFilter) return false;
    return true;
  });

  const opened = history.filter(h => h.status === "aberto").length;
  const sent = history.filter(h => h.status !== "erro").length;
  const errs = history.filter(h => h.status === "erro").length;
  const openRate = Math.round((opened / Math.max(sent, 1)) * 100);

  return (
    <div className="page page--wide">
      <div className="page__head">
        <div>
          <h1>Histórico de envios</h1>
          <p>Auditoria dos clippings aprovados e disparados nos últimos dias</p>
        </div>
        <div className="page__actions">
          <button className="btn" onClick={() => onToast("Exportando CSV do histórico…")}><Icon name="download" /> Exportar CSV</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 18 }}>
        {[
          { k: "Envios listados", v: sent, c: "var(--ink-900)" },
          { k: "Abertos pelo cliente", v: opened, c: "var(--ok-700)" },
          { k: "Taxa de abertura", v: openRate + "%", c: "var(--brand)" },
          { k: "Com erro", v: errs, c: errs ? "var(--err-700)" : "var(--ink-900)" },
        ].map(s => (
          <div key={s.k} className="mx-card">
            <div className="muted" style={{ fontSize: 11.5, textTransform: "uppercase", letterSpacing: ".05em" }}>{s.k}</div>
            <div style={{ fontSize: 26, fontWeight: 600, color: s.c, marginTop: 3, fontVariantNumeric: "tabular-nums" }}>{s.v}</div>
          </div>
        ))}
      </div>

      <div className="card">
        <div className="card__head">
          <h3>Envios recentes</h3>
          <div className="row" style={{ gap: 10 }}>
            <div className="row" style={{ gap: 7 }}>
              <span className="muted" style={{ fontSize: 12.5 }}>Cliente</span>
              <select className="select" style={{ width: 180 }} value={clientFilter} onChange={e => setClientFilter(e.target.value)}>
                <option value="Todos">Todos os clientes</option>
                {clientOptions.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <div className="row" style={{ gap: 7 }}>
              <span className="muted" style={{ fontSize: 12.5 }}>Status</span>
              <select className="select" style={{ width: 140 }} value={filter} onChange={e => setFilter(e.target.value)}>
                <option value="Todos">Todos</option>
                <option value="enviado">Enviado</option>
                <option value="aberto">Aberto</option>
                <option value="erro">Erro</option>
              </select>
            </div>
          </div>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: "12%" }}>Data</th>
              <th style={{ width: "10%" }}>Horário</th>
              <th style={{ width: "26%" }}>Cliente</th>
              <th style={{ width: "12%" }}>Matérias</th>
              <th style={{ width: "16%" }}>Aprovado por</th>
              <th style={{ width: "14%" }}>Status</th>
              <th style={{ width: "10%", textAlign: "right" }}>Ações</th>
            </tr>
          </thead>
          <tbody>
            {visible.map(h => (
              <tr key={h.id} style={{ cursor: "pointer" }} onClick={() => setOpen(h)}>
                <td><span style={{ fontWeight: 500 }}>{h.date}</span> <span className="muted mono" style={{ fontSize: 11 }}>/26</span></td>
                <td className="num muted">{h.time}</td>
                <td style={{ fontWeight: 500, color: "var(--ink-900)" }}>{h.client}</td>
                <td className="num">{h.count}</td>
                <td className="muted">{h.by}</td>
                <td><Status kind={histStatus[h.status].kind}>{histStatus[h.status].label}</Status></td>
                <td><div className="actions"><button className="iconbtn" title="Ver clipping" onClick={e => { e.stopPropagation(); setOpen(h); }}><Icon name="eye" /></button></div></td>
              </tr>
            ))}
            {visible.length === 0 ? <tr><td colSpan="7"><div className="empty">Nenhum envio encontrado.</div></td></tr> : null}
          </tbody>
        </table>
      </div>

      {open ? (
        <Modal wide title={`Clipping enviado · ${open.client}`}
          subtitle={`${open.dateFull} às ${open.time === "—" ? "—" : open.time} · aprovado por ${open.by}`}
          onClose={() => setOpen(null)}
          footer={
            <>
              <button className="btn" onClick={() => setOpen(null)}>Fechar</button>
              <div className="row" style={{ gap: 8 }}>
                {open.status === "erro" ? <span className="muted" style={{ fontSize: 12 }}>Erro: timeout do servidor SMTP às {open.dateFull}.</span> : null}
                <button className="btn btn--primary" onClick={() => { onToast("Clipping reenviado para " + open.client); setOpen(null); }}><Icon name="send" /> Reenviar</button>
              </div>
            </>
          }>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 18 }}>
            <div className="mx-card"><div className="muted" style={{ fontSize: 11.5, textTransform: "uppercase" }}>Status</div><div style={{ marginTop: 6 }}><Status kind={histStatus[open.status].kind}>{histStatus[open.status].label}</Status></div></div>
            <div className="mx-card"><div className="muted" style={{ fontSize: 11.5, textTransform: "uppercase" }}>Matérias</div><div style={{ fontSize: 22, fontWeight: 600, marginTop: 2 }}>{open.count}</div></div>
            <div className="mx-card"><div className="muted" style={{ fontSize: 11.5, textTransform: "uppercase" }}>Anexos Drive</div><div style={{ fontSize: 14, fontWeight: 500, marginTop: 6 }}>{open.count ? "PDFs arquivados" : "—"}</div></div>
          </div>
          {open.count > 0 ? (
            <>
              <div style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".05em", color: "var(--ink-500)", fontWeight: 500, marginBottom: 8 }}>Matérias deste clipping</div>
              <div style={{ display: "flex", flexDirection: "column" }}>
                {HistSample.slice(0, open.count).map((a, i) => (
                  <div key={i} style={{ padding: "11px 0", borderBottom: "1px solid var(--ink-100)" }}>
                    <div style={{ fontWeight: 500, fontSize: 13.5, color: "var(--ink-900)", marginBottom: 3 }}>
                      {a.midia ? <span style={{ fontSize: 11, color: "var(--brand)", fontWeight: 600, marginRight: 7 }}>SAIU NA MÍDIA</span> : null}
                      {a.title}
                    </div>
                    <div className="rv-item__meta">
                      <span style={{ color: "var(--ink-600)" }}>{a.source}</span><span>·</span><span className="mono">{a.time}</span>
                      {a.paid ? <a className="rv-pdf" href="#" onClick={e => e.preventDefault()}><Icon name="pdf" style={{ width: 12, height: 12 }} /> PDF no Drive</a> : null}
                    </div>
                  </div>
                ))}
              </div>
            </>
          ) : (
            <div className="empty" style={{ border: "1px dashed var(--ink-200)", borderRadius: 8 }}>O envio falhou antes da compilação — nenhuma matéria foi anexada.</div>
          )}
        </Modal>
      ) : null}
    </div>
  );
};

window.HistoryPage = HistoryPage;
