// pages/mobile/MobileNotasFiscais.jsx — real data (NFS-e emitidas + NF-e materiais)

function MobileNotasFiscais() {
  const [tab, setTab] = React.useState("emitidas");

  const monthLabel = (yyyymm) => {
    const [y, m] = yyyymm.split("-");
    const d = new Date(Number(y), Number(m) - 1, 1);
    return d.toLocaleDateString("pt-BR", { month: "long", year: "2-digit" })
      .replace(/^./, (c) => c.toUpperCase())
      .replace(/ de /, " ");
  };
  const ymKey = (iso) => String(iso || "").slice(0, 7);

  const nfEmitidaUrl = (parcela, tipo, dl) =>
    "/portal-cliente/api/notas-fiscais/emitida/file?parcela=" + encodeURIComponent(parcela) + "&tipo=" + (tipo || "pdf") + (dl ? "&dl=1" : "");
  const nfMaterialUrl = (id, tipo, dl) =>
    "/portal-cliente/api/notas-fiscais/material/" + encodeURIComponent(id) + "/file?tipo=" + (tipo || "pdf") + (dl ? "&dl=1" : "");

  const triggerDownload = (url, fname) => {
    const a = document.createElement("a");
    a.href = url; if (fname) a.download = fname; a.style.display = "none";
    document.body.appendChild(a); a.click(); setTimeout(() => a.remove(), 0);
  };

  const dataset = tab === "emitidas" ? NF_EMITIDAS : NF_MATERIAIS;
  const totalEmitidas = NF_EMITIDAS.reduce((s, nf) => s + nf.valor, 0);
  const totalMateriais = NF_MATERIAIS.reduce((s, nf) => s + nf.valor, 0);
  const totalCurrent = dataset.reduce((s, nf) => s + nf.valor, 0);

  const grouped = React.useMemo(() => {
    const map = new Map();
    dataset.forEach((nf) => {
      const key = tab === "emitidas" ? nf.competencia : ymKey(nf.emissao);
      if (!map.has(key)) map.set(key, []);
      map.get(key).push(nf);
    });
    return [...map.entries()].sort((a, b) => b[0].localeCompare(a[0]));
  }, [dataset, tab]);

  // Baixa XML + PDF da nota (com pequeno intervalo entre os dois).
  const baixarNf = (nf) => {
    if (!nf.hasFile && !nf.hasXml) return;
    let delay = 0;
    const queue = (url, fname) => { setTimeout(() => triggerDownload(url, fname), delay); delay += 300; };
    if (tab === "emitidas") {
      if (nf.hasFile) queue(nfEmitidaUrl(nf.parcela, "pdf", 1), "nfse_parcela-" + nf.parcela + ".pdf");
      if (nf.hasXml) queue(nfEmitidaUrl(nf.parcela, "xml", 1), "nfse_parcela-" + nf.parcela + ".xml");
    } else {
      if (nf.hasFile) queue(nfMaterialUrl(nf.id, "pdf", 1), "nfe_" + nf.id + ".pdf");
      if (nf.hasXml) queue(nfMaterialUrl(nf.id, "xml", 1), "nfe_" + nf.id + ".xml");
    }
  };

  const hasAnything = NF_EMITIDAS.length > 0 || NF_MATERIAIS.length > 0;

  return (
    <>
      <h1 className="m-title">Notas fiscais</h1>
      <div className="m-subtitle">Contrato · {PROJECT.code}</div>

      {!hasAnything ? (
        <div className="m-card" style={{ padding: 24, textAlign: "center", color: "var(--fg-4)", fontSize: 13 }}>
          Ainda nao ha notas fiscais lancadas para esta obra.
        </div>
      ) : (
      <>
      {/* Summary card */}
      <div className="m-card">
        <div className="m-card-body">
          <div style={{ fontSize: 10.5, color: "var(--fg-4)", textTransform: "uppercase", letterSpacing: "0.06em" }}>
            {tab === "emitidas" ? "Total emitido ao condomínio" : "Total de materiais comprados"}
          </div>
          <div className="mono" style={{ fontSize: 28, fontWeight: 500, letterSpacing: "-0.02em", marginTop: 6 }}>
            {fmtBRL(totalCurrent)}
          </div>
          <div style={{ fontSize: 11.5, color: "var(--fg-4)", fontFamily: "var(--font-mono)", marginTop: 2 }}>
            {dataset.length} notas · {grouped.length} {grouped.length === 1 ? "mês" : "meses"}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 14, paddingTop: 12, borderTop: "1px solid var(--border)" }}>
            <div>
              <div style={{ fontSize: 9.5, color: "var(--fg-4)", textTransform: "uppercase", letterSpacing: "0.06em" }}>NFS-e emitidas</div>
              <div className="mono" style={{ fontSize: 12.5, fontWeight: 500, marginTop: 3 }}>{NF_EMITIDAS.length}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--fg-4)", marginTop: 1 }}>{fmtBRL(totalEmitidas)}</div>
            </div>
            <div>
              <div style={{ fontSize: 9.5, color: "var(--fg-4)", textTransform: "uppercase", letterSpacing: "0.06em" }}>NF-e materiais</div>
              <div className="mono" style={{ fontSize: 12.5, fontWeight: 500, marginTop: 3 }}>{NF_MATERIAIS.length}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--fg-4)", marginTop: 1 }}>{fmtBRL(totalMateriais)}</div>
            </div>
          </div>
        </div>
      </div>

      {/* Segmented tabs */}
      <div
        style={{
          display: "flex",
          gap: 4,
          padding: 4,
          background: "var(--bg-muted)",
          borderRadius: 999,
          marginBottom: 14,
        }}
      >
        {[
          { id: "emitidas",  label: "Emitidas",  count: NF_EMITIDAS.length },
          { id: "materiais", label: "Materiais", count: NF_MATERIAIS.length },
        ].map((t) => {
          const active = tab === t.id;
          return (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              style={{
                flex: 1,
                height: 34,
                padding: "0 10px",
                borderRadius: 999,
                border: "none",
                background: active ? "#fff" : "transparent",
                color: active ? "var(--fg)" : "var(--fg-3)",
                fontSize: 12.5,
                fontWeight: active ? 700 : 600,
                fontFamily: "var(--font-sans)",
                boxShadow: active ? "0 1px 2px rgba(0,0,0,0.05)" : "none",
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 6,
              }}
            >
              {t.label}
              <span className="mono" style={{ color: "var(--fg-4)", fontSize: 11 }}>{t.count}</span>
            </button>
          );
        })}
      </div>

      {/* Month sections */}
      {grouped.map(([month, items]) => {
        const total = items.reduce((s, nf) => s + nf.valor, 0);
        return (
          <div key={month} className="m-section-block">
            <div className="m-section-block-head">
              <div className="m-section-block-title">{monthLabel(month)}</div>
              <div className="m-section-block-meta">
                {items.length} · {fmtBRL(total)}
              </div>
            </div>
            <div className="m-card">
              {items.map((nf, i) => (
                <button
                  key={(tab === "emitidas" ? nf.parcela : nf.id) + "-" + i}
                  className="m-nf-row"
                  style={{ borderTop: i ? "1px solid var(--border)" : "none", opacity: (nf.hasFile || nf.hasXml) ? 1 : 0.6 }}
                  onClick={() => baixarNf(nf)}
                >
                  <div className="m-nf-icon">
                    {tab === "emitidas" ? <I.Receipt size={16} /> : <I.Truck size={16} />}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="m-nf-title">
                      {tab === "emitidas" ? nf.desc : nf.fornecedor}
                    </div>
                    <div className="m-nf-sub">
                      <span className="mono">Nº {nf.num}</span>
                      <span className="mono">·</span>
                      <span className="mono">{fmtDateShort(nf.emissao)}</span>
                      {tab === "materiais" && (
                        <>
                          <span className="mono">·</span>
                          <span>{nf.cat}</span>
                        </>
                      )}
                    </div>
                    {tab === "materiais" && (
                      <div className="m-nf-desc">{nf.desc}</div>
                    )}
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4 }}>
                    <div className="m-nf-amount">{fmtBRL(nf.valor)}</div>
                    {(nf.hasFile || nf.hasXml) && (
                      <span style={{ color: "var(--fg-4)", display: "inline-flex" }}><I.Download size={13} /></span>
                    )}
                  </div>
                </button>
              ))}
            </div>
          </div>
        );
      })}
      </>
      )}
    </>
  );
}

window.MobileNotasFiscais = MobileNotasFiscais;
