import type { ShoppingListItem } from '@/src/types/meal-plan';

function formatNumber(value: number): string {
  return Number.isInteger(value) ? value.toString() : value.toFixed(2).replace(/\.?0+$/, '');
}

export function formatShoppingQuantity(item: ShoppingListItem, toTasteLabel: string): string {
  if (item.unit && !item.totalGrams && !item.totalAmount) {
    return item.unit;
  }
  if (item.totalGrams != null) {
    return `${formatNumber(item.totalGrams)} g`;
  }
  if (item.totalAmount != null && item.unit) {
    return `${formatNumber(item.totalAmount)} ${item.unit}`;
  }
  return toTasteLabel;
}

export function buildShoppingListHtml(
  items: ShoppingListItem[],
  title: string,
  generatedLabel: string,
  toTasteLabel: string,
): string {
  const rows = items
    .map((item) => {
      const qty = formatShoppingQuantity(item, toTasteLabel);
      const breakdown =
        item.breakdown.length > 0
          ? `<div style="font-size:11px;color:#64748b;margin-top:2px">${item.breakdown.join(' · ')}</div>`
          : '';
      return `<tr>
        <td style="padding:8px 12px;border-bottom:1px solid #e2e8f0">${item.name}${breakdown}</td>
        <td style="padding:8px 12px;border-bottom:1px solid #e2e8f0;text-align:right;white-space:nowrap">${qty}</td>
      </tr>`;
    })
    .join('');

  return `<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>${title}</title></head>
<body style="font-family:system-ui,sans-serif;padding:32px;color:#0f172a">
  <h1 style="font-size:24px;margin:0 0 4px">${title}</h1>
  <p style="color:#64748b;font-size:13px;margin:0 0 24px">${generatedLabel}</p>
  <table style="width:100%;border-collapse:collapse;font-size:14px">
    <thead>
      <tr style="background:#f1f5f9">
        <th style="padding:8px 12px;text-align:left">Item</th>
        <th style="padding:8px 12px;text-align:right">Qty</th>
      </tr>
    </thead>
    <tbody>${rows}</tbody>
  </table>
</body></html>`;
}
