/* global React, ReactDOM, Icon, Button */

// ─── Documentos imprimíveis — layout compartilhado ───────────────────────────
// Extraído do documento de PEDIDO DE VENDA (o layout que a Naii aprova). Serve
// venda, compra e os próximos documentos (Ordem de Produção) sem duplicar nada.
//
// ⚠️ IMPRESSÃO: o overlay é PORTALADO pra document.body e a regra de print esconde
// os IRMÃOS por `display` (`body > *:not(.doc-print-overlay)`). NUNCA use
// `body * { visibility: hidden }` — isso vaza pra qualquer outro overlay de
// impressão e faz o documento sair em branco (foi exatamente o bug do doc de
// compra que apagou o PDF do pedido de venda). Regras em styles.css.

const DOC_BRAND = "#C9A36B";

// Célula de cabeçalho / corpo das tabelas do documento.
const docThS = { padding: "5px 7px", border: "1px solid #ddd", fontWeight: "bold", fontSize: 10.5, background: "#f8f3ea", color: "#5a3e1b", textAlign: "left" };
const docTdS = { padding: "5px 7px", border: "1px solid #ddd", fontSize: 11, verticalAlign: "top" };

// ── Overlay + folha A4 ───────────────────────────────────────────────────────
// Portala pra body (requisito da regra de print). `barraTitulo` é o texto da
// barra de ferramentas (não sai no papel).
function DocPrintOverlay({ barraTitulo, onClose, loading, children }) {
  return ReactDOM.createPortal(
    <div className="doc-print-overlay" style={{
      position: "fixed", inset: 0, zIndex: 99990,
      background: "rgba(0,0,0,0.72)",
      display: "flex", flexDirection: "column", alignItems: "center", overflowY: "auto",
    }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>

      <div className="doc-no-print" style={{
        position: "sticky", top: 0, zIndex: 99991,
        width: "100%", maxWidth: 880,
        display: "flex", gap: 10, padding: "12px 20px",
        background: "var(--tm-bg-1)", borderBottom: "1px solid var(--tm-line-1)",
        alignItems: "center",
      }}>
        <Icon name="file-text" size={16} style={{ color: "var(--tm-brand-champagne)" }} />
        <span style={{ flex: 1, fontSize: 13.5, fontWeight: 600, color: "var(--tm-fg-1)" }}>
          {barraTitulo}
        </span>
        <Button variant="primary" icon="printer" size="sm" onClick={() => window.print()}>
          Imprimir / Salvar PDF
        </Button>
        <Button variant="secondary" size="sm" onClick={onClose}>Fechar</Button>
      </div>

      <div className="doc-sheet" style={{
        width: 794, background: "#fff", margin: "24px auto 48px",
        fontFamily: "'Arial', 'Helvetica Neue', sans-serif",
        fontSize: 11, color: "#111", lineHeight: 1.45,
        boxShadow: "0 6px 40px rgba(0,0,0,0.4)",
      }}>
        <div className="doc-sheet-accent" style={{ height: 5, background: DOC_BRAND }} />
        {loading ? (
          <div style={{ textAlign: "center", padding: 80, color: "#666", fontSize: 13 }}>Carregando…</div>
        ) : (
          <div className="doc-sheet-inner" style={{ padding: "32px 44px 36px" }}>{children}</div>
        )}
      </div>
    </div>,
    document.body
  );
}

// ── Cabeçalho da empresa emitente ────────────────────────────────────────────
function DocCabecalhoEmpresa({ empresa }) {
  const emp = empresa || {};
  const endEmp = [emp.logradouro, emp.numero, emp.complemento].filter(Boolean).join(', ');
  const cidEmp = [emp.bairro, emp.cidade, emp.uf].filter(Boolean).join(' · ');
  return (
    <table width="100%" style={{ marginBottom: 24, borderCollapse: "collapse" }}><tbody><tr>
      <td style={{ width: "38%", verticalAlign: "middle" }}>
        {emp.logo_url
          ? <img src={emp.logo_url} alt="logo" style={{ maxHeight: 60, maxWidth: 160, objectFit: "contain" }} />
          : <div style={{ fontSize: 17, fontWeight: "bold", color: "#222", letterSpacing: "0.02em" }}>
              {emp.nome_fantasia || emp.razao_social || "TopMix Profissional"}
            </div>}
      </td>
      <td style={{ textAlign: "right", fontSize: 10, color: "#444", verticalAlign: "top", lineHeight: 1.7 }}>
        {(emp.nome_fantasia || emp.razao_social) && (
          <div style={{ fontWeight: "bold", fontSize: 11 }}>{emp.nome_fantasia || emp.razao_social}</div>
        )}
        {emp.razao_social && emp.nome_fantasia && (
          <div>{emp.razao_social}</div>
        )}
        {emp.cnpj     && <div>CNPJ: {emp.cnpj}</div>}
        {emp.telefone && <div>Tel: {emp.telefone}</div>}
        {endEmp       && <div>{endEmp}</div>}
        {cidEmp       && <div>{cidEmp}{emp.cep ? ` · CEP ${emp.cep}` : ""}</div>}
      </td>
    </tr></tbody></table>
  );
}

// ── Título do documento ("Pedido de Venda PED-1", "Pedido de Compra PC-…") ────
function DocTitulo({ texto, numero }) {
  return (
    <div style={{ textAlign: "center", fontSize: 15, fontWeight: "bold", margin: "4px 0 20px", borderBottom: `3px solid ${DOC_BRAND}`, paddingBottom: 10, color: "#1a1a1a" }}>
      {texto}&nbsp;&nbsp;<span style={{ color: DOC_BRAND }}>{numero}</span>
    </div>
  );
}

// ── Bloco da contraparte (CLIENTE na venda, FORNECEDOR na compra) + dados ─────
// `detalhes` é livre (nós React) porque cada documento mostra campos diferentes.
// `info` é a tabelinha da direita: array de [label, valor].
function DocParteInfo({ parteLabel, parteNome, detalhes, info }) {
  return (
    <table width="100%" style={{ borderCollapse: "collapse", marginBottom: 20 }}><tbody><tr valign="top">
      <td style={{ width: "54%", padding: "10px 12px", border: "1px solid #ccc" }}>
        <div style={{ fontSize: 9, fontWeight: "bold", color: "#666", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 5 }}>{parteLabel}</div>
        <div style={{ fontWeight: "bold", fontSize: 12.5, marginBottom: 4 }}>{parteNome || "—"}</div>
        {detalhes}
      </td>
      <td style={{ width: "46%" }}>
        <table width="100%" style={{ borderCollapse: "collapse" }}><tbody>
          {(info || []).filter(Boolean).map(([lbl, val]) => (
            <tr key={lbl}>
              <td style={{ padding: "5px 8px", border: "1px solid #ccc", fontWeight: "bold", fontSize: 10, background: "#f7f7f7", width: "48%" }}>{lbl}</td>
              <td style={{ padding: "5px 8px", border: "1px solid #ccc", fontSize: 11 }}>{val}</td>
            </tr>
          ))}
        </tbody></table>
      </td>
    </tr></tbody></table>
  );
}

// ── Título de seção (barrinha dourada à esquerda) ────────────────────────────
function DocTituloSecao({ children }) {
  return (
    <div style={{ fontWeight: "bold", fontSize: 10.5, marginBottom: 5, borderLeft: `3px solid ${DOC_BRAND}`, paddingLeft: 7, color: "#2a1a00" }}>{children}</div>
  );
}

// ── Tabela de itens + totalizadores ──────────────────────────────────────────
// colunas: [{ label, width?, align? }]
// linhas:  [[{ v, align?, muted?, num? }, …], …]
// totais:  [[label, valor, bold], …]  → colSpan calculado a partir das colunas
function DocTabelaItens({ colunas, linhas, totais }) {
  const cols = colunas || [];
  const spanEsq = Math.max(1, cols.length - 2);
  const celStyle = (c) => {
    let s = { ...docTdS };
    if (c.align) s.textAlign = c.align;
    if (c.muted) s = { ...s, color: "#666", fontSize: 10 };
    if (c.num) s.fontVariantNumeric = "tabular-nums";
    return s;
  };
  return (
    <table width="100%" style={{ borderCollapse: "collapse", marginBottom: 20 }}>
      <thead>
        <tr>
          {cols.map((c, i) => (
            <th key={i} style={{ ...docThS, ...(c.width ? { width: c.width } : {}), ...(c.align ? { textAlign: c.align } : {}) }}>{c.label}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {(linhas || []).map((row, i) => (
          <tr key={i} style={{ background: i % 2 === 0 ? "#fff" : "#fafafa" }}>
            {row.map((c, j) => <td key={j} style={celStyle(c)}>{c.v}</td>)}
          </tr>
        ))}
        {(totais || []).filter(Boolean).map(([lbl, val, bold], i) => (
          <tr key={lbl}>
            <td colSpan={spanEsq} style={{ borderTop: i === 0 ? `2px solid ${DOC_BRAND}` : "none", background: bold ? "#fdf8f0" : "transparent" }} />
            <td style={{ padding: "4px 7px", textAlign: "right", fontWeight: bold ? "bold" : 600, fontSize: bold ? 11.5 : 10, borderTop: i === 0 ? `2px solid ${DOC_BRAND}` : "none", borderRight: "1px solid #ddd", color: bold ? "#7A4F1A" : "#444", background: bold ? "#fdf3e3" : "transparent" }}>{lbl}</td>
            <td style={{ padding: "4px 7px", textAlign: "right", fontVariantNumeric: "tabular-nums", fontWeight: bold ? "bold" : "normal", fontSize: bold ? 12.5 : 10.5, borderTop: i === 0 ? `2px solid ${DOC_BRAND}` : "none", border: "1px solid #ddd", color: bold ? "#7A4F1A" : "#333", background: bold ? "#fdf3e3" : "transparent" }}>{val}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ── Bloco de observações (caixa com altura mínima) ───────────────────────────
function DocObservacoes({ texto, titulo = "Observações" }) {
  return (
    <div className="doc-section-break">
      <DocTituloSecao>{titulo}</DocTituloSecao>
      <div style={{ border: "1px solid #ddd", padding: "8px 10px", minHeight: 48, fontSize: 11, whiteSpace: "pre-wrap", marginBottom: 32 }}>
        {texto || ""}
      </div>
    </div>
  );
}

// ── Tabela chave/valor (Transportador na venda, Condições na compra) ─────────
function DocTabelaCampos({ linhas }) {
  return (
    <table width="100%" style={{ borderCollapse: "collapse", marginBottom: 20 }}>
      <tbody>
        {(linhas || []).filter(Boolean).map(([lbl, val]) => (
          <tr key={lbl}>
            <td style={{ ...docTdS, fontWeight: "bold", width: "28%", background: "#f7f7f7", border: "1px solid #ccc" }}>{lbl}</td>
            <td style={{ ...docTdS, border: "1px solid #ccc" }}>{val}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ── Caixinha de conferência manual (a fábrica marca a caneta, no papel) ──────
function DocCaixaConferencia() {
  return <span style={{ display: "inline-block", width: 13, height: 13, border: "1.5px solid #999", borderRadius: 2 }} />;
}

// ── Assinatura / recebimento (documentos de remessa) ─────────────────────────
// `campos`: array de [label, largura]. Renderiza a linha pontilhada pra caneta.
function DocAssinatura({ titulo = "Recebimento", campos, nota }) {
  const linhas = campos || [["Recebido por (nome legível)", "52%"], ["Data", "22%"], ["Assinatura", "26%"]];
  return (
    <div className="doc-section-break" style={{ marginTop: 28 }}>
      <DocTituloSecao>{titulo}</DocTituloSecao>
      <table width="100%" style={{ borderCollapse: "collapse", marginTop: 14 }}><tbody><tr valign="bottom">
        {linhas.map(([lbl, w], i) => (
          <td key={lbl} style={{ width: w, padding: i === 0 ? "0 14px 0 0" : "0 14px" }}>
            <div style={{ borderBottom: "1px solid #999", height: 26 }} />
            <div style={{ fontSize: 9, color: "#666", paddingTop: 4 }}>{lbl}</div>
          </td>
        ))}
      </tr></tbody></table>
      {nota && <div style={{ fontSize: 9.5, color: "#777", marginTop: 10 }}>{nota}</div>}
    </div>
  );
}

Object.assign(window, {
  DOC_BRAND, docThS, docTdS,
  DocPrintOverlay, DocCabecalhoEmpresa, DocTitulo, DocParteInfo,
  DocTituloSecao, DocTabelaItens, DocObservacoes, DocTabelaCampos,
  DocCaixaConferencia, DocAssinatura,
});
