export interface CustomItemViewProps {
  items: CustomerInvoiceItemFormData[];
  onItemsChange: (items: InvoiceItem[]) => void;
  updateItem?: (index: number, field: string, value: any) => void;
  removeItem?: (index: number) => void;
}

// types.ts
export interface InvoiceLine {
  description: string;
  quantity?: number; // vacío permitido
  unit_amount?: number; // vacío permitido (€)
  discount_percentage?: number; // 0..100
  tax_codes: string[]; // ids de catálogo
}
export interface LineComputed {
  subtotal_amount: number; // 4 decimales
  taxable_amount: number;
  taxes_amount: number;
  total_amount: number;
}
export interface TaxItem {
  id: string;
  label: string;
  rate: number;
} // rate en %
export type TaxCatalog = Record<string, TaxItem>;

// taxes-catalog.ts (ejemplo mínimo, amplía según necesidad)
export const TAXES: TaxCatalog = {
  iva21: { id: "iva21", label: "IVA 21 %", rate: 21 },
  iva10: { id: "iva10", label: "IVA 10 %", rate: 10 },
  iva4: { id: "iva4", label: "IVA 4 %", rate: 4 },
  re52: { id: "re52", label: "RE 5,2 %", rate: 5.2 },
  irpf15: { id: "irpf15", label: "IRPF −15 %", rate: -15 },
};
// util-decimal.ts
export const round4 = (n: number) => Math.round(n * 1e4) / 1e4;
export const parseNum = (v: string) => (v.trim() === "" ? undefined : Number(v.replace(",", ".")));
export const fmtNum = (n: number | undefined, max = 2) =>
  n === undefined ? "" : Intl.NumberFormat(undefined, { maximumFractionDigits: max }).format(n);
export const fmtMoney4 = (n: number | undefined) =>
  n === undefined ? "" : Intl.NumberFormat(undefined, { maximumFractionDigits: 4 }).format(n);

// calc.ts
import { InvoiceLine, LineComputed, TaxCatalog } from "./types";
export function computeLine(line: InvoiceLine, taxes: TaxCatalog): LineComputed {
  const q = line.quantity ?? 0;
  const u = line.unit_amount ?? 0;
  const subtotal = round4(q * u);
  const disc = Math.min(Math.max(line.discount_percentage ?? 0, 0), 100);
  const taxable = round4(subtotal * (1 - disc / 100));
  const taxesSum = round4(
    (line.tax_codes ?? []).reduce((acc, id) => acc + taxable * ((taxes[id]?.rate ?? 0) / 100), 0)
  );
  const total = round4(taxable + taxesSum);
  return {
    subtotal_amount: subtotal,
    taxable_amount: taxable,
    taxes_amount: taxesSum,
    total_amount: total,
  };
}
