{{--
    Health Marketor Dashboard — Create Machine Listing
    Multi-step form with per-step validation, old() repopulation, and payment awareness.
    Authenticated page with <x-app-layout> + <x-module-hero>
    Requirements: 3.1, 8.2, 8.4
--}}
<x-app-layout>

    <x-module-hero
        title="New Machine Listing"
        description="Showcase your digital health equipment"
        icon="fa-cogs"
    >
        <x-slot name="backButton">
            <a href="{{ route('dashboard.machines.index') }}"
               class="inline-flex items-center gap-2 text-white/80 hover:text-white text-sm transition">
                <i class="fas fa-arrow-left"></i> Back to My Machines
            </a>
        </x-slot>
        <x-slot name="tabs">
            @can('view institutions')
                <a href="{{ route('dashboard.institutions.index') }}" class="module-hero-tab">
                    <i class="fas fa-hospital"></i> My Institutions
                </a>
            @endcan
            @can('view machines')
                <a href="{{ route('dashboard.machines.index') }}" class="module-hero-tab active-tab" aria-current="page">
                    <i class="fas fa-cogs"></i> My Machines
                </a>
            @endcan
            @can('view payments')
                <a href="{{ route('dashboard.payments.index') }}" class="module-hero-tab">
                    <i class="fas fa-credit-card"></i> Payment History
                </a>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-6">

        {{-- Global validation error banner --}}
        @if($errors->any())
            <div class="mb-6 bg-red-50 border-l-4 border-red-500 p-4 rounded-r-lg">
                <div class="flex items-start">
                    <i class="fas fa-exclamation-circle text-red-500 mt-0.5 mr-3 flex-shrink-0"></i>
                    <div>
                        <h4 class="font-semibold text-red-800 mb-1">Please fix the following errors:</h4>
                        <ul class="list-disc list-inside text-sm text-red-700 space-y-1">
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
        @endif

        {{-- Payment info alert --}}
        @if($paymentConfig && $paymentConfig->requiresPayment())
            <div class="mb-6 bg-blue-50 border-l-4 border-blue-500 p-4 rounded-r-lg">
                <div class="flex items-start">
                    <i class="fas fa-info-circle text-blue-500 mt-0.5 mr-3"></i>
                    <div>
                        <h4 class="font-semibold text-blue-800">Listing Fee Required</h4>
                        <p class="text-blue-700 text-sm">
                            After submission, a payment of
                            <strong>SSP {{ number_format($paymentConfig->amount_ssp) }}</strong>
                            @if($paymentConfig->amount_usd)
                                (or <strong>USD {{ number_format($paymentConfig->amount_usd, 2) }}</strong>)
                            @endif
                            is required before your listing goes for approval.
                        </p>
                    </div>
                </div>
            </div>
        @endif

        <form action="{{ route('dashboard.machines.store') }}" method="POST" enctype="multipart/form-data"
              id="machine-create-form"
              x-data="{
                  step: {{ ($errors->has('images') || $errors->has('images.*')) ? 3 : ($errors->has('price_ssp') || $errors->has('price_usd') || $errors->has('functionalities') || $errors->has('functionalities.*') ? 2 : 1) }},
                  totalSteps: 3,
                  functionalities: {{ json_encode(old('functionalities', [])) }},
                  newFunc: '',
                  addFunc() {
                      const v = this.newFunc.trim();
                      if (v && !this.functionalities.includes(v)) {
                          this.functionalities.push(v);
                          this.newFunc = '';
                      }
                  },
                  removeFunc(i) { this.functionalities.splice(i, 1); },
                  nextStep() {
                      if (!this.validateStep(this.step)) return;
                      if (this.step < this.totalSteps) { this.step++; window.scrollTo({ top: 0, behavior: 'smooth' }); }
                  },
                  prevStep() {
                      if (this.step > 1) { this.step--; window.scrollTo({ top: 0, behavior: 'smooth' }); }
                  },
                  validateStep(s) {
                      const stepEl = document.querySelector('[data-step=\'' + s + '\']');
                      if (!stepEl) return true;
                      let valid = true;
                      stepEl.querySelectorAll('[required]').forEach(input => {
                          if (input.type === 'file') {
                              if (!input.files || input.files.length === 0) { input.reportValidity(); valid = false; }
                          } else if (!input.value.trim()) {
                              input.reportValidity(); valid = false;
                          }
                      });
                      return valid;
                  }
              }">
            @csrf

            {{-- Progress Bar --}}
            <div class="mb-8">
                <div class="flex items-center justify-between mb-2">
                    <span class="text-sm font-medium text-gray-700">Step <span x-text="step"></span> of <span x-text="totalSteps"></span></span>
                    <span class="text-sm text-blue-600 font-medium" x-text="Math.round((step / totalSteps) * 100) + '% Complete'"></span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-3">
                    <div class="bg-gradient-to-r from-blue-600 to-blue-700 h-3 rounded-full transition-all duration-300"
                         :style="'width: ' + (step / totalSteps) * 100 + '%'"></div>
                </div>
                <div class="flex justify-between mt-2">
                    @foreach(['Machine Details', 'Pricing & Features', 'Images & Submit'] as $i => $label)
                        <span class="text-xs font-medium"
                              :class="{{ $i + 1 }} <= step ? 'text-blue-600' : 'text-gray-400'">
                            {{ $label }}
                        </span>
                    @endforeach
                </div>
            </div>

            {{-- ================================================================ --}}
            {{-- Step 1: Machine Details --}}
            {{-- ================================================================ --}}
            <div x-show="step === 1" x-transition
                 class="bg-white rounded-xl shadow-md p-6 lg:p-8"
                 data-step="1">
                <fieldset>
                    <legend class="text-xl font-bold text-gray-800 mb-6 pb-4 border-b">
                        <i class="fas fa-cogs text-blue-500 mr-2"></i>Machine Details
                    </legend>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {{-- Name --}}
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Machine Name <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="name" required
                                   value="{{ old('name') }}"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition"
                                   placeholder="e.g., Ultrasound Scanner Model X200">
                            @error('name')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        {{-- Category --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Category <span class="text-red-500">*</span>
                            </label>
                            <select name="category" required
                                    class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition">
                                <option value="">Select Category</option>
                                @foreach($categories as $key => $label)
                                    <option value="{{ $key }}" {{ old('category') == $key ? 'selected' : '' }}>{{ $label }}</option>
                                @endforeach
                            </select>
                            @error('category')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        {{-- Brand --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Brand <span class="text-gray-400">(Optional)</span>
                            </label>
                            <input type="text" name="brand"
                                   value="{{ old('brand') }}"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition"
                                   placeholder="e.g., Philips">
                        </div>

                        {{-- Model --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Model <span class="text-gray-400">(Optional)</span>
                            </label>
                            <input type="text" name="model"
                                   value="{{ old('model') }}"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition"
                                   placeholder="e.g., X200">
                        </div>

                        {{-- Vendor --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Vendor <span class="text-gray-400">(Optional)</span>
                            </label>
                            <input type="text" name="vendor"
                                   value="{{ old('vendor') }}"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition"
                                   placeholder="Local distributor name">
                        </div>

                        {{-- Manufacturer --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Manufacturer <span class="text-gray-400">(Optional)</span>
                            </label>
                            <input type="text" name="manufacturers"
                                   value="{{ old('manufacturers') }}"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition"
                                   placeholder="e.g., Philips Healthcare">
                        </div>

                        {{-- Description --}}
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Description <span class="text-red-500">*</span>
                            </label>
                            <textarea name="description" rows="5" required
                                      class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition"
                                      placeholder="Describe the machine, its purpose, condition, and key features...">{{ old('description') }}</textarea>
                            <p class="mt-1 text-xs text-gray-500">Minimum 50 characters</p>
                            @error('description')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>
                    </div>
                </fieldset>
            </div>

            {{-- ================================================================ --}}
            {{-- Step 2: Pricing & Features --}}
            {{-- ================================================================ --}}
            <div x-show="step === 2" x-transition
                 class="bg-white rounded-xl shadow-md p-6 lg:p-8"
                 data-step="2">
                <fieldset>
                    <legend class="text-xl font-bold text-gray-800 mb-6 pb-4 border-b">
                        <i class="fas fa-tag text-blue-500 mr-2"></i>Pricing & Features
                    </legend>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {{-- Price SSP --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Price (SSP) <span class="text-gray-400">(Optional)</span>
                            </label>
                            <input type="number" name="price_ssp"
                                   value="{{ old('price_ssp') }}"
                                   step="0.01" min="0"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition"
                                   placeholder="0.00">
                            @error('price_ssp')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        {{-- Price USD --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Price (USD) <span class="text-gray-400">(Optional)</span>
                            </label>
                            <input type="number" name="price_usd"
                                   value="{{ old('price_usd') }}"
                                   step="0.01" min="0"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition"
                                   placeholder="0.00">
                            @error('price_usd')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        {{-- Price Visibility --}}
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-3">Price Visibility</label>
                            <div class="flex items-center gap-6">
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="price_publishable" value="1"
                                           {{ old('price_publishable', '1') == '1' ? 'checked' : '' }}
                                           class="h-4 w-4 text-blue-600 focus:ring-blue-500">
                                    <span class="text-sm text-gray-700">Show price publicly</span>
                                </label>
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="price_publishable" value="0"
                                           {{ old('price_publishable') == '0' ? 'checked' : '' }}
                                           class="h-4 w-4 text-blue-600 focus:ring-blue-500">
                                    <span class="text-sm text-gray-700">Hide price (Contact for Price)</span>
                                </label>
                            </div>
                        </div>

                        {{-- Contact Phone --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Contact Phone <span class="text-gray-400">(Optional)</span>
                            </label>
                            <input type="tel" name="contact_phone"
                                   value="{{ old('contact_phone') }}"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition"
                                   placeholder="+211 9XX XXX XXX">
                        </div>

                        {{-- Contact Email --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Contact Email <span class="text-gray-400">(Optional)</span>
                            </label>
                            <input type="email" name="contact_email"
                                   value="{{ old('contact_email') }}"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition"
                                   placeholder="sales@example.com">
                        </div>

                        {{-- Key Functionalities --}}
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-3">
                                Key Functionalities <span class="text-gray-400">(Optional)</span>
                            </label>
                            <div class="flex gap-2 mb-3">
                                <input type="text" x-model="newFunc"
                                       @keydown.enter.prevent="addFunc()"
                                       placeholder="Type a functionality and press Add or Enter…"
                                       class="flex-1 px-4 py-3 border-2 border-gray-200 rounded-lg text-sm focus:border-blue-500 transition">
                                <button type="button" @click="addFunc()"
                                        class="px-5 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition text-sm font-medium whitespace-nowrap">
                                    <i class="fas fa-plus mr-1"></i>Add
                                </button>
                            </div>
                            <div class="flex flex-wrap gap-2 min-h-[2rem]">
                                <template x-for="(f, i) in functionalities" :key="i">
                                    <span class="inline-flex items-center px-3 py-1.5 bg-blue-100 text-blue-800 rounded-full text-sm">
                                        <span x-text="f"></span>
                                        <button type="button" @click="removeFunc(i)"
                                                class="ml-2 text-blue-500 hover:text-blue-800 transition">
                                            <i class="fas fa-times text-xs"></i>
                                        </button>
                                    </span>
                                </template>
                                <span x-show="functionalities.length === 0" class="text-sm text-gray-400 italic">No functionalities added yet</span>
                            </div>
                            {{-- Hidden inputs carry the array to the server --}}
                            <template x-for="(f, i) in functionalities" :key="'hidden-' + i">
                                <input type="hidden" name="functionalities[]" :value="f">
                            </template>
                            @error('functionalities.*')
                                <p class="mt-2 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>
                    </div>
                </fieldset>
            </div>

            {{-- ================================================================ --}}
            {{-- Step 3: Images & Submit --}}
            {{-- ================================================================ --}}
            <div x-show="step === 3" x-transition
                 class="bg-white rounded-xl shadow-md p-6 lg:p-8"
                 data-step="3"
                 x-data="Object.assign($data, {
                     previews: [],
                     handleImages(event) {
                         this.previews = [];
                         Array.from(event.target.files).forEach(file => {
                             if (file.type.startsWith('image/')) {
                                 const reader = new FileReader();
                                 reader.onload = e => this.previews.push(e.target.result);
                                 reader.readAsDataURL(file);
                             }
                         });
                     }
                 })">
                <fieldset>
                    <legend class="text-xl font-bold text-gray-800 mb-6 pb-4 border-b">
                        <i class="fas fa-images text-blue-500 mr-2"></i>Images & Submit
                    </legend>

                    <div class="space-y-6">
                        {{-- Image Upload --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Machine Images <span class="text-red-500">*</span>
                            </label>
                            <input type="file" name="images[]" multiple accept="image/*" required
                                   @change="handleImages($event)"
                                   class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg text-sm focus:border-blue-500 transition">
                            <p class="mt-1 text-xs text-gray-500">First image will be used as primary. Max 15 images, 5MB each. JPG, PNG, WEBP.</p>
                            @error('images')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                            @error('images.*')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror

                            {{-- Image Previews --}}
                            <div class="grid grid-cols-4 gap-3 mt-3">
                                <template x-for="(src, idx) in previews" :key="idx">
                                    <div class="relative aspect-square rounded-lg overflow-hidden border-2 border-gray-200">
                                        <img :src="src" class="w-full h-full object-cover">
                                        <span x-show="idx === 0"
                                              class="absolute bottom-1 left-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded">
                                            Primary
                                        </span>
                                    </div>
                                </template>
                            </div>
                        </div>

                        {{-- Payment Notice --}}
                        @if($paymentConfig && $paymentConfig->requiresPayment())
                            <div class="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                                <div class="flex items-start">
                                    <i class="fas fa-exclamation-triangle text-yellow-500 mt-0.5 mr-3"></i>
                                    <div>
                                        <h4 class="font-semibold text-yellow-800">Payment Required After Submission</h4>
                                        <p class="text-yellow-700 text-sm">
                                            You will be redirected to complete payment of
                                            <strong>SSP {{ number_format($paymentConfig->amount_ssp) }}</strong>
                                            before your listing is submitted for admin approval.
                                        </p>
                                    </div>
                                </div>
                            </div>
                        @endif
                    </div>
                </fieldset>
            </div>

            {{-- Navigation Buttons --}}
            <div class="mt-8 flex justify-between">
                <button type="button"
                        @click="prevStep()"
                        x-show="step > 1"
                        class="px-6 py-3 bg-gray-200 text-gray-700 font-semibold rounded-lg hover:bg-gray-300 transition">
                    <i class="fas fa-arrow-left mr-2"></i>Previous
                </button>

                <div class="ml-auto flex gap-3">
                    <button type="button"
                            @click="nextStep()"
                            x-show="step < totalSteps"
                            class="px-6 py-3 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition">
                        Next Step<i class="fas fa-arrow-right ml-2"></i>
                    </button>

                    <button type="submit"
                            x-show="step === totalSteps"
                            class="px-8 py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-semibold rounded-lg hover:from-blue-700 hover:to-blue-800 transition shadow-lg">
                        <i class="fas fa-paper-plane mr-2"></i>Submit Listing
                    </button>
                </div>
            </div>
        </form>

    </div>

</x-app-layout>
