{{--
    Shared create/edit fields for an asset.

    $asset            — the Asset being edited, or a fresh instance with defaults
    $editing          — true on the edit screen
    $categories       — active asset categories
    $locations        — active locations
    $teams            — active teams
    $manufacturerSuggestions, $vendorSuggestions — distinct values already on file

    Status has no field here at all, on either screen. On create it is
    restricted to AssetStatus::assignableOnCreate() and rendered as its own
    fieldset below; on edit it is never shown, because status moves only
    through the governed "Change Status" action on the detail page — see
    AssetService::changeStatus().
--}}
@php
    /** @var \App\Models\Asset $asset */
    // Empty string, not null, on the edit screen: an already-assigned tag
    // never needs a preview, and asset-tag-preview.js treats a blank
    // data-asset-tag-input as "nothing to fetch" rather than firing a
    // request against an empty URL.
    $tagPreviewUrl = $editing ? '' : route('assets.tag-preview');
    $specRows = $asset->specifications ?: [];

    // Always at least 3 rows so the fieldset never looks broken with nothing
    // to type into, whether creating fresh or editing an asset with no
    // specifications recorded yet.
    while (count($specRows) < 3) {
        $specRows[] = ['', ''];
    }

    $specRows = collect($specRows)->map(function ($value, $key) {
        return is_int($key) ? ['', ''] : [$key, $value];
    })->values()->all();
@endphp

<x-form.fieldset legend="Identity">
    <div class="row g-3">
        <div class="col-md-4">
            <x-form.input
                name="asset_tag"
                label="Asset Tag"
                :value="$asset->asset_tag"
                autocomplete="off"
                style="text-transform: uppercase"
                data-asset-tag-input="{{ $tagPreviewUrl }}"
                :help="$editing ? 'The primary identifier for this asset. Must stay unique.' : 'Auto-generated — edit if you need a specific tag instead.'" />
        </div>

        <div class="col-md-4">
            <x-form.input
                name="name"
                label="Asset Name"
                :value="$asset->name"
                placeholder="Dell Latitude 5440"
                autocomplete="off"
                required />
        </div>

        <div class="col-md-4">
            <x-form.input
                name="serial_number"
                label="Serial Number"
                :value="$asset->serial_number"
                autocomplete="off"
                help="Optional. Must be unique." />
        </div>

        <div class="col-md-4">
            <x-form.input
                name="mac_address"
                label="MAC Address"
                :value="$asset->mac_address"
                autocomplete="off"
                help="Optional. Must be unique." />
        </div>
    </div>
</x-form.fieldset>

@unless ($editing)
    <x-form.fieldset legend="Initial Status">
        <div class="row g-3">
            <div class="col-md-6">
                <x-form.select
                    name="status"
                    label="Status"
                    :selected="$asset->status?->value"
                    :options="collect(\App\Enums\AssetStatus::assignableOnCreate())->mapWithKeys(fn ($status) => [$status->value => $status->label()])->all()"
                    help="An asset starts in stock, or already under repair or damaged if that is the truth on arrival."
                    required />
            </div>

            <div class="col-md-6">
                <x-form.select
                    name="condition"
                    label="Condition"
                    :selected="$asset->condition?->value"
                    :options="\App\Enums\AssetCondition::options()"
                    required />
            </div>
        </div>
    </x-form.fieldset>
@else
    {{--
        Condition still belongs to the general edit form — unlike status, it
        carries no transition rules of its own, only a snapshot of physical
        state that can be corrected at any time.
    --}}
    <x-form.fieldset legend="Condition">
        <x-form.select
            name="condition"
            label="Condition"
            :selected="$asset->condition?->value"
            :options="\App\Enums\AssetCondition::options()"
            required />
    </x-form.fieldset>
@endunless

<x-form.fieldset legend="Classification">
    <div class="row g-3">
        <div class="col-md-4">
            <x-form.select
                name="category_id"
                label="Category"
                placeholder="Choose a category"
                :selected="$asset->category_id"
                :options="$categories->mapWithKeys(fn ($category) => [$category->id => $category->qualifiedName()])->all()"
                data-asset-tag-category
                required />
        </div>

        <div class="col-md-4">
            <x-form.select
                name="location_id"
                label="Location"
                placeholder="No location"
                :selected="$asset->location_id"
                :options="$locations->pluck('name', 'id')->all()" />
        </div>

        <div class="col-md-4">
            <x-form.select
                name="team_id"
                label="Team"
                placeholder="No team"
                :selected="$asset->team_id"
                :options="$teams->pluck('name', 'id')->all()"
                help="Which team owns this asset on the books." />
        </div>
    </div>
</x-form.fieldset>

<x-form.fieldset legend="Technical Information">
    <div class="row g-3">
        <div class="col-md-6">
            <x-form.datalist
                name="manufacturer"
                label="Manufacturer"
                :value="$asset->manufacturer"
                :options="$manufacturerSuggestions"
                placeholder="Dell"
                help="Start typing, or enter a new one." />
        </div>

        <div class="col-md-6">
            <x-form.input
                name="model"
                label="Model"
                :value="$asset->model"
                placeholder="Latitude 5440"
                autocomplete="off" />
        </div>
    </div>

    <div class="ams-fieldset__legend mt-3">Specifications</div>
    <p class="ams-fieldset__hint">
        Attributes specific to this kind of asset — RAM, CPU, storage, screen
        size, IMEI. Optional, and however many rows you need.
    </p>

    <div data-specs-container>
        @foreach ($specRows as $index => [$specKey, $specValue])
            <div class="row g-2 mb-2" data-specs-row>
                <div class="col-5">
                    <label class="visually-hidden" for="spec_key_{{ $index }}">Attribute</label>
                    <input type="text"
                           id="spec_key_{{ $index }}"
                           name="spec_key[]"
                           class="form-control form-control-sm"
                           placeholder="Attribute, e.g. RAM"
                           value="{{ $specKey }}">
                </div>
                <div class="col-6">
                    <label class="visually-hidden" for="spec_value_{{ $index }}">Value</label>
                    <input type="text"
                           id="spec_value_{{ $index }}"
                           name="spec_value[]"
                           class="form-control form-control-sm"
                           placeholder="Value, e.g. 16 GB"
                           value="{{ $specValue }}">
                </div>
                <div class="col-1 d-flex align-items-center">
                    <button type="button"
                            class="btn btn-sm btn-icon text-secondary"
                            data-specs-remove
                            title="Remove row">
                        <i class="bi bi-dash-circle" aria-hidden="true"></i>
                        <span class="visually-hidden">Remove row</span>
                    </button>
                </div>
            </div>
        @endforeach

        {{--
            Inside the container deliberately: addRow() always inserts a new
            row after the last [data-specs-row], so this stays the last
            element regardless of how many rows exist. More importantly,
            specifications.js finds the container via
            addButton.closest('[data-specs-container]') — .closest() only
            searches an element's ancestors, never its siblings, so this
            button has to be a descendant of the container to be found at all.
        --}}
        <button type="button" class="btn btn-sm btn-outline-secondary mt-1" data-specs-add>
            <i class="bi bi-plus-lg" aria-hidden="true"></i>Add row
        </button>
    </div>
</x-form.fieldset>

<x-form.fieldset legend="Purchase Information">
    <div class="row g-3">
        <div class="col-md-6">
            <x-form.datalist
                name="vendor"
                label="Vendor"
                :value="$asset->vendor"
                :options="$vendorSuggestions"
                placeholder="Where it was purchased from"
                help="Start typing, or enter a new one." />
        </div>

        <div class="col-md-3">
            <x-form.date
                name="purchase_date"
                label="Purchase Date"
                :value="$asset->purchase_date" />
        </div>

        <div class="col-md-3">
            <x-form.input
                name="purchase_cost"
                label="Purchase Cost"
                type="number"
                step="0.01"
                min="0"
                :value="$asset->purchase_cost"
                autocomplete="off" />
        </div>

        <div class="col-md-3">
            <x-form.input
                name="currency"
                label="Currency"
                :value="$asset->currency"
                maxlength="3"
                placeholder="INR"
                autocomplete="off"
                help="ISO code, e.g. INR or USD." />
        </div>

        <div class="col-md-4">
            <x-form.input
                name="invoice_number"
                label="Invoice Number"
                :value="$asset->invoice_number"
                autocomplete="off" />
        </div>

        <div class="col-md-4">
            <x-form.input
                name="po_number"
                label="PO Number"
                :value="$asset->po_number"
                autocomplete="off" />
        </div>
    </div>
</x-form.fieldset>

@unless ($editing)
    <x-form.fieldset legend="Warranty">
        <p class="ams-fieldset__hint">
            Optional. Fill in both dates to record this asset's initial
            Manufacturer Warranty at the same time — no separate trip to the
            Warranty screen needed. Leave both blank to add coverage later.
        </p>

        <div class="row g-3">
            <div class="col-md-6">
                <x-form.date
                    name="warranty_start_date"
                    label="Warranty Start Date" />
            </div>

            <div class="col-md-6">
                <x-form.date
                    name="warranty_end_date"
                    label="Warranty End Date" />
            </div>
        </div>
    </x-form.fieldset>

    <x-form.fieldset legend="Invoice / Purchase Document" hint="Optional. Attach the invoice, PO or any other document for this asset now — more can be added later from the asset's Documents section.">
        <div class="row g-3">
            <div class="col-md-4">
                <x-form.select
                    name="document_type"
                    label="Document Type"
                    :selected="'invoice'"
                    :options="\App\Enums\AssetDocumentType::options()" />
            </div>

            <div class="col-md-8">
                <x-form.file
                    name="document"
                    label="Document"
                    accept=".pdf,.jpg,.jpeg,.png"
                    help="PDF, JPG or PNG, up to 10 MB." />
            </div>
        </div>
    </x-form.fieldset>
@endunless

<x-form.fieldset legend="Notes">
    <x-form.textarea
        name="notes"
        label="Notes"
        :value="$asset->notes"
        :rows="3"
        help="Visible to every user who can view this record." />
</x-form.fieldset>

<x-form.fieldset legend="Availability">
    <x-form.checkbox
        name="is_active"
        label="Asset is active"
        :checked="$asset->is_active"
        help="Inactive assets keep their history but are not offered when assigning to an employee." />
</x-form.fieldset>
