// acquisition-views.jsx — filtros e colunas compartilhadas para views da mesma aquisição
window.NA = window.NA || {};

function acqText(v) {
  return [v.plate, v.brand, v.model, v.owner, v.sellerName, v.bank, v.chassis, v.renavam]
    .filter(Boolean).join(" ").toLowerCase();
}

function hasLegalRestriction(v) {
  const notes = String(v.notes || "").toLowerCase();
  return !!(v.legalRestriction || v.renajud || v.seizure || notes.includes("renajud") || notes.includes("restri"));
}

function acquisitionFilterRows(vehicles, view, q, itemsByAcq) {
  let rows = vehicles || [];
  const query = String(q || "").trim().toLowerCase();
  if (query) rows = rows.filter(v => acqText(v).includes(query));
  const AM = window.NA?.AcquisitionMaintenance;

  if (view === "legal_pending") {
    rows = rows.filter(v => !["sold", "settled"].includes(v.status));
  } else if (view === "legal_restricted") {
    rows = rows.filter(hasLegalRestriction);
  } else if (view === "maintenance") {
    rows = rows.filter(v => {
      if (v.status === "sold") return false;
      const items = itemsByAcq?.[v.id] || [];
      if (items.length > 0) return true;
      return v.status === "in_stock" || v.status === "in_process";
    });
  } else if (view === "maintenance_pending") {
    rows = rows.filter(v => {
      if (v.status === "sold") return false;
      const items = itemsByAcq?.[v.id] || [];
      if (AM?.hasMaintenancePending) return AM.hasMaintenancePending(v, items);
      return (v.maintenance || []).length > 0;
    });
  } else if (view === "maintenance_ready") {
    rows = rows.filter(v => {
      if (v.status === "sold") return false;
      if (v.maintenanceReady) return true;
      const items = itemsByAcq?.[v.id] || [];
      const prog = AM?.computeMaintenanceProgress?.(items, AM?.vehicleMaintenanceFlags?.(v));
      return prog?.isReadyCandidate && prog?.pct >= 100;
    });
  } else if (view === "stock") {
    rows = rows.filter(v => v.status === "in_stock");
  } else if (view === "overdue") {
    rows = rows.filter(v => v.status === "overdue" || (v.parcels?.overdue || 0) > 0);
  } else if (view === "sold") {
    rows = rows.filter(v => v.status === "sold");
  } else if (view === "settled") {
    rows = rows.filter(v => ["settled", "in_settlement", "overdue"].includes(v.status));
  } else if (view === "post") {
    rows = rows.filter(v => ["settled", "sold"].includes(v.status));
  }
  return rows;
}

function acquisitionOpen(setT, vehicle, extra) {
  if (!setT || !vehicle) return;
  setT({ module: "acquisitions", acquisitionId: vehicle.id, ...(extra || {}) });
}

function acquisitionVehicleColumns(t, lang, context) {
  const NA = window.NA;
  const cols = [
    { key: "plate", label: t("common_plate"), render: v => <span className="mono fw-600">{v.plate}</span> },
    { key: "vehicle", label: lang === "pt" ? "Veículo" : "Vehicle", render: v => (
      <div><div className="fw-500">{v.brand}</div><div className="text-faint fs-11">{v.model}</div></div>
    )},
    { key: "owner", label: lang === "pt" ? "Cliente" : "Client", render: v => v.sellerName || v.owner || "—" },
    { key: "status", label: t("common_status"), render: (v, l) => <NA.StatusTag status={v.status} lang={l} /> },
  ];

  if (context === "legal") {
    cols.push(
      { key: "legal", label: "Jurídico", render: v => (
        <div className="row gap-4">
          {hasLegalRestriction(v) ? <NA.Tag kind="error">Restrição</NA.Tag> : <NA.Tag kind="success">OK</NA.Tag>}
          {(v.parcels?.overdue || 0) > 0 && <NA.Tag kind="warning">Quitação</NA.Tag>}
        </div>
      )},
      { key: "bank", label: t("common_bank"), render: v => v.bank || "—" },
    );
  } else if (context === "maintenance") {
    cols.push(
      { key: "items", label: lang === "pt" ? "Checklist" : "Checklist", render: v => {
        const items = window.NA?.maintenanceItemsByAcq?.[v.id] || [];
        const AM = window.NA?.AcquisitionMaintenance;
        const prog = AM?.computeMaintenanceProgress?.(items, AM?.vehicleMaintenanceFlags?.(v))
          || { done: 0, total: (v.maintenance || []).length };
        return <span className="mono">{prog.done}/{prog.total || 0}</span>;
      }},
      { key: "tracker", label: lang === "pt" ? "Rastreador" : "Tracker", render: v => (
        <NA.Tag kind={v.trackerStatus === "active" || v.trackerOursInstalled ? "success" : "default"} dot>
          {v.trackerStatus === "active" || v.trackerOursInstalled ? (lang === "pt" ? "ativo" : "active") : (lang === "pt" ? "inativo" : "inactive")}
        </NA.Tag>
      )},
    );
  } else {
    cols.push(
      { key: "next", label: lang === "pt" ? "Próx. venc." : "Next due", render: v => (
        <span className="mono fs-12">{NA.AcquisitionFinance?.fmtPtDate(NA.AcquisitionFinance?.getNextInstallmentDue(v)) || "—"}</span>
      )},
      { key: "roi", label: "ROI", render: v => <span className="mono">{Number(v.realRoi || v.roi || 0).toFixed(1)}%</span> },
    );
  }
  return cols;
}

function AcquisitionSourceBanner({ lang }) {
  return (
    <div className="alert info" style={{ marginBottom: 12 }}>
      <window.NA.Icon name="database" size={14} />
      <div className="body fs-12">
        {lang === "pt"
          ? "Esta tela é uma view operacional da tabela de Aquisições. Cadastro, status, documentos e financeiro continuam centralizados em Aquisições."
          : "This screen is an operational view of Acquisitions. CRUD, status, documents and finance remain centralized in Acquisitions."}
      </div>
    </div>
  );
}

window.NA.AcquisitionViews = {
  filterRows: acquisitionFilterRows,
  columns: acquisitionVehicleColumns,
  open: acquisitionOpen,
  hasLegalRestriction,
};
window.NA.AcquisitionSourceBanner = AcquisitionSourceBanner;
