<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between w-full">
            <div>
                <h1 class="text-lg font-semibold text-gray-800">Edit Invoice</h1>
                <p class="text-xs text-gray-400 mt-0.5"
                    x-text="`Editing invoice ${form.local_invoice_no || '#{{ $invoice->id }}'}`"></p>
            </div>
            <a href="{{ route('invoices.index') }}" class="text-sm text-gray-500 hover:text-gray-700 font-medium">
                Back to Invoices
            </a>
        </div>
    </x-slot>

    <div x-data="invoiceForm()" class="w-full space-y-6">
        <form @submit.prevent="submit" class="grid grid-cols-1 lg:grid-cols-[1fr_320px] xl:grid-cols-[1fr_360px] 2xl:grid-cols-[1fr_400px] gap-6">
            <!-- Left Panel: Details & Items -->
            <div class="space-y-6 min-w-0">
                <!-- Customer & Scenario Information -->
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 space-y-4">
                    <h2 class="flex items-center gap-2 text-sm font-semibold text-gray-700 border-b border-gray-100 pb-3">
                        <span class="flex items-center justify-center w-6 h-6 rounded-full bg-indigo-100 text-indigo-600 text-[11px] font-bold">1</span>
                        Header Information
                    </h2>

                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                        <!-- Searchable Customer Selector -->
                        <div class="relative" x-data="{ open: false, search: '' }">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Customer <span class="text-red-500">*</span></label>
                            <button type="button" @click="open = !open"
                                    class="w-full text-left bg-white border border-gray-200 rounded-lg px-3 py-2.5 text-sm text-gray-700 flex items-center justify-between focus:border-indigo-400 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 hover:border-gray-300 transition"
                                    :class="errors.customer_id && 'border-red-400'">
                                <span x-text="selectedCustomer ? selectedCustomer.name : 'Select Customer...'" :class="!selectedCustomer && 'text-gray-400'"></span>
                                <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                                </svg>
                            </button>

                            <div x-show="open" @click.away="open = false" x-cloak
                                 class="absolute z-50 mt-1.5 w-full bg-white border border-gray-200 rounded-xl shadow-lg max-h-60 overflow-y-auto p-2 space-y-2">
                                <input type="text" x-model="search" placeholder="Search customer..."
                                       class="w-full rounded-lg border-gray-200 text-xs p-1.5 focus:border-indigo-400 focus:ring-indigo-400">
                                <div class="divide-y divide-gray-50 max-h-40 overflow-y-auto">
                                    <template x-for="c in customers.filter(item => item.name.toLowerCase().includes(search.toLowerCase()) || (item.ntn_cnic && item.ntn_cnic.includes(search)))" :key="c.id">
                                        <button type="button" @click="selectCustomer(c); open = false; search = ''"
                                                class="w-full text-left text-xs text-gray-700 hover:bg-indigo-50 py-2 px-2 rounded-lg transition flex items-center justify-between">
                                            <span x-text="c.name"></span>
                                            <span class="text-[10px] text-gray-400 font-mono" x-text="c.ntn_cnic || 'No NTN/CNIC'"></span>
                                        </button>
                                    </template>
                                </div>
                            </div>
                            <p class="text-xs text-red-500 mt-1" x-show="errors.customer_id" x-text="errors.customer_id?.[0]"></p>
                        </div>

                        <!-- Searchable Scenario Selector -->
                        <div class="relative" x-data="{ open: false, search: '' }">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Scenario ID <span class="text-red-500">*</span></label>
                            <button type="button" @click="open = !open"
                                    class="w-full text-left bg-white border border-gray-200 rounded-lg px-3 py-2.5 text-sm text-gray-700 flex items-center justify-between focus:border-indigo-400 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 hover:border-gray-300 transition"
                                    :class="errors.scenario_id && 'border-red-400'">
                                <span x-text="form.scenario_id ? form.scenario_id : 'Select Scenario...'"></span>
                                <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                                </svg>
                            </button>

                            <div x-show="open" @click.away="open = false" x-cloak
                                 class="absolute z-50 mt-1.5 w-full bg-white border border-gray-200 rounded-xl shadow-lg max-h-60 overflow-y-auto p-2 space-y-2">
                                <input type="text" x-model="search" placeholder="Search scenario..."
                                       class="w-full rounded-lg border-gray-200 text-xs p-1.5 focus:border-indigo-400 focus:ring-indigo-400">
                                <div class="divide-y divide-gray-50 max-h-40 overflow-y-auto">
                                    <template x-for="s in scenarios.filter(item => item.name.toLowerCase().includes(search.toLowerCase()) || item.id.toLowerCase().includes(search.toLowerCase()))" :key="s.id">
                                        <button type="button" @click="form.scenario_id = s.id; open = false; search = ''"
                                                class="w-full text-left text-xs text-gray-700 hover:bg-indigo-50 py-2 px-2 rounded-lg transition">
                                            <div class="font-semibold text-gray-800" x-text="s.id"></div>
                                            <div class="text-[10px] text-gray-400" x-text="s.desc"></div>
                                        </button>
                                    </template>
                                </div>
                            </div>
                            <p class="text-xs text-red-500 mt-1" x-show="errors.scenario_id" x-text="errors.scenario_id?.[0]"></p>
                        </div>

                        <div>
                            <label class="block text-xs font-medium text-gray-500 mb-1">Invoice Date <span class="text-red-500">*</span></label>
                            <input type="text" x-model="form.invoice_date" x-flatpickr
                                   class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400 py-2.5"
                                   :class="errors.invoice_date && 'border-red-400'">
                            <p class="text-xs text-red-500 mt-1" x-show="errors.invoice_date" x-text="errors.invoice_date?.[0]"></p>
                        </div>

                        <div>
                            <label class="block text-xs font-medium text-gray-500 mb-1">Invoice No (Optional)</label>
                            <input type="text" x-model="form.local_invoice_no" placeholder="Auto-generated if empty"
                                class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400 py-2.5"
                                :class="errors.local_invoice_no && 'border-red-400'">
                            <p class="text-xs text-red-500 mt-1" x-show="errors.local_invoice_no"
                                x-text="errors.local_invoice_no?.[0]"></p>
                        </div>
                    </div>

                    <!-- Selected Customer details -->
                    <template x-if="selectedCustomer">
                        <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 p-3.5 bg-indigo-50/50 border border-indigo-100 rounded-xl text-xs">
                            <div>
                                <span class="text-indigo-400 block uppercase mb-0.5 tracking-wide font-medium">NTN / CNIC</span>
                                <span class="font-semibold text-gray-700" x-text="selectedCustomer.ntn_cnic || '—'"></span>
                            </div>
                            <div>
                                <span class="text-indigo-400 block uppercase mb-0.5 tracking-wide font-medium">Registration Type</span>
                                <span class="font-semibold text-gray-700" x-text="selectedCustomer.registration_type || '—'"></span>
                            </div>
                            <div>
                                <span class="text-indigo-400 block uppercase mb-0.5 tracking-wide font-medium">Name / Business Name</span>
                                <span class="font-semibold text-gray-700" x-text="selectedCustomer.name || '—'"></span>
                            </div>
                            <div>
                                <span class="text-indigo-400 block uppercase mb-0.5 tracking-wide font-medium">Province</span>
                                <span class="font-semibold text-gray-700" x-text="selectedCustomer.province || '—'"></span>
                            </div>
                        </div>
                    </template>
                </div>

                <!-- Product Search Autocomplete & Invoice Line Items -->
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 space-y-4">
                    <div class="border-b border-gray-100 pb-4 space-y-3">
                        <h2 class="flex items-center gap-2 text-sm font-semibold text-gray-700">
                            <span class="flex items-center justify-center w-6 h-6 rounded-full bg-indigo-100 text-indigo-600 text-[11px] font-bold">2</span>
                            Line Items
                        </h2>

                        <!-- Search Product Autocomplete Input -->
                        <div class="relative" x-data="{ open: false, query: '', productLoading: false, async performSearch() {
                            if (this.query.length < 2) {
                                $data.items = [];
                                return;
                            }
                            this.productLoading = true;
                            try {
                                const res = await apiFetch(`/items/data?active_only=1&per_page=15&search=${encodeURIComponent(this.query)}`);
                                $data.items = res.data || [];
                            } catch (e) {
                                console.error(e);
                            } finally {
                                this.productLoading = false;
                            }
                        } }">
                            <div class="flex gap-2 items-center">
                                <div class="relative flex-1">
                                    <svg class="w-4 h-4 text-gray-300 absolute left-3 top-1/2 -translate-y-1/2" fill="none"
                                        stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M21 21l-4.35-4.35M17 10a7 7 0 11-14 0 7 7 0 0114 0z" />
                                    </svg>
                                    <input type="text" x-model="query" @focus="open = true" @input.debounce.300ms="performSearch()"
                                        placeholder="Search products by Name, SKU, or HS Code to add (min 2 chars)..."
                                        class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400 p-2.5 pl-9 pr-10">
                                    <div x-show="productLoading" class="absolute right-3 top-1/2 -translate-y-1/2">
                                        <svg class="animate-spin h-4 w-4 text-indigo-500" fill="none" viewBox="0 0 24 24">
                                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                        </svg>
                                    </div>
                                </div>
                                <button type="button" @click="openQuickItemModal = true"
                                    class="p-2.5 bg-indigo-50 hover:bg-indigo-100 border border-indigo-100 hover:border-indigo-200 text-indigo-600 rounded-xl transition flex items-center justify-center font-bold"
                                    title="Quick Add Item">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                                    </svg>
                                </button>
                            </div>

                            <div x-show="open && query.length >= 2" @click.away="open = false" x-cloak
                                class="absolute z-50 mt-1.5 w-full bg-white border border-gray-200 rounded-xl shadow-lg max-h-60 overflow-y-auto p-2 divide-y divide-gray-50">
                                <div x-show="productLoading" class="text-xs text-gray-400 text-center py-4 flex items-center justify-center gap-2">
                                    <svg class="animate-spin h-3.5 w-3.5 text-indigo-500" fill="none" viewBox="0 0 24 24">
                                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                    </svg>
                                    <span>Searching products...</span>
                                </div>
                                <template x-if="!productLoading">
                                    <div>
                                        <template x-for="item in items" :key="item.id">
                                            <button type="button" @click="selectItem(item); open = false; query = ''; items = []"
                                                class="w-full text-left text-xs hover:bg-indigo-50 p-2.5 rounded-lg transition flex items-center justify-between">
                                                <div>
                                                    <div class="font-semibold text-gray-800" x-text="item.name"></div>
                                                    <div class="text-[10px] text-gray-400"
                                                        x-text="`SKU: ${item.sku || 'N/A'} | HS: ${item.hs_code || 'N/A'}`">
                                                    </div>
                                                </div>
                                                <div class="text-right">
                                                    <div class="font-semibold text-indigo-600"
                                                        x-text="`Rs. ${Number(item.default_price_excl_st).toFixed(2)}`"></div>
                                                    <div class="text-[10px] text-gray-400"
                                                        x-text="`Rate: ${item.default_rate}%`"></div>
                                                </div>
                                            </button>
                                        </template>
                                        <div x-show="items.length === 0" class="text-xs text-gray-400 text-center py-4">
                                            No products match the search.
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>

                    <div class="overflow-x-auto">
                        <table class="text-left text-xs w-full" style="border-collapse: separate; border-spacing: 0 8px;">
                            <colgroup>
                                <col style="width:26%">
                                <col style="width:7%">
                                <col style="width:12%">
                                <col style="width:18%">
                                <col style="width:18%">
                                <col style="width:10%">
                                <col style="width:11%">
                                <col style="width:4%">
                            </colgroup>
                            <thead>
                                <tr class="bg-gradient-to-r from-indigo-50 to-indigo-50/40 text-indigo-700">
                                    <th class="py-3 pl-4 pr-4 rounded-l-lg font-semibold uppercase tracking-wider text-[10.5px] whitespace-nowrap">Product</th>
                                    <th class="py-3 px-2 text-center font-semibold uppercase tracking-wider text-[10.5px] whitespace-nowrap">Qty</th>
                                    <th class="py-3 px-2 font-semibold uppercase tracking-wider text-[10.5px] whitespace-nowrap">Price</th>
                                    <th class="py-3 px-2 text-center font-semibold uppercase tracking-wider text-[10.5px] whitespace-nowrap">Further Tax</th>
                                    <th class="py-3 px-2 text-center font-semibold uppercase tracking-wider text-[10.5px] whitespace-nowrap">Advance Tax</th>
                                    <th class="py-3 px-2 text-right font-semibold uppercase tracking-wider text-[10.5px] whitespace-nowrap">Tax Amt</th>
                                    <th class="py-3 px-2 text-right font-semibold uppercase tracking-wider text-[10.5px] whitespace-nowrap">Total</th>
                                    <th class="py-3 pr-4 rounded-r-lg"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="(row, idx) in form.items" :key="idx">
                                    <tr class="align-top bg-white border border-gray-100 shadow-sm hover:shadow-md hover:border-indigo-200 transition">
                                        <td class="py-4 pl-4 pr-4 rounded-l-lg">
                                            <div class="font-semibold text-gray-800" x-text="row.product_name"></div>
                                            <div class="text-[10px] text-gray-400 font-mono mt-0.5" x-text="`SKU: ${row.sku || 'N/A'} | HS: ${row.hs_code || 'N/A'}`"></div>
                                            <input type="text" x-model="row.product_description" placeholder="Custom description..."
                                                   class="w-full rounded-lg border-gray-200 text-xs mt-1.5 focus:border-indigo-400 focus:ring-indigo-400 py-1 px-2">
                                            <!-- Discount Button/Text -->
                                            <div class="mt-2 flex items-center justify-between">
                                                <button type="button" @click="openDiscountModal(idx)"
                                                        class="text-[10px] font-semibold text-indigo-600 hover:text-indigo-800 flex items-center gap-1 transition">
                                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5a2 2 0 10-2 2h2zm0 0h4m-4 0H8m12 3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                    </svg>
                                                    <span x-text="row.discount > 0 ? `Discount: Rs. ${Number(row.discount).toFixed(2)}` : 'Add Discount'"></span>
                                                </button>
                                            </div>
                                        </td>
                                        <td class="py-4 px-2">
                                            <input type="number" x-model.number="row.quantity" @input="recalculateRow(idx)" min="0" :step="Math.pow(10, -AppConfig.quantityPrecision)"
                                                   class="w-full text-center rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 py-1.5 px-2">
                                        </td>
                                        <td class="py-4 px-2">
                                            <input type="number" :step="Math.pow(10, -AppConfig.currencyPrecision)" x-model.number="row.value_sales_excluding_st" @input="recalculateRow(idx)"
                                                   class="w-full rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 py-1.5 px-2 text-right">
                                        </td>
                                        <!-- Further Tax (Percentage / Fixed) -->
                                        <td class="py-4 px-2">
                                            <div class="flex items-center gap-1">
                                                <input type="number" :step="Math.pow(10, -AppConfig.currencyPrecision)" x-model.number="row.further_tax_value" @input="recalculateRow(idx)"
                                                       class="w-full rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 py-1.5 px-2 text-right">
                                                <select x-model="row.further_tax_type" @change="recalculateRow(idx)"
                                                        class="rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 py-1.5 px-1.5 bg-gray-50 text-gray-600 font-semibold">
                                                    <option value="percent">%</option>
                                                    <option value="fixed">Rs</option>
                                                </select>
                                            </div>
                                            <input type="text" disabled :value="formatCurrency(row.further_tax)"
                                                   class="w-full rounded-lg border-gray-100 bg-gray-50/50 text-gray-400 font-mono text-[10px] mt-1.5 text-right py-1 px-2 border cursor-not-allowed">
                                        </td>
                                        <!-- Advance Tax (Percentage / Fixed) -->
                                        <td class="py-4 px-2">
                                            <div class="flex items-center gap-1">
                                                <input type="number" :step="Math.pow(10, -AppConfig.currencyPrecision)" x-model.number="row.advance_tax_value" @input="recalculateRow(idx)"
                                                       class="w-full rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 py-1.5 px-2 text-right">
                                                <select x-model="row.advance_tax_type" @change="recalculateRow(idx)"
                                                        class="rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 py-1.5 px-1.5 bg-gray-50 text-gray-600 font-semibold">
                                                    <option value="percent">%</option>
                                                    <option value="fixed">Rs</option>
                                                </select>
                                            </div>
                                            <input type="text" disabled :value="formatCurrency(row.extra_tax)"
                                                   class="w-full rounded-lg border-gray-100 bg-gray-50/50 text-gray-400 font-mono text-[10px] mt-1.5 text-right py-1 px-2 border cursor-not-allowed">
                                        </td>
                                        <!-- Sales Tax Auto Input -->
                                        <td class="py-4 px-2">
                                            <input type="text" disabled :value="formatCurrency(row.sales_tax_applicable)"
                                                   class="w-full rounded-lg border-gray-100 bg-gray-50/50 text-gray-500 font-mono text-xs text-right py-1.5 px-2 border cursor-not-allowed">
                                            <div class="text-[9px] text-gray-400 text-right mt-1 font-semibold" x-text="'Rate: ' + (String(row.rate).endsWith('%') ? row.rate : row.rate + '%')"></div>
                                        </td>
                                        <!-- Row Total Auto Input -->
                                        <td class="py-4 px-2">
                                            <input type="text" disabled :value="formatCurrency(row.total_values)"
                                                   class="w-full rounded-lg border-indigo-100 bg-indigo-50/40 text-indigo-700 font-semibold font-mono text-xs text-right py-1.5 px-2 border cursor-not-allowed">
                                        </td>
                                        <td class="py-4 pr-4 rounded-r-lg text-right align-middle">
                                            <button type="button" @click="removeItemRow(idx)" class="text-gray-400 hover:text-rose-600 transition pt-1.5">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                                                </svg>
                                            </button>
                                        </td>
                                    </tr>
                                </template>
                                <tr x-show="form.items.length === 0">
                                    <td colspan="8" class="py-10 text-center text-gray-400 bg-gray-50/40 rounded-lg border border-dashed border-gray-200">
                                        No items added. Search and select a product above to add items.
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Right Panel: Summary & Submission -->
            <div class="space-y-6">
                <!-- Summary Card -->
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 space-y-4">
                    <h2 class="text-sm font-semibold text-gray-700 border-b border-gray-100 pb-3">Invoice Summary</h2>

                    <div class="space-y-3 text-sm">
                        <div class="flex items-center justify-between text-gray-500">
                            <span>Subtotal (Excl. Tax)</span>
                            <span class="font-mono text-gray-700" x-text="formatCurrency(totals.subtotal)"></span>
                        </div>
                        <div class="flex items-center justify-between text-gray-500" x-show="totals.discount > 0">
                            <span>Item Discount</span>
                            <span class="font-mono text-emerald-600" x-text="'- ' + formatCurrency(totals.discount)"></span>
                        </div>
                        <div class="flex items-center justify-between text-gray-500">
                            <span>Sales Tax Amount</span>
                            <span class="font-mono text-indigo-600" x-text="'+ ' + formatCurrency(totals.sales_tax)"></span>
                        </div>
                        <div class="flex items-center justify-between text-gray-500">
                            <span>Further Tax</span>
                            <span class="font-mono text-indigo-600" x-text="'+ ' + formatCurrency(totals.further_tax)"></span>
                        </div>
                        <div class="flex items-center justify-between text-gray-500">
                            <span>Advance Tax</span>
                            <span class="font-mono text-indigo-600" x-text="'+ ' + formatCurrency(totals.advance_tax)"></span>
                        </div>
                        <div class="rounded-xl bg-indigo-50/60 border border-indigo-100 px-4 py-3 flex items-center justify-between font-bold text-gray-800 text-base mt-1">
                            <span>Grand Total</span>
                            <span class="font-mono text-indigo-700" x-text="formatCurrency(totals.grand_total)"></span>
                        </div>
                    </div>

                    <!-- Sync options -->
                    <div class="pt-2 border-t border-gray-100 space-y-3">
                        <div class="flex items-center gap-2 pt-2">
                            <input type="checkbox" x-model="form.sync_immediately" id="sync_immediately"
                                   class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-400">
                            <label for="sync_immediately" class="text-xs text-gray-600 font-medium">Sync immediately with FBR</label>
                        </div>
                    </div>

                    <div class="flex flex-col gap-2 pt-2">
                        <button type="submit" :disabled="saving"
                                class="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 disabled:opacity-50 transition shadow-sm shadow-indigo-200">
                            <svg x-show="saving" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                            </svg>
                            <span x-text="saving ? 'Saving...' : (form.sync_immediately ? 'Update & Sync' : 'Update Draft')"></span>
                        </button>
                    </div>
                </div>

                <!-- Notes Card -->
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 space-y-3">
                    <h2 class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Invoice Notes</h2>
                    <textarea x-model="form.notes" rows="3" placeholder="Add optional remarks or terms..."
                              class="w-full rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400"></textarea>
                </div>
            </div>
        </form>

    <script>
        function invoiceForm() {
            return {
                customers: [],
                items: [],
                scenarios: [
                    { id: 'SN001', name: 'SN001', desc: 'Goods at Standard Rate (Registered Buyer)' },
                    { id: 'SN002', name: 'SN002', desc: 'Goods at Standard Rate (Unregistered Buyer)' },
                    { id: 'SN003', name: 'SN003', desc: '3rd Schedule Goods (Retail Price)' },
                    { id: 'SN004', name: 'SN004', desc: 'Goods at Reduced Rate' },
                    { id: 'SN005', name: 'SN005', desc: 'Goods at Zero-Rate' },
                    { id: 'SN006', name: 'SN006', desc: 'Exempt Goods' },
                    { id: 'SN007', name: 'SN007', desc: 'Petroleum Products' },
                    { id: 'SN008', name: 'SN008', desc: 'Services at Standard/Reduced Rates' },
                    { id: 'SN009', name: 'SN009', desc: 'Export Sales' },
                    { id: 'SN010', name: 'SN010', desc: 'Sales to Government/Withholding Agent' },
                    { id: 'SN011', name: 'SN011', desc: 'Standard Rate with Extra Tax' },
                    { id: 'SN012', name: 'SN012', desc: 'Standard Rate with Further Tax' },
                    { id: 'SN013', name: 'SN013', desc: 'Debit/Credit Note adjustments' },
                    { id: 'SN014', name: 'SN014', desc: 'Import Stage Transactions' },
                    { id: 'SN015', name: 'SN015', desc: 'Gas/Electricity Utility Bills' },
                    { id: 'SN016', name: 'SN016', desc: 'Steel/Sugar sector special tax regime' },
                    { id: 'SN017', name: 'SN017', desc: 'Tier-1 Retailer POS Integration' },
                    { id: 'SN018', name: 'SN018', desc: 'Reduced Rate under Schedule 8' },
                    { id: 'SN019', name: 'SN019', desc: 'Sales to Active Filer' },
                    { id: 'SN020', name: 'SN020', desc: 'Sales to Non-Active Taxpayer' },
                    { id: 'SN021', name: 'SN021', desc: 'Toll Manufacturing Transactions' },
                    { id: 'SN022', name: 'SN022', desc: 'Sales of Exempt Goods by Wholesalers' },
                    { id: 'SN023', name: 'SN023', desc: 'Special Excise Duty' },
                    { id: 'SN024', name: 'SN024', desc: 'Sales with Multiple Tax Rates' },
                    { id: 'SN025', name: 'SN025', desc: 'B2B Wholesale Distribution' },
                    { id: 'SN026', name: 'SN026', desc: 'Sales through Online Marketplace' },
                    { id: 'SN027', name: 'SN027', desc: 'Corporate Taxpayer Bulk Sales' },
                    { id: 'SN028', name: 'SN028', desc: 'General Sales Tax on Services (ICT)' },
                ],
                selectedCustomer: null,
                saving: false,
                errors: {},
                form: {
                    customer_id: '{{ $invoice->customer_id }}',
                    invoice_date: '{{ $invoice->invoice_date->format('Y-m-d') }}',
                    scenario_id: '{{ $invoice->scenario_id ?? 'SN001' }}',
                    notes: {!! json_encode($invoice->notes) !!},
                    local_invoice_no: '{{ $invoice->local_invoice_no }}',
                    sync_immediately: false,
                    items: [],
                },
                totals: {
                    subtotal: 0,
                    sales_tax: 0,
                    further_tax: 0,
                    advance_tax: 0,
                    discount: 0,
                    grand_total: 0,
                },
                showDiscountModal: false,
                activeItemIndex: null,
                discountForm: {
                    type: "fixed",
                    value: 0
                },
                openDiscountModal(idx) {
                    this.activeItemIndex = idx;
                    const row = this.form.items[idx];
                    this.discountForm.type = row.discount_type || "fixed";
                    this.discountForm.value = row.discount_value || 0;
                    this.showDiscountModal = true;
                },
                applyDiscount() {
                    if (this.activeItemIndex === null) return;
                    const row = this.form.items[this.activeItemIndex];
                    row.discount_type = this.discountForm.type;
                    row.discount_value = Number(this.discountForm.value) || 0;
                    this.recalculateRow(this.activeItemIndex);
                    this.showDiscountModal = false;
                },
                unwrap(res) {
                    const payload = res && typeof res === 'object' && 'data' in res ? res.data : res;
                    return Array.isArray(payload) ? payload : [];
                },
                async searchHsCode() {
                    this.hsHighlight = 0;
                    if (this.hsSearch.trim().length < 2) { this.hsResults = []; this.hsOpen = true; return; }
                    this.hsLoading = true;
                    this.hsOpen = true;
                    try {
                        const res = await apiFetch(`/fbr/item-codes?search=${encodeURIComponent(this.hsSearch.trim())}`);
                        this.hsResults = this.unwrap(res).map(r => ({
                            code: r.hS_CODE ?? r.HS_CODE ?? r.code ?? r.hsCode ?? '',
                            desc: r.hS_DESC ?? r.HS_DESC ?? r.description ?? r.desc ?? '',
                        }));
                    } catch (e) {
                        this.hsResults = [];
                    } finally {
                        this.hsLoading = false;
                    }
                },
                moveHsHighlight(dir) {
                    if (!this.hsResults.length) return;
                    this.hsHighlight = (this.hsHighlight + dir + this.hsResults.length) % this.hsResults.length;
                },
                selectHsCode(row) {
                    this.quickItem.hs_code = row.code;
                    this.hsSearch = `${row.code} — ${row.desc}`;
                    this.hsOpen = false;
                    this.uomManualEntry = false;
                    this.quickItem.uom = '';
                    this.fetchUom(row.code);
                },
                clearHsCode() {
                    this.hsSearch = '';
                    this.quickItem.hs_code = '';
                    this.hsResults = [];
                    this.uomOptions = [];
                    this.quickItem.uom = '';
                    this.uomManualEntry = false;
                },
                async fetchUom(hsCode) {
                    this.uomLoading = true;
                    this.uomOptions = [];
                    try {
                        const res = await apiFetch(`/fbr/hs-uom?hs_code=${encodeURIComponent(hsCode)}&annexure_id=3`);
                        this.uomOptions = this.unwrap(res)
                            .map(u => u.description ?? u.uoM ?? u.uom ?? u.desc)
                            .filter(Boolean);
                        if (this.uomOptions.length === 1) this.quickItem.uom = this.uomOptions[0];
                        if (this.uomOptions.length === 0) this.uomManualEntry = true;
                    } catch (e) {
                        this.uomManualEntry = true;
                    } finally {
                        this.uomLoading = false;
                    }
                },
                async fetchRates() {
                    this.rateOptions = [];
                    this.selectedRateId = '';
                    if (!this.transTypeId || !this.rateDate) return;
                    this.ratesLoading = true;
                    try {
                        const res = await apiFetch(`/fbr/sale-type-to-rate?date=${this.rateDate}&trans_type_id=${this.transTypeId}&origination_supplier=1`);
                        this.rateOptions = this.unwrap(res).map(r => ({
                            id: r.ratE_ID ?? r.rate_id ?? r.id,
                            desc: r.ratE_DESC ?? r.description ?? r.desc ?? `${r.ratE_VALUE ?? ''}%`,
                        }));
                    } catch (e) {
                    } finally {
                        this.ratesLoading = false;
                    }
                },
                applyRate() {
                    const rate = this.rateOptions.find(r => String(r.id) === String(this.selectedRateId));
                    if (!rate) return;
                    this.quickItem.default_rate = rate.desc;
                    const type = this.transTypes.find(t => String(t.id) === String(this.transTypeId));
                    this.quickItem.default_sale_type = type ? type.desc : '';
                },
                async submitQuickItem() {
                    try {
                        const res = await apiFetch('/items', {
                            method: 'POST',
                            body: this.quickItem
                        });
                        if (res.success) {
                            this.items.push(res.data);
                            this.selectItem(res.data);
                            this.openQuickItemModal = false;
                            this.quickItem = {
                                name: '',
                                sku: '',
                                hs_code: '',
                                uom: '',
                                default_rate: '',
                                default_price_excl_st: '',
                                default_sale_type: ''
                            };
                            this.clearHsCode();
                            this.transTypeId = '';
                            this.rateOptions = [];
                            this.selectedRateId = '';
                            notify('Item added and selected.', 'success');
                        }
                    } catch (e) {
                        notify(e.message || 'Validation error while saving item.', 'error');
                    }
                },
                async init() {
                    try {
                        const custRes = await apiFetch('/customers/data?active_only=1&per_page=100');
                        this.customers = custRes.data || [];
                        const initialCust = this.customers.find(c => c.id == this.form.customer_id);
                        if (initialCust) this.selectCustomer(initialCust);


                        const transRes = await apiFetch('/fbr/transaction-types');
                        this.transTypes = this.unwrap(transRes).map(t => ({
                            id: t.transactioN_TYPE_ID ?? t.trans_type_id ?? t.id,
                            desc: t.transactioN_DESC ?? t.description ?? t.desc ?? `Type ${t.id ?? ''}`,
                        }));
                    } catch (e) {}

                    // Load current invoice items
                    const loadedItems = {!! json_encode($invoice->items->load('item')) !!} || [];
                    loadedItems.forEach(row => {
                        this.form.items.push({
                            item_id: row.item_id,
                            product_name: row.item?.name || row.product_description,
                            product_description: row.product_description,
                            sku: row.item?.sku || '',
                            hs_code: row.hs_code,
                            quantity: Number(row.quantity),
                            value_sales_excluding_st: Number(row.value_sales_excluding_st),
                            rate: row.rate,
                            uom: row.uom || 'Nos',
                            sale_type: row.sale_type || 'Goods',
                            further_tax_type: 'fixed',
                            further_tax_value: Number(row.further_tax),
                            further_tax: Number(row.further_tax),
                            advance_tax_type: 'fixed',
                            advance_tax_value: Number(row.extra_tax),
                            extra_tax: Number(row.extra_tax),
                            sales_tax_applicable: Number(row.sales_tax_applicable),
                            total_values: Number(row.total_values),
                            discount_type: row.discount_type || 'fixed',
                            discount_value: Number(row.discount_value) || 0,
                            discount: Number(row.discount) || 0,
                        });
                    });

                    this.recalculateTotals();
                },
                selectCustomer(c) {
                    this.selectedCustomer = c;
                    this.form.customer_id = c.id;
                },
                selectItem(item) {
                    this.form.items.push({
                        item_id: item.id,
                        product_name: item.name,
                        product_description: item.name,
                        sku: item.sku,
                        hs_code: item.hs_code,
                        quantity: 1,
                        value_sales_excluding_st: Number(item.default_price_excl_st) || 0,
                        rate: item.default_rate || '18%',
                        uom: item.uom || 'Nos',
                        sale_type: item.default_sale_type || 'Goods',
                        further_tax_type: 'percent',
                        further_tax_value: 0,
                        further_tax: 0,
                        advance_tax_type: 'percent',
                        advance_tax_value: 0,
                        extra_tax: 0,
                        sales_tax_applicable: 0,
                        total_values: 0,
                        discount_type: 'fixed',
                        discount_value: 0,
                        discount: 0,
                    });
                    this.recalculateRow(this.form.items.length - 1);
                },
                removeItemRow(idx) {
                    this.form.items.splice(idx, 1);
                    this.recalculateTotals();
                },
                recalculateRow(idx) {
                    const row = this.form.items[idx];
                    const grossSubtotal = (Number(row.value_sales_excluding_st) || 0) * (Number(row.quantity) || 1);

                    if (row.discount_type === undefined) row.discount_type = 'fixed';
                    if (row.discount_value === undefined) row.discount_value = 0;
                    if (row.discount === undefined) row.discount = 0;

                    if (row.discount_type === 'percent') {
                        row.discount = grossSubtotal * ((Number(row.discount_value) || 0) / 100);
                    } else {
                        row.discount = Number(row.discount_value) || 0;
                    }

                    const netSubtotal = grossSubtotal - row.discount;

                    row.sales_tax_applicable = netSubtotal * ((parseFloat(row.rate) || 0) / 100);

                    if (row.further_tax_type === 'percent') {
                        row.further_tax = netSubtotal * ((Number(row.further_tax_value) || 0) / 100);
                    } else {
                        row.further_tax = Number(row.further_tax_value) || 0;
                    }

                    if (row.advance_tax_type === 'percent') {
                        row.extra_tax = netSubtotal * ((Number(row.advance_tax_value) || 0) / 100);
                    } else {
                        row.extra_tax = Number(row.advance_tax_value) || 0;
                    }

                    row.total_values = netSubtotal + row.sales_tax_applicable + row.further_tax + row.extra_tax;
                    this.recalculateTotals();
                },
                recalculateTotals() {
                    let sub = 0;
                    let tax = 0;
                    let further = 0;
                    let advance = 0;
                    let discount = 0;

                    this.form.items.forEach(row => {
                        const rowSub = (Number(row.value_sales_excluding_st) || 0) * (Number(row.quantity) || 1);
                        sub += rowSub;
                        tax += Number(row.sales_tax_applicable) || 0;
                        further += Number(row.further_tax) || 0;
                        advance += Number(row.extra_tax) || 0;
                        discount += Number(row.discount) || 0;
                    });

                    this.totals.subtotal = sub;
                    this.totals.sales_tax = tax;
                    this.totals.further_tax = further;
                    this.totals.advance_tax = advance;
                    this.totals.discount = discount;
                    this.totals.grand_total = sub + tax + further + advance - discount;
                },
                async submit() {
                    this.errors = {};
                    this.saving = true;
                    try {
                        const res = await apiFetch('/invoices/{{ $invoice->id }}', { method: 'PUT', body: this.form });
                        if (res.success === false && res.sync_error) {
                            notify(`Draft updated, but FBR Sync failed: ${res.sync_error}`, 'error');
                            flashAndRedirect('Invoice draft updated (FBR sync failed).', 'warning', '{{ route('invoices.index') }}');
                        } else {
                            notify('Invoice updated successfully.', 'success');
                            flashAndRedirect('Invoice updated successfully.', 'success', '{{ route('invoices.index') }}');
                        }
                    } catch (e) {
                        if (e.status === 422) this.errors = e.errors;
                    } finally {
                        this.saving = false;
                    }
                },
            };
        }
    </script>
        <!-- Quick Add Item Modal -->
        <div x-show="openQuickItemModal" x-cloak class="fixed inset-0 z-50 overflow-y-auto"
            aria-labelledby="modal-title" role="dialog" aria-modal="true">
            <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
                    @click="openQuickItemModal = false"></div>
                <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
                <div
                    class="inline-block align-middle bg-white rounded-2xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                    <div class="bg-indigo-600 px-6 py-4 flex items-center justify-between">
                        <h3 class="text-base font-bold text-white">Quick Add Item</h3>
                        <button type="button" @click="openQuickItemModal = false"
                            class="text-indigo-200 hover:text-white transition">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                    <form @submit.prevent="submitQuickItem()">
                        <div class="p-6 grid grid-cols-2 gap-4">
                            <div class="col-span-2">
                                <label
                                    class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Product
                                    Name <span class="text-red-500">*</span></label>
                                <input type="text" x-model="quickItem.name" required
                                    class="w-full rounded-xl border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400">
                            </div>
                            <div>
                                <label
                                    class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">SKU</label>
                                <input type="text" x-model="quickItem.sku"
                                    class="w-full rounded-xl border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400">
                            </div>

                            <!-- Dynamic HS Code Typeahead -->
                            <div class="relative">
                                <label
                                    class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">HS
                                    Code <span class="text-red-500">*</span></label>
                                <div class="relative">
                                    <input type="text" x-model="hsSearch" @input.debounce.350ms="searchHsCode()"
                                        @keydown.arrow-down.prevent="moveHsHighlight(1)"
                                        @keydown.arrow-up.prevent="moveHsHighlight(-1)"
                                        @keydown.enter.prevent="hsResults[hsHighlight] && selectHsCode(hsResults[hsHighlight])"
                                        @keydown.escape="hsOpen = false" @focus="hsResults.length && (hsOpen = true)"
                                        @click.outside="hsOpen = false" placeholder="Search HS code..."
                                        autocomplete="off"
                                        class="w-full rounded-xl border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 pr-7"
                                        required>
                                    <button type="button" x-show="hsSearch" @click="clearHsCode()"
                                        class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-300 hover:text-gray-500 text-xs">✕</button>
                                </div>
                                <input type="hidden" x-model="quickItem.hs_code">

                                <div x-show="hsOpen" x-cloak
                                    class="absolute z-50 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-40 overflow-y-auto">
                                    <template x-if="hsSearch.trim().length < 2">
                                        <p class="px-3 py-2 text-[10px] text-gray-400">Type 2+ characters to search...
                                        </p>
                                    </template>
                                    <template x-if="hsSearch.trim().length >= 2 && hsLoading">
                                        <p class="px-3 py-2 text-[10px] text-gray-400 flex items-center gap-2">
                                            <span
                                                class="inline-block h-3 w-3 rounded-full border-2 border-indigo-300 border-t-transparent animate-spin"></span>
                                            Searching FBR...
                                        </p>
                                    </template>
                                    <template
                                        x-if="hsSearch.trim().length >= 2 && !hsLoading && hsResults.length === 0">
                                        <p class="px-3 py-2 text-[10px] text-gray-400">No matches found.</p>
                                    </template>
                                    <template x-for="(row, i) in hsResults" :key="row.code">
                                        <button type="button" @click="selectHsCode(row)" @mouseenter="hsHighlight = i"
                                            class="w-full text-left px-3 py-1.5 text-[10px] border-b border-gray-50 last:border-0"
                                            :class="i === hsHighlight ? 'bg-indigo-50' : 'hover:bg-gray-50'">
                                            <span class="font-medium text-gray-700" x-text="row.code"></span>
                                            <span class="text-gray-400 block truncate" x-text="row.desc"></span>
                                        </button>
                                    </template>
                                </div>
                            </div>

                            <!-- Dynamic UOM Dropdown -->
                            <div>
                                <label
                                    class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">UoM
                                    <span class="text-red-500">*</span></label>
                                <template x-if="!uomManualEntry">
                                    <select x-model="quickItem.uom" :disabled="!quickItem.hs_code"
                                        class="w-full rounded-xl border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 disabled:bg-gray-50 disabled:text-gray-400"
                                        required>
                                        <option value="">-- select --</option>
                                        <template x-for="u in uomOptions" :key="u">
                                            <option :value="u" x-text="u"></option>
                                        </template>
                                    </select>
                                </template>
                                <template x-if="uomManualEntry">
                                    <input type="text" x-model="quickItem.uom" placeholder="Enter UoM manually"
                                        class="w-full rounded-xl border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400"
                                        required>
                                </template>
                                <div class="mt-1 flex items-center justify-between text-[9px] text-gray-400">
                                    <span x-show="!quickItem.hs_code">Select HS Code first</span>
                                    <button type="button" x-show="quickItem.hs_code"
                                        class="underline text-indigo-500 hover:text-indigo-700"
                                        @click="uomManualEntry = !uomManualEntry"
                                        x-text="uomManualEntry ? 'Select from list' : 'Enter manual UoM'"></button>
                                </div>
                            </div>

                            <!-- Dynamic Transaction Type -->
                            <div>
                                <label
                                    class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Transaction
                                    Type</label>
                                <select x-model="transTypeId" @change="fetchRates()"
                                    class="w-full rounded-xl border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400">
                                    <option value="">-- select --</option>
                                    <template x-for="t in transTypes" :key="t.id">
                                        <option :value="t.id" x-text="t.desc"></option>
                                    </template>
                                </select>
                            </div>

                            <!-- Dynamic Rate Selection -->
                            <div>
                                <label
                                    class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Default
                                    Rate <span class="text-red-500">*</span></label>
                                <select x-model="selectedRateId" @change="applyRate()" :disabled="!transTypeId"
                                    class="w-full rounded-xl border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 disabled:bg-gray-50 disabled:text-gray-400"
                                    required>
                                    <option value="">-- select type first --</option>
                                    <template x-for="r in rateOptions" :key="r.id">
                                        <option :value="r.id" x-text="r.desc"></option>
                                    </template>
                                </select>
                            </div>

                            <div>
                                <label
                                    class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Price
                                    (Excl. Tax) <span class="text-red-500">*</span></label>
                                <input type="number" step="0.01" x-model="quickItem.default_price_excl_st" required
                                    class="w-full rounded-xl border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400">
                            </div>

                            <div>
                                <label
                                    class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Sale
                                    Type</label>
                                <select x-model="quickItem.default_sale_type"
                                    class="w-full rounded-xl border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400">
                                    <option value="Goods">Goods</option>
                                    <option value="Services">Services</option>
                                </select>
                            </div>
                        </div>
                        <div class="bg-gray-50 px-6 py-4 flex justify-end gap-2 border-t border-gray-100">
                            <button type="button" @click="openQuickItemModal = false"
                                class="px-4 py-2 border border-gray-200 rounded-xl text-xs font-semibold text-gray-600 hover:bg-gray-100 transition">Cancel</button>
                            <button type="submit"
                                class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-semibold transition shadow-sm shadow-indigo-200">Save
                                Item</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    <!-- Item Discount Modal -->
    <div x-show="showDiscountModal" class="fixed inset-0 z-50 overflow-y-auto" x-cloak>
        <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75" @click="showDiscountModal = false"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen">&#8203;</span>
            <div class="inline-block overflow-hidden text-left align-bottom transition-all transform bg-white rounded-2xl shadow-xl sm:my-8 sm:align-middle sm:max-w-md sm:w-full">
                <div class="bg-indigo-600 px-6 py-4 flex items-center justify-between">
                    <h3 class="text-base font-bold text-white flex items-center gap-2">
                        <svg class="w-5 h-5 text-indigo-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5a2 2 0 10-2 2h2zm0 0h4m-4 0H8m12 3a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        Apply Item Discount
                    </h3>
                    <button type="button" @click="showDiscountModal = false" class="text-indigo-200 hover:text-white transition">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <form @submit.prevent="applyDiscount()">
                    <div class="p-6 space-y-4">
                        <div>
                            <label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Discount Type</label>
                            <div class="grid grid-cols-2 gap-2">
                                <label class="border rounded-xl p-3 flex items-center justify-center gap-2 cursor-pointer transition"
                                       :class="discountForm.type === 'percent' ? 'border-indigo-600 bg-indigo-50/50 text-indigo-700 font-semibold' : 'border-gray-200 hover:bg-gray-50 text-gray-600'">
                                    <input type="radio" x-model="discountForm.type" value="percent" class="sr-only">
                                    <span>Percentage (%)</span>
                                </label>
                                <label class="border rounded-xl p-3 flex items-center justify-center gap-2 cursor-pointer transition"
                                       :class="discountForm.type === 'fixed' ? 'border-indigo-600 bg-indigo-50/50 text-indigo-700 font-semibold' : 'border-gray-200 hover:bg-gray-50 text-gray-600'">
                                    <input type="radio" x-model="discountForm.type" value="fixed" class="sr-only">
                                    <span>Fixed Amount (Rs)</span>
                                </label>
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2" x-text="discountForm.type === 'percent' ? 'Discount Percentage (%)' : 'Discount Amount (Rs)'"></label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 pl-3.5 flex items-center text-gray-400 font-semibold text-xs" x-text="discountForm.type === 'percent' ? '%' : 'Rs.'"></span>
                                <input type="number" step="0.01" min="0" x-model.number="discountForm.value" required
                                       class="w-full rounded-xl border-gray-200 pl-10 pr-4 py-2.5 text-sm focus:border-indigo-500 focus:ring-indigo-500 font-semibold">
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-6 py-4 flex justify-end gap-2 border-t border-gray-100">
                        <button type="button" @click="showDiscountModal = false" class="px-4 py-2 border border-gray-200 rounded-xl text-xs font-semibold text-gray-600 hover:bg-gray-100 transition">Cancel</button>
                        <button type="submit" class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-semibold transition shadow-sm shadow-indigo-200">Apply Discount</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    </div>
</x-app-layout>