@extends('layouts.admin')

@section('title', 'Create Variant Product')

@section('content')
@php
    $defaultShipping = old('shipping_days', \App\Models\Setting::get('default_shipping_days'));
@endphp

<div class="vp-page">
<x-admin.form-page
    title="Create Variant Product"
    subtitle="Pick attributes once — every combination is generated with its own price and stock."
    :crumbs="[['label' => 'Products', 'url' => route('admin.products.index', ['type' => 'variant'])], 'Create Variant']"
    :back-url="route('admin.products.index', ['type' => 'variant'])"
    :action="route('admin.products.variant.store')"
    form-id="variantProductForm"
    submit-label="Create variants"
    submit-label-id="vpHeaderSubmit"
    enctype="multipart/form-data"
>
    <input type="hidden" name="product_type" value="variant">

    {{-- Basic Information --}}
    <section class="pp-card">
        <div class="pp-card__head">
            <span class="pp-card__icon"><i class="bi bi-info-circle"></i></span>
            <div>
                <h2 class="pp-card__title">Basic Information</h2>
                <p class="pp-card__sub">Name, category, brand and visibility</p>
            </div>
        </div>
        <div class="pp-card__body">
            <div class="pp-grid pp-grid--2">
                <div class="pp-field">
                    <label for="vpName">Product Name <span class="pp-req">*</span></label>
                    <input type="text" name="name" id="vpName" class="form-control @error('name') is-invalid @enderror"
                           value="{{ old('name') }}" required placeholder="Enter product name">
                    @error('name')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                </div>
                <div class="pp-field">
                    <label for="vpCategory">Category <span class="pp-req">*</span></label>
                    <select name="category_id" id="vpCategory" class="form-select @error('category_id') is-invalid @enderror" required>
                        <option value="">Select Category</option>
                        @foreach ($categories as $category)
                            <option value="{{ $category->id }}" {{ (string) old('category_id') === (string) $category->id ? 'selected' : '' }}>
                                {{ $category->name }}
                            </option>
                        @endforeach
                    </select>
                    @error('category_id')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                </div>
                <div class="pp-field">
                    <label for="vpBrand">Brand</label>
                    <select name="brand_id" id="vpBrand" class="form-select">
                        <option value="">Select Brand</option>
                        @foreach ($brands as $brand)
                            @php
                                $brandSelected = old('brand_id') !== null
                                    ? (string) old('brand_id') === (string) $brand->id
                                    : $loop->first;
                            @endphp
                            <option value="{{ $brand->id }}" {{ $brandSelected ? 'selected' : '' }}>
                                {{ $brand->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="pp-field">
                    <label for="vpUnit">Unit</label>
                    <select name="unit_id" id="vpUnit" class="form-select">
                        <option value="">Select Unit</option>
                        @foreach ($units as $unit)
                            <option value="{{ $unit->id }}" {{ (string) old('unit_id') === (string) $unit->id ? 'selected' : '' }}>
                                {{ ucfirst($unit->name) }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="pp-field">
                    <label for="vpTax">Tax</label>
                    <select name="tax_id" id="vpTax" class="form-select">
                        <option value="" data-rate="0">No Tax</option>
                        @foreach ($taxes as $tax)
                            @php
                                $taxSelected = old('tax_id') !== null
                                    ? (string) old('tax_id') === (string) $tax->id
                                    : $loop->first;
                            @endphp
                            <option value="{{ $tax->id }}" data-rate="{{ $tax->rate }}" {{ $taxSelected ? 'selected' : '' }}>
                                {{ $tax->name }} — {{ number_format($tax->rate, 2) }}%
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="pp-field">
                    <label for="barcode">Barcode</label>
                    <div class="pp-barcode-row">
                        <input type="text" name="barcode" id="barcode" class="form-control"
                               value="{{ old('barcode') }}" maxlength="8" placeholder="Auto-generated">
                        <button type="button" class="pp-btn pp-btn--ghost" onclick="generateNewBarcode()" title="Generate barcode">
                            <i class="bi bi-arrow-clockwise"></i>
                        </button>
                    </div>
                    <span class="pp-hint">Leave blank to auto-generate an 8-digit barcode</span>
                </div>
                <div class="pp-field">
                    <label for="vpShippingDays">Shipping Days</label>
                    <input type="number" name="shipping_days" id="vpShippingDays" class="form-control"
                           value="{{ $defaultShipping }}" min="0" placeholder="e.g. 3">
                </div>
                <div class="pp-field">
                    <label for="vpImage">Product Image</label>
                    <input type="file" name="image" id="vpImage" class="form-control"
                           accept="image/jpeg,image/png,image/jpg,image/webp">
                </div>
            </div>

            <div class="pp-field mt-3">
                <label for="productTagsTextarea">Product Tags</label>
                <input type="text" id="productTagsTextarea" class="form-control pp-tags-input"
                       placeholder="Add a tag" autocomplete="off">
                <input type="hidden" name="tags" id="productTagsHidden" value="{{ old('tags') }}">
                <div class="pp-tags" id="tagsDisplay"></div>
                <span class="pp-hint">Press Enter or comma to add tags</span>
            </div>

            <div class="pp-field mt-3">
                <label for="vpShortDesc">Short Description</label>
                <textarea name="short_desc" id="vpShortDesc" class="form-control" rows="2"
                          placeholder="Short product description">{{ old('short_desc') }}</textarea>
            </div>

            <div class="pp-toggles mt-3">
                <label class="pp-toggle" for="isActive">
                    <input type="hidden" name="is_active" value="0">
                    <input type="checkbox" class="form-check-input" role="switch" name="is_active" id="isActive"
                           value="1" {{ old('is_active', true) ? 'checked' : '' }}>
                    Active
                </label>
                <label class="pp-toggle" for="isFeatured">
                    <input type="hidden" name="is_featured" value="0">
                    <input type="checkbox" class="form-check-input" role="switch" name="is_featured" id="isFeatured"
                           value="1" {{ old('is_featured') ? 'checked' : '' }}>
                    Featured
                </label>
                <label class="pp-toggle" for="isVerified">
                    <input type="hidden" name="is_verified" value="0">
                    <input type="checkbox" class="form-check-input" role="switch" name="is_verified" id="isVerified"
                           value="1" {{ old('is_verified') ? 'checked' : '' }}>
                    Verified
                </label>
                <label class="pp-toggle" for="isPrebooking">
                    <input type="checkbox" class="form-check-input" role="switch" name="is_prebooking" id="isPrebooking"
                           value="1" {{ old('is_prebooking') ? 'checked' : '' }}>
                    Pre-booking
                </label>
            </div>

            <div class="pp-field mt-3">
                <label for="vpChannel">Show Product In <span class="pp-req">*</span></label>
                <select name="channel_visibility" id="vpChannel" class="form-select" required>
                    <option value="both" {{ old('channel_visibility', 'both') === 'both' ? 'selected' : '' }}>Both POS and Website</option>
                    <option value="website_only" {{ old('channel_visibility') === 'website_only' ? 'selected' : '' }}>Only Website</option>
                    <option value="pos_only" {{ old('channel_visibility') === 'pos_only' ? 'selected' : '' }}>Only POS</option>
                </select>
            </div>
        </div>
    </section>

    {{-- Variant Attributes --}}
    <section class="pp-card">
        <div class="pp-card__head">
            <span class="pp-card__icon"><i class="bi bi-tags"></i></span>
            <div class="vp-attr-head">
                <div>
                    <h2 class="pp-card__title">Variant Attributes</h2>
                    <p class="pp-card__sub">Select values — combinations generate automatically</p>
                </div>
                <span id="combinationCountBadge" class="vp-combo-badge">0 combinations</span>
            </div>
        </div>
        <div class="pp-card__body">
            @forelse ($attributes as $attribute)
                <div class="vp-attr-group" data-attribute-id="{{ $attribute->id }}">
                    <div class="vp-attr-group__bar">
                        <div class="vp-attr-group__title">
                            <strong>{{ $attribute->name }}</strong>
                            <span class="vp-attr-selected-count" data-count-for="{{ $attribute->id }}">0 selected</span>
                        </div>
                        <div class="vp-attr-group__tools">
                            <input type="search" class="form-control form-control-sm vp-attr-search"
                                   placeholder="Search {{ strtolower($attribute->name) }}…"
                                   data-search-for="{{ $attribute->id }}"
                                   autocomplete="off">
                            <button type="button" class="pp-btn pp-btn--ghost vp-attr-clear"
                                    data-clear-for="{{ $attribute->id }}">Clear</button>
                        </div>
                    </div>
                    <div class="attribute-checkboxes" data-attribute-id="{{ $attribute->id }}" data-attribute-name="{{ $attribute->name }}">
                        @foreach ($attribute->activeValues as $value)
                            <label class="attribute-checkbox-item"
                                   data-search-text="{{ strtolower($value->value) }}">
                                <input type="checkbox"
                                       name="attributes[{{ $attribute->id }}][]"
                                       value="{{ $value->id }}"
                                       data-attribute-id="{{ $attribute->id }}"
                                       data-attribute-name="{{ $attribute->name }}"
                                       data-value-name="{{ $value->value }}"
                                       onchange="updateVariantCombinations()">
                                <span>{{ $value->value }}</span>
                            </label>
                        @endforeach
                    </div>
                </div>
            @empty
                <p class="pp-hint mb-0">No attributes configured. Add attributes before creating variant products.</p>
            @endforelse
        </div>
    </section>

    {{-- Variant Details --}}
    <section class="pp-card" id="variantsSection" style="display: none;">
        <div class="pp-card__head">
            <span class="pp-card__icon"><i class="bi bi-box"></i></span>
            <div>
                <h2 class="pp-card__title">Variant Details</h2>
                <p class="pp-card__sub">Pricing and stock per combination — barcode &amp; ship days are automatic</p>
            </div>
        </div>
        <div class="pp-card__body">
            <div class="vp-bulk">
                <div class="vp-bulk__label">
                    Bulk apply to all <span id="bulkApplyCount">0</span> variants
                </div>
                <div class="vp-bulk__fields">
                    <div class="vp-bulk__field">
                        <label for="bulkPrice">Price</label>
                        <input type="number" step="0.01" min="0" id="bulkPrice" class="form-control form-control-sm" placeholder="0.00">
                    </div>
                    <div class="vp-bulk__field">
                        <label for="bulkMrp">MRP</label>
                        <input type="number" step="0.01" min="0" id="bulkMrp" class="form-control form-control-sm" placeholder="0.00">
                    </div>
                    <div class="vp-bulk__field">
                        <label for="bulkPurchasePrice">Purchase</label>
                        <input type="number" step="0.01" min="0" id="bulkPurchasePrice" class="form-control form-control-sm" placeholder="0.00">
                    </div>
                    <div class="vp-bulk__field">
                        <label for="bulkWholesalePrice">Wholesale</label>
                        <input type="number" step="0.01" min="0" id="bulkWholesalePrice" class="form-control form-control-sm" placeholder="0.00">
                    </div>
                    <div class="vp-bulk__field">
                        <label for="bulkOpeningStock">Stock</label>
                        <input type="number" min="0" id="bulkOpeningStock" class="form-control form-control-sm" placeholder="0">
                    </div>
                    <button type="button" class="pp-btn pp-btn--primary vp-bulk__apply" onclick="applyBulkAll()">Apply</button>
                </div>
            </div>

            <div class="variant-combinations-table">
                <table class="table table-sm vp-table">
                    <thead>
                        <tr>
                            <th>Variant</th>
                            <th>SKU</th>
                            <th>Purchase</th>
                            <th>Price <span class="pp-req">*</span></th>
                            <th>MRP</th>
                            <th>Wholesale</th>
                            <th>Stock <span class="pp-req">*</span></th>
                            <th>Margin</th>
                            <th>Image</th>
                        </tr>
                    </thead>
                    <tbody id="variantsTableBody"></tbody>
                </table>
            </div>
        </div>
    </section>

    <x-slot:aside>
        <section class="pp-card vp-summary">
            <div class="pp-card__head">
                <span class="pp-card__icon pp-card__icon--summary"><i class="bi bi-layers"></i></span>
                <div>
                    <h2 class="pp-card__title">Variant summary</h2>
                </div>
            </div>
            <div class="pp-card__body">
                <div class="vp-summary__stats">
                    <div class="vp-summary__stat">
                        <span class="vp-summary__stat-label">Combinations</span>
                        <span class="vp-summary__stat-value" id="vpSumCombos">0</span>
                    </div>
                    <div class="vp-summary__stat">
                        <span class="vp-summary__stat-label">Total stock</span>
                        <span class="vp-summary__stat-value" id="vpSumStock">0</span>
                    </div>
                    <div class="vp-summary__stat">
                        <span class="vp-summary__stat-label">Stock value</span>
                        <span class="vp-summary__stat-value" id="vpSumCost">₹0</span>
                    </div>
                    <div class="vp-summary__stat">
                        <span class="vp-summary__stat-label">Retail value</span>
                        <span class="vp-summary__stat-value" id="vpSumRetail">₹0</span>
                    </div>
                </div>

                <div class="vp-summary__chips">
                    <span class="vp-chip" id="vpSumCategory">Category —</span>
                    <span class="vp-chip" id="vpSumBrand">Brand —</span>
                    <span class="vp-chip" id="vpSumTax">Tax —</span>
                    <span class="vp-chip vp-chip--active" id="vpSumActive">Active</span>
                </div>

                <button type="submit" id="vpAsideSubmit" class="pp-btn pp-btn--primary pp-btn--block" disabled>
                    <i class="bi bi-save"></i> <span class="pp-submit-label">Create variants</span>
                </button>
                <p class="pp-hint mt-2 mb-0">Combinations update as you pick attributes.</p>
            </div>
        </section>
    </x-slot:aside>
</x-admin.form-page>
</div>
@endsection

@push('styles')
<style>
.vp-page {
    --vp-teal: var(--admin-primary, #0f766e);
    --vp-teal-soft: color-mix(in srgb, var(--vp-teal) 12%, #fff);
    --vp-teal-strong: color-mix(in srgb, var(--vp-teal) 18%, #fff);
    --vp-border: var(--admin-border-color, #e4e0d8);
    --vp-muted: var(--color-text-muted, #6b7280);
}

.vp-page .pp-toggles {
    margin-top: 0.25rem;
}

.vp-attr-head {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    justify-content: space-between;
    gap: 0.75rem;
    flex: 1;
    min-width: 0;
}

.vp-combo-badge {
    display: inline-flex;
    align-items: center;
    height: 1.75rem;
    padding: 0 0.7rem;
    border-radius: 999px;
    font-size: 0.75rem;
    font-weight: 650;
    background: var(--vp-teal-soft);
    color: var(--vp-teal);
    white-space: nowrap;
}

.vp-attr-group {
    padding: 1rem 0;
    border-bottom: 1px solid var(--vp-border);
}

.vp-attr-group:first-child {
    padding-top: 0;
}

.vp-attr-group:last-child {
    border-bottom: 0;
    padding-bottom: 0;
}

.vp-attr-group__bar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 0.75rem;
    margin-bottom: 0.75rem;
}

.vp-attr-group__title {
    display: flex;
    align-items: baseline;
    gap: 0.55rem;
}

.vp-attr-group__title strong {
    font-size: 0.92rem;
    color: var(--color-text, #161b26);
}

.vp-attr-selected-count {
    font-size: 0.78rem;
    color: var(--vp-muted);
}

.vp-attr-group__tools {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.45rem;
}

.vp-attr-search {
    width: 11rem;
    max-width: 100%;
    border-radius: 0.55rem;
}

.vp-attr-clear {
    height: 2rem;
    padding: 0 0.75rem;
    font-size: 0.8rem;
}

.vp-page .attribute-checkboxes {
    display: flex;
    flex-wrap: wrap;
    gap: 0.45rem;
}

.vp-page .attribute-checkbox-item {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.4rem 0.75rem;
    background: #fff;
    border: 1px solid var(--vp-border);
    border-radius: 999px;
    cursor: pointer;
    transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease, box-shadow 0.15s ease;
    font-size: 0.84rem;
    font-weight: 500;
    color: var(--color-text, #161b26);
    user-select: none;
}

.vp-page .attribute-checkbox-item:hover {
    border-color: color-mix(in srgb, var(--vp-teal) 40%, var(--vp-border));
    background: var(--vp-teal-soft);
}

.vp-page .attribute-checkbox-item input[type="checkbox"] {
    position: absolute;
    opacity: 0;
    pointer-events: none;
    width: 0;
    height: 0;
}

.vp-page .attribute-checkbox-item.selected,
.vp-page .attribute-checkbox-item:has(input:checked) {
    background: var(--vp-teal);
    border-color: var(--vp-teal);
    color: #fff;
    box-shadow: 0 1px 2px rgba(15, 118, 110, 0.22);
}

.vp-page .attribute-checkbox-item.is-hidden {
    display: none;
}

.vp-bulk {
    background: var(--vp-teal-soft);
    border: 1px solid color-mix(in srgb, var(--vp-teal) 18%, var(--vp-border));
    border-radius: 0.85rem;
    padding: 0.85rem 1rem;
    margin-bottom: 1rem;
}

.vp-bulk__label {
    font-size: 0.84rem;
    font-weight: 650;
    color: var(--vp-teal);
    margin-bottom: 0.65rem;
}

.vp-bulk__fields {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-end;
    gap: 0.55rem;
}

.vp-bulk__field {
    display: flex;
    flex-direction: column;
    gap: 0.2rem;
    min-width: 5.5rem;
}

.vp-bulk__field label {
    font-size: 0.72rem;
    font-weight: 600;
    color: var(--vp-muted);
    margin: 0;
}

.vp-bulk__field .form-control {
    width: 6.25rem;
    border-radius: 0.5rem;
}

.vp-bulk__apply {
    height: 2rem;
    padding: 0 1rem;
    font-size: 0.82rem;
}

.vp-page .variant-combinations-table {
    max-height: 28rem;
    overflow: auto;
    border: 1px solid var(--vp-border);
    border-radius: 0.85rem;
}

.vp-table {
    margin: 0;
    font-size: 0.82rem;
}

.vp-table thead th {
    position: sticky;
    top: 0;
    z-index: 2;
    background: #f8faf9;
    border-bottom: 1px solid var(--vp-border);
    font-size: 0.72rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.03em;
    color: var(--vp-muted);
    white-space: nowrap;
    padding: 0.65rem 0.5rem;
}

.vp-table td {
    vertical-align: middle;
    padding: 0.45rem 0.4rem;
    border-color: var(--vp-border);
}

.vp-table .form-control,
.vp-table .form-control-sm {
    font-size: 0.8rem;
    padding: 0.28rem 0.45rem;
    border-radius: 0.45rem;
    min-width: 4.5rem;
}

.vp-table .vp-variant-name {
    font-size: 0.8rem;
    font-weight: 650;
    line-height: 1.35;
    max-width: 12rem;
}

.vp-margin {
    font-weight: 700;
    font-size: 0.78rem;
    white-space: nowrap;
}

.vp-margin.is-pos { color: #059669; }
.vp-margin.is-neg { color: #dc2626; }
.vp-margin.is-empty { color: var(--vp-muted); font-weight: 500; }

.vp-image-box {
    position: relative;
    display: inline-flex;
    width: 3.25rem;
    height: 3.25rem;
    margin: 0;
    cursor: pointer;
}

.vp-image-box__input {
    position: absolute;
    inset: 0;
    opacity: 0;
    cursor: pointer;
    z-index: 2;
}

.vp-image-box__frame {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    border: 1.5px dashed var(--vp-border);
    border-radius: 0.65rem;
    background: #fafaf9;
    overflow: hidden;
    transition: border-color 0.15s ease, background 0.15s ease;
}

.vp-image-box:hover .vp-image-box__frame,
.vp-image-box.has-image .vp-image-box__frame {
    border-color: color-mix(in srgb, var(--vp-teal) 45%, var(--vp-border));
    background: var(--vp-teal-soft);
}

.vp-image-box__placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 0.1rem;
    color: var(--vp-muted);
    font-size: 0.62rem;
    font-weight: 650;
    line-height: 1;
    pointer-events: none;
}

.vp-image-box__placeholder i {
    font-size: 1rem;
}

.vp-image-box__preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

.vp-summary__stats {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.65rem;
    margin-bottom: 1rem;
}

.vp-summary__stat {
    background: var(--vp-teal-soft);
    border-radius: 0.7rem;
    padding: 0.65rem 0.7rem;
}

.vp-summary__stat-label {
    display: block;
    font-size: 0.7rem;
    color: var(--vp-muted);
    margin-bottom: 0.2rem;
}

.vp-summary__stat-value {
    display: block;
    font-size: 1rem;
    font-weight: 750;
    color: var(--color-text, #161b26);
    letter-spacing: -0.02em;
}

.vp-summary__chips {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem;
    margin-bottom: 1rem;
}

.vp-chip {
    display: inline-flex;
    align-items: center;
    max-width: 100%;
    padding: 0.28rem 0.6rem;
    border-radius: 999px;
    background: #f3f4f6;
    color: #374151;
    font-size: 0.72rem;
    font-weight: 600;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.vp-chip--active {
    background: var(--vp-teal-soft);
    color: var(--vp-teal);
}

.vp-chip--inactive {
    background: #fef2f2;
    color: #dc2626;
}

.vp-page .pp-btn:disabled,
.vp-page .pp-btn[disabled] {
    opacity: 0.55;
    cursor: not-allowed;
    box-shadow: none;
}
</style>
@endpush

@push('scripts')
<script>
@php
    $attributesDataForJs = $attributes->mapWithKeys(function ($attr) {
        return [
            $attr->id => [
                'name' => $attr->name,
                'values' => $attr->activeValues->map(function ($val) {
                    return ['id' => $val->id, 'value' => $val->value];
                })->values(),
            ],
        ];
    });
@endphp
const attributesData = @json($attributesDataForJs);

let variantCombinations = [];

function money(n) {
    const v = Math.round((n + Number.EPSILON) * 100) / 100;
    return '₹' + v.toLocaleString('en-IN', {
        minimumFractionDigits: v % 1 === 0 ? 0 : 2,
        maximumFractionDigits: 2,
    });
}

function selectedText(selectEl) {
    if (!selectEl || !selectEl.selectedOptions.length) return '—';
    const t = selectEl.selectedOptions[0].textContent.trim();
    return selectEl.value ? t.split('—')[0].trim() : '—';
}

function setSubmitDisabled(disabled) {
    document.querySelectorAll('button[form="variantProductForm"], #vpAsideSubmit').forEach((btn) => {
        btn.disabled = disabled;
    });
}

function updateSubmitLabels(n) {
    const label = n > 0 ? `Create ${n} variants` : 'Create variants';
    document.querySelectorAll('.pp-submit-label').forEach((el) => {
        el.textContent = label;
    });
    const badge = document.getElementById('combinationCountBadge');
    if (badge) {
        badge.textContent = n === 1 ? '1 combination' : `${n} combinations`;
    }
    const bulkCount = document.getElementById('bulkApplyCount');
    if (bulkCount) bulkCount.textContent = String(n);
}

function syncChipSelectedState(checkbox) {
    const label = checkbox.closest('.attribute-checkbox-item');
    if (label) label.classList.toggle('selected', checkbox.checked);
}

function updateAttributeSelectedCounts() {
    document.querySelectorAll('.vp-attr-group').forEach((group) => {
        const attrId = group.dataset.attributeId;
        const count = group.querySelectorAll('input[type="checkbox"]:checked').length;
        const el = group.querySelector(`[data-count-for="${attrId}"]`);
        if (el) el.textContent = `${count} selected`;
    });
}

function calcMargin(price, purchase) {
    const p = parseFloat(price) || 0;
    const c = parseFloat(purchase) || 0;
    if (p <= 0) return { text: '—', cls: 'is-empty' };
    const m = ((p - c) / p) * 100;
    return {
        text: (m >= 0 ? '' : '') + m.toFixed(1) + '%',
        cls: m >= 0 ? 'is-pos' : 'is-neg',
    };
}

function updateRowMargin(row) {
    if (!row) return;
    const price = row.querySelector('.variant-price')?.value;
    const purchase = row.querySelector('.variant-purchase_price')?.value;
    const cell = row.querySelector('.vp-margin');
    if (!cell) return;
    const m = calcMargin(price, purchase);
    cell.textContent = m.text;
    cell.className = 'vp-margin ' + m.cls;
}

function refreshSummary() {
    const n = variantCombinations.length;
    const combosEl = document.getElementById('vpSumCombos');
    const stockEl = document.getElementById('vpSumStock');
    const costEl = document.getElementById('vpSumCost');
    const retailEl = document.getElementById('vpSumRetail');

    let totalStock = 0;
    let totalCost = 0;
    let totalRetail = 0;

    document.querySelectorAll('#variantsTableBody tr').forEach((row) => {
        const stock = parseFloat(row.querySelector('.variant-opening_stock')?.value) || 0;
        const purchase = parseFloat(row.querySelector('.variant-purchase_price')?.value) || 0;
        const price = parseFloat(row.querySelector('.variant-price')?.value) || 0;
        totalStock += stock;
        totalCost += stock * purchase;
        totalRetail += stock * price;
    });

    if (combosEl) combosEl.textContent = String(n);
    if (stockEl) stockEl.textContent = String(totalStock);
    if (costEl) costEl.textContent = money(totalCost);
    if (retailEl) retailEl.textContent = money(totalRetail);

    const cat = document.getElementById('vpSumCategory');
    const brand = document.getElementById('vpSumBrand');
    const tax = document.getElementById('vpSumTax');
    const activeChip = document.getElementById('vpSumActive');

    if (cat) cat.textContent = 'Category · ' + selectedText(document.getElementById('vpCategory'));
    if (brand) brand.textContent = 'Brand · ' + selectedText(document.getElementById('vpBrand'));
    if (tax) tax.textContent = 'Tax · ' + selectedText(document.getElementById('vpTax'));

    const isActive = document.getElementById('isActive')?.checked;
    if (activeChip) {
        activeChip.textContent = isActive ? 'Active' : 'Inactive';
        activeChip.classList.toggle('vp-chip--active', !!isActive);
        activeChip.classList.toggle('vp-chip--inactive', !isActive);
    }
}

function generateCombinations() {
    const selectedAttributes = {};

    document.querySelectorAll('.attribute-checkboxes input[type="checkbox"]:checked').forEach((checkbox) => {
        const attrId = checkbox.dataset.attributeId;
        const attrName = checkbox.dataset.attributeName;
        const valueId = checkbox.value;
        const valueName = checkbox.dataset.valueName;

        if (!selectedAttributes[attrId]) {
            selectedAttributes[attrId] = { name: attrName, values: [] };
        }

        selectedAttributes[attrId].values.push({ id: valueId, name: valueName });
    });

    const attributeIds = Object.keys(selectedAttributes);
    if (attributeIds.length === 0) return [];

    const attributeArrays = attributeIds.map((attrId) =>
        selectedAttributes[attrId].values.map((val) => ({
            attributeId: attrId,
            attributeName: selectedAttributes[attrId].name,
            valueId: val.id,
            valueName: val.name,
        }))
    );

    function cartesianProduct(arrays) {
        return arrays.reduce((acc, curr) => {
            const result = [];
            acc.forEach((accItem) => {
                curr.forEach((currItem) => {
                    result.push([...accItem, currItem]);
                });
            });
            return result;
        }, [[]]);
    }

    return cartesianProduct(attributeArrays).map((combo) => {
        const variantName = combo.map((item) => `${item.attributeName}: ${item.valueName}`).join(' · ');
        return {
            name: variantName,
            attributeValueIds: combo.map((item) => item.valueId),
            attributes: combo,
        };
    });
}

function updateVariantCombinations() {
    document.querySelectorAll('.attribute-checkboxes input[type="checkbox"]').forEach(syncChipSelectedState);
    updateAttributeSelectedCounts();

    variantCombinations = generateCombinations();
    const variantsSection = document.getElementById('variantsSection');
    const n = variantCombinations.length;

    updateSubmitLabels(n);

    if (n === 0) {
        if (variantsSection) variantsSection.style.display = 'none';
        setSubmitDisabled(true);
        document.getElementById('variantsTableBody').innerHTML = '';
        refreshSummary();
        return;
    }

    if (variantsSection) variantsSection.style.display = '';
    setSubmitDisabled(false);
    generateVariantsTable();
    refreshSummary();
}

function generateVariantsTable() {
    const tbody = document.getElementById('variantsTableBody');
    tbody.innerHTML = '';

    const nameVal = (document.querySelector('input[name="name"]')?.value || '').replace(/\s+/g, '').substring(0, 10).toUpperCase();
    const baseSku = nameVal || 'PROD';

    variantCombinations.forEach((combo, index) => {
        const row = document.createElement('tr');
        const sku = `${baseSku}-${index + 1}`;

        row.innerHTML = `
            <td>
                <div class="vp-variant-name">${combo.name}</div>
                ${combo.attributeValueIds.map((id) => `<input type="hidden" name="variants[${index}][attribute_value_ids][]" value="${id}">`).join('')}
            </td>
            <td>
                <input type="text" name="variants[${index}][sku]" class="form-control form-control-sm" value="${sku}" required>
            </td>
            <td>
                <input type="number" step="0.01" name="variants[${index}][purchase_price]" class="form-control form-control-sm variant-purchase_price" value="0" min="0">
            </td>
            <td>
                <input type="number" step="0.01" name="variants[${index}][price]" class="form-control form-control-sm variant-price" value="0" required min="0">
            </td>
            <td>
                <input type="number" step="0.01" name="variants[${index}][mrp]" class="form-control form-control-sm variant-mrp" value="0" min="0">
            </td>
            <td>
                <input type="number" step="0.01" name="variants[${index}][wholesale_price]" class="form-control form-control-sm variant-wholesale_price" value="0" min="0">
            </td>
            <td>
                <input type="number" name="variants[${index}][opening_stock]" class="form-control form-control-sm variant-opening_stock" value="0" required min="0">
            </td>
            <td><span class="vp-margin is-empty">—</span></td>
            <td>
                <label class="vp-image-box" title="Add variant image">
                    <input type="file" name="variants[${index}][image]" class="vp-image-box__input" accept="image/jpeg,image/png,image/jpg,image/webp">
                    <span class="vp-image-box__frame">
                        <img class="vp-image-box__preview" alt="" hidden>
                        <span class="vp-image-box__placeholder">
                            <i class="bi bi-image"></i>
                            <span>Add</span>
                        </span>
                    </span>
                </label>
            </td>
        `;

        tbody.appendChild(row);
        updateRowMargin(row);
        bindVariantImageBox(row);

        row.querySelectorAll('.variant-price, .variant-purchase_price, .variant-opening_stock').forEach((input) => {
            input.addEventListener('input', () => {
                updateRowMargin(row);
                refreshSummary();
            });
        });
    });
}

function bindVariantImageBox(row) {
    const input = row.querySelector('.vp-image-box__input');
    const preview = row.querySelector('.vp-image-box__preview');
    const placeholder = row.querySelector('.vp-image-box__placeholder');
    const box = row.querySelector('.vp-image-box');
    if (!input || !preview || !placeholder) return;

    input.addEventListener('change', function () {
        const file = this.files && this.files[0];
        if (!file) {
            preview.hidden = true;
            preview.removeAttribute('src');
            placeholder.hidden = false;
            box.classList.remove('has-image');
            return;
        }
        const url = URL.createObjectURL(file);
        preview.onload = () => URL.revokeObjectURL(url);
        preview.src = url;
        preview.hidden = false;
        placeholder.hidden = true;
        box.classList.add('has-image');
    });
}

function toCamelCase(str) {
    return str.split('_').map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join('');
}

function applyBulkValue(field) {
    const camelField = toCamelCase(field);
    const input = document.getElementById(`bulk${camelField}`);
    if (!input) return;

    const value = input.value;
    if (!value && value !== '0') return;

    document.querySelectorAll(`.variant-${field}`).forEach((inputEl) => {
        inputEl.value = value;
    });

    input.value = '';
}

function applyBulkAll() {
    ['price', 'mrp', 'purchase_price', 'wholesale_price', 'opening_stock'].forEach((field) => {
        const camelField = toCamelCase(field);
        const input = document.getElementById(`bulk${camelField}`);
        if (!input) return;
        const value = input.value;
        if (value === '' || value === null || value === undefined) return;

        document.querySelectorAll(`.variant-${field}`).forEach((inputEl) => {
            inputEl.value = value;
        });
        input.value = '';
    });

    document.querySelectorAll('#variantsTableBody tr').forEach(updateRowMargin);
    refreshSummary();
}

function generateNewBarcode() {
    document.getElementById('barcode').value = String(Math.floor(Math.random() * 90000000 + 10000000));
}

// Attribute search + clear
document.addEventListener('input', function (e) {
    if (!e.target.classList.contains('vp-attr-search')) return;
    const attrId = e.target.dataset.searchFor;
    const q = (e.target.value || '').trim().toLowerCase();
    const group = document.querySelector(`.vp-attr-group[data-attribute-id="${attrId}"]`);
    if (!group) return;
    group.querySelectorAll('.attribute-checkbox-item').forEach((chip) => {
        const text = chip.dataset.searchText || '';
        chip.classList.toggle('is-hidden', q !== '' && !text.includes(q));
    });
});

document.addEventListener('click', function (e) {
    const btn = e.target.closest('.vp-attr-clear');
    if (!btn) return;
    const attrId = btn.dataset.clearFor;
    const group = document.querySelector(`.vp-attr-group[data-attribute-id="${attrId}"]`);
    if (!group) return;
    group.querySelectorAll('input[type="checkbox"]').forEach((cb) => {
        cb.checked = false;
        syncChipSelectedState(cb);
    });
    const search = group.querySelector('.vp-attr-search');
    if (search) {
        search.value = '';
        group.querySelectorAll('.attribute-checkbox-item').forEach((chip) => chip.classList.remove('is-hidden'));
    }
    updateVariantCombinations();
});

// Tags (pp-tag style)
(function () {
    const tagInput = document.getElementById('productTagsTextarea');
    const tagsDisplay = document.getElementById('tagsDisplay');
    const tagsHidden = document.getElementById('productTagsHidden');
    let tags = [];

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function syncTagsHidden() {
        if (tagsHidden) tagsHidden.value = tags.join(', ');
    }

    function renderTags() {
        if (!tagsDisplay) return;
        tagsDisplay.innerHTML = '';
        tags.forEach((tag, index) => {
            const el = document.createElement('span');
            el.className = 'pp-tag';
            el.innerHTML = '<span>' + escapeHtml(tag) + '</span><button type="button" data-index="' + index + '" aria-label="Remove tag"><i class="bi bi-x"></i></button>';
            tagsDisplay.appendChild(el);
        });
        tagsDisplay.querySelectorAll('button').forEach((btn) => {
            btn.addEventListener('click', function () {
                tags.splice(parseInt(this.getAttribute('data-index'), 10), 1);
                renderTags();
            });
        });
        syncTagsHidden();
    }

    function addTag(raw) {
        const tag = (raw || '').trim();
        if (!tag || tags.includes(tag)) return false;
        tags.push(tag);
        renderTags();
        return true;
    }

    if (tagInput && tagsHidden) {
        const initial = (tagsHidden.value || '').split(',').map((t) => t.trim()).filter(Boolean);
        tags = [...new Set(initial)];
        renderTags();

        tagInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ',') {
                e.preventDefault();
                if (addTag(tagInput.value.replace(/,/g, ''))) tagInput.value = '';
            }
        });
        tagInput.addEventListener('blur', function () {
            if (addTag(tagInput.value.replace(/,/g, ''))) tagInput.value = '';
        });
        document.getElementById('variantProductForm')?.addEventListener('submit', syncTagsHidden);
    }
})();

document.addEventListener('DOMContentLoaded', function () {
    setSubmitDisabled(true);
    updateSubmitLabels(0);
    refreshSummary();

    ['vpCategory', 'vpBrand', 'vpTax', 'isActive'].forEach((id) => {
        const el = document.getElementById(id);
        if (!el) return;
        el.addEventListener('change', refreshSummary);
    });

    document.getElementById('vpName')?.addEventListener('input', refreshSummary);
});

document.getElementById('variantProductForm').addEventListener('submit', function (e) {
    if (variantCombinations.length === 0) {
        e.preventDefault();
        alert('Please select at least one attribute value to create variants.');
        return false;
    }

    let hasError = false;
    document.querySelectorAll('input[name*="[price]"]').forEach((input) => {
        if (!input.value || parseFloat(input.value) < 0) {
            hasError = true;
            input.classList.add('is-invalid');
        } else {
            input.classList.remove('is-invalid');
        }
    });

    document.querySelectorAll('input[name*="[opening_stock]"]').forEach((input) => {
        if (!input.value || parseInt(input.value, 10) < 0) {
            hasError = true;
            input.classList.add('is-invalid');
        } else {
            input.classList.remove('is-invalid');
        }
    });

    if (hasError) {
        e.preventDefault();
        alert('Please fill in all required fields (Price and Stock) for all variants.');
        return false;
    }
});
</script>
@endpush
