(function attachKotFormatter(global: any) {
  type KotItem = {
    item_name: string;
    quantity: number;
    portion_breakup?: Array<{ portion: "full" | "half"; qty: number }>;
    packing_note?: string;
    special_instruction?: string;
  };

  type KotOrder = {
    kotNumber: string;
    createdAt: string;
    customer_name: string;
    customer_phone: string;
    address: string;
    items: KotItem[];
    order_total: number;
  };

  function rupees(value: number): string {
    const amount = Number(value || 0);
    return Number.isInteger(amount) ? `₹${amount}` : `₹${amount.toFixed(2)}`;
  }

  function generateKotText(order: KotOrder): string {
    const date = new Date(order.createdAt || Date.now());
    const itemLines = order.items
      .map((item, index) => {
        const note = item.special_instruction ? ` - ${item.special_instruction}` : "";
        const shouldShowBreakup = Boolean(item.portion_breakup?.some((part) => part.portion === "half") || (item.portion_breakup?.length || 0) > 1);
        const portionText = shouldShowBreakup
          ? item.portion_breakup.map((part) => `${part.qty} ${part.portion}`).join(" + ")
          : `x ${item.quantity}`;
        const packing = item.packing_note ? ` | ${item.packing_note}` : "";
        return shouldShowBreakup
          ? `${index + 1}. ${item.item_name} - ${portionText}${packing}${note}`
          : `${index + 1}. ${item.item_name} ${portionText}${packing}${note}`;
      })
      .join("\n");
    const instructions = order.items
      .map((item) => item.special_instruction)
      .filter(Boolean)
      .join(", ");

    return `RAMA FOODS
KOT #${order.kotNumber}
Date: ${date.toLocaleDateString("en-IN")}
Time: ${date.toLocaleTimeString("en-IN")}

Customer: ${order.customer_name || "-"}
Mobile: ${order.customer_phone || "-"}
Address: ${order.address || "Address missing"}

Items:
${itemLines || "-"}

Total: ${rupees(order.order_total)}

Instructions:
${instructions || "-"}`;
  }

  const api = { generateKotText };
  global.RamaKotFormatter = api;
  if (typeof module !== "undefined" && module.exports) {
    module.exports = api;
  }
})(typeof globalThis !== "undefined" ? globalThis : window);
