import { Fragment } from "react";
import { formatPrice } from "../lib/format";
import type { TaxBreakdownGroup } from "../lib/taxBreakdown";

// The actual amount of VAT included in a total — not just a disclosure
// that VAT is included (see cartTotals.ts's effectiveTaxRate() for the
// "which %" shown next to each line item elsewhere). One line per rate
// when a cart/order spans more than one; a single line otherwise.
//
// `self-start` — the block starts flush left, at the same x as
// "Gesamtsumme" on the total row above it, not pinned under the €
// amount on the right (tried that, didn't read right against the label).
//
// Multi-rate case is a 3-column CSS grid (label / rate / amount), not a
// flex column — the "enthält MwSt.:" label only occupies row 1's first
// cell (later rows get an empty cell there), so the first rate sits on
// the *same line* as the label instead of dropping to its own row below
// it. Grid (unlike stacked flex rows) sizes each column to the widest
// cell across every row automatically, so the rate column still lines up
// a single-digit rate ("7%") under a two-digit one ("19%") without
// needing an explicit fixed width.
export function VatBreakdown({ groups }: { groups: TaxBreakdownGroup[] }) {
  if (groups.length === 0) return null;
  if (groups.length === 1) {
    const [g] = groups;
    return (
      <p className="self-start text-label text-text-muted">
        enthält {g.rate}% MwSt.: {formatPrice(g.tax)}
      </p>
    );
  }
  return (
    <div className="self-start grid grid-cols-[auto_auto_auto] items-baseline gap-x-1.5 gap-y-0.5">
      {groups.map((g, i) => (
        <Fragment key={g.rate}>
          <span className="text-label text-text-muted">{i === 0 ? "enthält MwSt.:" : ""}</span>
          <span className="text-right text-label text-text-muted tabular-nums">{g.rate}%</span>
          <span className="text-label text-text-muted tabular-nums">{formatPrice(g.tax)}</span>
        </Fragment>
      ))}
    </div>
  );
}
