@extends('layouts.app')

@section('title', 'Buat Tiket Servis')

@push('head')
{{-- signature_pad dari CDN jsDelivr --}}
<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>
<style>
    /* Prevent double-tap zoom on mobile buttons */
    button, label { touch-action: manipulation; }

    /* Signature canvas border style */
    #sig-canvas {
        cursor: crosshair;
        touch-action: none;
    }

    /* ── Terms & Conditions Modal ──────────────────────── */
    #terms-modal    { display: none; }
    #terms-backdrop {
        position: absolute; inset: 0;
        background: rgba(0,0,0,0.5);
        backdrop-filter: blur(4px);
        -webkit-backdrop-filter: blur(4px);
        opacity: 0;
        transition: opacity 0.25s ease;
    }
    #terms-card {
        opacity: 0;
        transform: translateY(52px);
        transition: opacity 0.3s ease, transform 0.32s cubic-bezier(0.34,1.2,0.64,1);
    }
    #terms-scroll-hint {
        opacity: 1;
        transition: opacity 0.3s ease;
        pointer-events: none;
    }
    /* Checkbox custom accent color */
    #agree_terms { accent-color: #2563eb; }
</style>
@endpush

@section('content')
<div id="mode-header" class="mb-5">
    <h1 id="mode-title" class="text-xl font-bold text-gray-800">Buat Tiket Servis Baru</h1>
    <p id="mode-subtitle" class="text-sm text-gray-500 mt-0.5">Pilih jenis penerimaan perangkat.</p>
</div>

{{-- Mode Toggle --}}
<div class="grid grid-cols-2 gap-3 mb-5" id="mode-toggle">
    <button type="button" id="btn-walkin"
            onclick="setIntakeMode('walkin')"
            class="mode-btn flex flex-col items-center gap-2 rounded-2xl border-2 border-brand-600 bg-brand-50
                   p-4 text-brand-700 font-semibold text-sm transition">
        <svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                  d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
        </svg>
        Customer Walk-in
        <span class="text-xs font-normal text-brand-600">Bawa sendiri ke toko</span>
    </button>
    <button type="button" id="btn-courier"
            onclick="setIntakeMode('courier')"
            class="mode-btn flex flex-col items-center gap-2 rounded-2xl border-2 border-gray-200 bg-white
                   p-4 text-gray-600 font-semibold text-sm transition">
        <svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                  d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"/>
        </svg>
        Dijemput Kurir
        <span class="text-xs font-normal text-gray-500">Kurir datang ke tempat</span>
    </button>
</div>

<form method="POST" action="{{ route('tickets.store') }}"
      enctype="multipart/form-data" id="ticket-form" novalidate>
    @csrf
    <input type="hidden" name="intake_type" id="intake_type_input" value="{{ old('intake_type', 'walkin') }}">

    {{-- ══════════════════════════════════════
         SECTION 1 – Data Pelanggan
    ══════════════════════════════════════ --}}
    <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 mb-5">
        <h2 class="text-base font-semibold text-gray-700 mb-4 flex items-center gap-2">
            <span class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-brand-600 text-white text-xs font-bold">1</span>
            Data Pelanggan
        </h2>

        <div class="space-y-4">
            {{-- Nama --}}
            <div>
                <label for="customer_name" class="block text-sm font-medium text-gray-700 mb-1">
                    Nama Lengkap <span class="text-red-500">*</span>
                </label>
                <input type="text" id="customer_name" name="customer_name"
                       value="{{ old('customer_name') }}"
                       placeholder="Contoh: Budi Santoso"
                       autocomplete="name"
                       class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm
                              focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent
                              @error('customer_name') border-red-400 bg-red-50 @enderror">
                @error('customer_name')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            {{-- WhatsApp --}}
            <div>
                <label for="customer_whatsapp" class="block text-sm font-medium text-gray-700 mb-1">
                    Nomor WhatsApp
                </label>
                <div class="flex rounded-xl border border-gray-300 overflow-hidden
                            @error('customer_whatsapp') border-red-400 @enderror">
                    <span class="px-3 py-2.5 bg-gray-50 text-gray-500 text-sm border-r border-gray-300">+62</span>
                    <input type="tel" id="customer_whatsapp" name="customer_whatsapp"
                           value="{{ old('customer_whatsapp') }}"
                           placeholder="81234567890"
                           autocomplete="tel"
                           class="flex-1 px-3 py-2.5 text-sm focus:outline-none focus:ring-2
                                  focus:ring-brand-500 rounded-r-xl">
                </div>
                @error('customer_whatsapp')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            {{-- Email --}}
            <div>
                <label for="customer_email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input type="email" id="customer_email" name="customer_email"
                       value="{{ old('customer_email') }}"
                       placeholder="budi@email.com"
                       autocomplete="email"
                       class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm
                              focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent
                              @error('customer_email') border-red-400 bg-red-50 @enderror">
                @error('customer_email')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            {{-- Alamat --}}
            <div>
                <label for="customer_address" class="block text-sm font-medium text-gray-700 mb-1">
                    Alamat
                    <span id="address-required-star" class="text-red-500 hidden">*</span>
                </label>
                <textarea id="customer_address" name="customer_address" rows="2"
                          placeholder="Jl. Merdeka No. 1, Jakarta"
                          class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm resize-none
                                 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent
                                 @error('customer_address') border-red-400 bg-red-50 @enderror">{{ old('customer_address') }}</textarea>
                @error('customer_address')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            {{-- Catatan Pickup (untuk mode kurir) --}}
            <div id="pickup-note-field" class="hidden">
                <label for="pickup_note" class="block text-sm font-medium text-gray-700 mb-1">
                    Catatan Singkat
                    <span class="ml-1 text-xs text-gray-400 font-normal">(jenis perangkat, keluhan awal, dll.)</span>
                </label>
                <textarea id="pickup_note" name="pickup_note" rows="2"
                          placeholder="Contoh: Laptop ASUS, tidak bisa menyala. Ada di lantai 2."
                          class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm resize-none
                                 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent
                                 @error('pickup_note') border-red-400 bg-red-50 @enderror">{{ old('pickup_note') }}</textarea>
                @error('pickup_note')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>
        </div>
    </div>

    {{-- ══════════════════════════════════════
         SECTION 2 – Detail Perangkat
    ══════════════════════════════════════ --}}
    <div id="section-walkin" class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 mb-5">
        <h2 class="text-base font-semibold text-gray-700 mb-4 flex items-center gap-2">
            <span class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-brand-600 text-white text-xs font-bold">2</span>
            Detail Perangkat
        </h2>

        <div class="space-y-4">
            {{-- Jenis Perangkat --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    Jenis Perangkat <span class="text-red-500">*</span>
                </label>
                <div class="grid grid-cols-3 gap-2">
                    @foreach($deviceTypes as $type)
                    <label class="device-type-card relative flex flex-col items-center gap-1.5 cursor-pointer
                                  rounded-xl border-2 border-gray-200 p-3 text-center transition
                                  hover:border-brand-500 has-[:checked]:border-brand-600
                                  has-[:checked]:bg-brand-50">
                        <input type="radio" name="device_type" value="{{ $type }}"
                               class="sr-only"
                               {{ old('device_type') === $type ? 'checked' : '' }}>
                        @if($type === 'Laptop')
                            <svg class="w-7 h-7 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                                      d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                            </svg>
                        @elseif($type === 'PC')
                            <svg class="w-7 h-7 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                                      d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                                <rect x="7" y="2" width="10" height="10" rx="1" stroke-width="1.8"/>
                            </svg>
                        @else
                            <svg class="w-7 h-7 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                                      d="M17 17H7a2 2 0 01-2-2V5a2 2 0 012-2h10a2 2 0 012 2v10a2 2 0 01-2 2zM12 17v4m-4 0h8"/>
                            </svg>
                        @endif
                        <span class="text-xs font-medium text-gray-700">{{ $type }}</span>
                    </label>
                    @endforeach
                </div>
                @error('device_type')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            {{-- Merek --}}
            <div>
                <label for="brand" class="block text-sm font-medium text-gray-700 mb-1">
                    Merek <span class="text-red-500">*</span>
                </label>
                <input type="text" id="brand" name="brand"
                       value="{{ old('brand') }}"
                       placeholder="Contoh: ASUS, HP, Canon"
                       class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm
                              focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent
                              @error('brand') border-red-400 bg-red-50 @enderror">
                @error('brand')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            {{-- Tipe/Model --}}
            <div>
                <label for="model" class="block text-sm font-medium text-gray-700 mb-1">
                    Tipe / Model <span class="text-red-500">*</span>
                </label>
                <input type="text" id="model" name="model"
                       value="{{ old('model') }}"
                       placeholder="Contoh: VivoBook 14, LaserJet Pro"
                       class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm
                              focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent
                              @error('model') border-red-400 bg-red-50 @enderror">
                @error('model')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            {{-- Serial Number --}}
            <div>
                <label for="serial_number" class="block text-sm font-medium text-gray-700 mb-1">
                    Serial Number / S/N
                </label>
                <input type="text" id="serial_number" name="serial_number"
                       value="{{ old('serial_number') }}"
                       placeholder="Opsional"
                       class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm font-mono
                              focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
            </div>

            {{-- Keluhan --}}
            <div>
                <label for="problem_desc" class="block text-sm font-medium text-gray-700 mb-1">
                    Keluhan / Deskripsi Masalah <span class="text-red-500">*</span>
                </label>
                <textarea id="problem_desc" name="problem_desc" rows="3"
                          placeholder="Ceritakan kerusakan atau keluhan perangkat secara detail…"
                          class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm resize-none
                                 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent
                                 @error('problem_desc') border-red-400 bg-red-50 @enderror">{{ old('problem_desc') }}</textarea>
                @error('problem_desc')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            {{-- Kondisi Fisik --}}
            <div>
                <label for="physical_condition" class="block text-sm font-medium text-gray-700 mb-1">
                    Kondisi Fisik Perangkat
                    <span class="ml-1 text-xs text-gray-400 font-normal">(opsional — catat goresan/penyok yang sudah ada sebelum servis)</span>
                </label>
                <textarea id="physical_condition" name="physical_condition" rows="2"
                          placeholder="Contoh: Goresan di cover atas, engsel kiri longgar, layar retak sudut kanan…"
                          class="w-full rounded-xl border border-gray-300 px-4 py-2.5 text-sm resize-none
                                 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">{{ old('physical_condition') }}</textarea>
            </div>

            {{-- Password / PIN --}}
            <div>
                <label for="device_password" class="block text-sm font-medium text-gray-700 mb-1">
                    Password / PIN Perangkat
                    <span class="ml-1 text-xs text-gray-400 font-normal">(opsional)</span>
                </label>
                <div class="relative">
                    <input type="password" id="device_password" name="device_password"
                           value="{{ old('device_password') }}"
                           placeholder="Jika diperlukan untuk proses servis"
                           autocomplete="off"
                           class="w-full rounded-xl border border-gray-300 px-4 py-2.5 pr-11 text-sm
                                  focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                    <button type="button" id="btn-toggle-pass"
                            class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600">
                        <svg id="eye-icon" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                                  d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                                  d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7
                                     -1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                        </svg>
                    </button>
                </div>
                <p class="mt-1 text-xs text-amber-600 flex items-center gap-1">
                    <svg class="w-3.5 h-3.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                    </svg>
                    Password hanya digunakan untuk keperluan servis dan tidak disimpan secara permanen.
                </p>
            </div>
        </div>
    </div>

    {{-- ══════════════════════════════════════
         SECTION 3 – Kelengkapan / Aksesori
    ══════════════════════════════════════ --}}
    <div id="section-walkin-2" class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 mb-5">
        <h2 class="text-base font-semibold text-gray-700 mb-1 flex items-center gap-2">
            <span class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-brand-600 text-white text-xs font-bold">3</span>
            Kelengkapan yang Diserahkan
        </h2>
        <p class="text-xs text-gray-400 mb-4 pl-8">Centang aksesori yang ikut diserahkan bersama perangkat. Hanya yang dicentang yang tercatat dalam tanda terima.</p>

        @php
        $accOptions = [
            ['id' => 'acc_charger',  'label' => 'Charger / Adaptor',  'icon' => '🔌'],
            ['id' => 'acc_cable',    'label' => 'Kabel Power',         'icon' => '🔋'],
            ['id' => 'acc_bag',      'label' => 'Tas / Softcase',      'icon' => '👜'],
            ['id' => 'acc_mouse',    'label' => 'Mouse',               'icon' => '🖱️'],
            ['id' => 'acc_keyboard', 'label' => 'Keyboard',            'icon' => '⌨️'],
            ['id' => 'acc_battery',  'label' => 'Baterai Eksternal',   'icon' => '🔋'],
            ['id' => 'acc_stylus',   'label' => 'Stylus / Pen',        'icon' => '✏️'],
            ['id' => 'acc_memory',   'label' => 'Memori / Flashdisk',  'icon' => '💾'],
            ['id' => 'acc_cd',       'label' => 'CD / DVD',            'icon' => '💿'],
        ];
        @endphp

        <div class="grid grid-cols-2 gap-2 mb-3">
            @foreach($accOptions as $acc)
            <label class="flex items-center gap-2.5 rounded-xl border border-gray-200 px-3 py-2.5
                          cursor-pointer transition hover:border-brand-400 hover:bg-brand-50
                          has-[:checked]:border-brand-500 has-[:checked]:bg-brand-50">
                <input type="checkbox" name="accessories[]" value="{{ $acc['label'] }}"
                       class="w-4 h-4 rounded accent-blue-600 flex-shrink-0"
                       {{ is_array(old('accessories')) && in_array($acc['label'], old('accessories')) ? 'checked' : '' }}>
                <span class="text-sm text-gray-700 leading-tight">{{ $acc['icon'] }} {{ $acc['label'] }}</span>
            </label>
            @endforeach
        </div>

        {{-- Lain-lain --}}
        <label class="flex items-start gap-2.5 rounded-xl border border-gray-200 px-3 py-2.5
                      cursor-pointer transition hover:border-brand-400 hover:bg-brand-50
                      has-[:checked]:border-brand-500 has-[:checked]:bg-brand-50">
            <input type="checkbox" id="acc_other_chk"
                   class="w-4 h-4 rounded accent-blue-600 flex-shrink-0 mt-0.5"
                   {{ old('accessories_other') ? 'checked' : '' }}>
            <div class="flex-1">
                <span class="text-sm text-gray-700">✏️ Lain-lain</span>
                <input type="text" id="acc_other_text" name="accessories_other"
                       value="{{ old('accessories_other') }}"
                       placeholder="Sebutkan aksesori lainnya…"
                       class="mt-1.5 w-full rounded-lg border border-gray-300 px-3 py-1.5 text-sm
                              focus:outline-none focus:ring-2 focus:ring-brand-500
                              {{ old('accessories_other') ? '' : 'hidden' }}"
                       onclick="event.stopPropagation()">
            </div>
        </label>
    </div>

    {{-- ══════════════════════════════════════
         SECTION 4 – Foto Barang
    ══════════════════════════════════════ --}}
    <div id="section-walkin-3" class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 mb-5">
        <h2 class="text-base font-semibold text-gray-700 mb-1 flex items-center gap-2">
            <span class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-brand-600 text-white text-xs font-bold">4</span>
            Foto Barang Masuk
        </h2>
        <p class="text-xs text-gray-400 mb-4 pl-8">Ambil langsung dari kamera atau pilih dari galeri. Maks. 5 MB.</p>

        {{-- Dropzone / Preview --}}
        <label id="photo-label" for="photo_entry"
               class="flex flex-col items-center justify-center gap-2
                      border-2 border-dashed border-gray-300 rounded-xl
                      p-6 cursor-pointer transition hover:border-brand-500 hover:bg-brand-50">
            <svg id="camera-icon" class="w-10 h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                      d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                      d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"/>
            </svg>
            <img id="photo-preview" src="#" alt="Preview" class="hidden max-h-48 rounded-lg object-contain">
            <span id="photo-label-text" class="text-sm text-gray-500">
                Ketuk untuk ambil foto atau pilih dari galeri
            </span>
            <input type="file" id="photo_entry" name="photo_entry"
                   accept="image/*" capture="camera"
                   class="sr-only">
        </label>
        <button type="button" id="btn-remove-photo"
                class="hidden mt-2 w-full text-xs text-red-500 hover:text-red-700 py-1">
            ✕ Hapus foto
        </button>
        @error('photo_entry')
            <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
        @enderror
    </div>

    {{-- ══════════════════════════════════════
         SECTION 5 – Tanda Tangan Pelanggan
    ══════════════════════════════════════ --}}
    <div id="section-walkin-4" class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 mb-6">
        <h2 class="text-base font-semibold text-gray-700 mb-1 flex items-center gap-2">
            <span class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-brand-600 text-white text-xs font-bold">5</span>
            Tanda Tangan Pelanggan
        </h2>
        <p class="text-xs text-gray-400 mb-3 pl-8">Minta pelanggan tanda tangan di kotak di bawah ini.</p>

        <div class="border-2 border-gray-200 rounded-xl overflow-hidden bg-gray-50 relative">
            <canvas id="sig-canvas" class="w-full block" height="180"></canvas>
            <span id="sig-hint"
                  class="absolute inset-0 flex items-center justify-center
                         text-gray-300 text-sm pointer-events-none select-none">
                Tanda tangan di sini
            </span>
        </div>

        <div class="flex gap-2 mt-2">
            <button type="button" id="btn-clear-sig"
                    class="flex-1 text-sm text-gray-600 border border-gray-300 rounded-xl py-2 hover:bg-gray-50">
                Ulangi
            </button>
            <button type="button" id="btn-undo-sig"
                    class="flex-1 text-sm text-gray-600 border border-gray-300 rounded-xl py-2 hover:bg-gray-50">
                Undo
            </button>
        </div>

        {{-- Hidden input untuk kirim base64 --}}
        <input type="hidden" name="sig_entry" id="sig_entry_input">
    </div>

    {{-- ══════════════════════════════════════
         Syarat & Ketentuan
    ══════════════════════════════════════ --}}
    <div id="section-walkin-5" class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 mb-5">
        <div class="flex items-start gap-3">
            <input type="checkbox" id="agree_terms" name="agree_terms"
                   class="mt-0.5 h-5 w-5 rounded border-gray-300 cursor-pointer flex-shrink-0">
            <label for="agree_terms" class="text-sm text-gray-600 leading-relaxed cursor-pointer select-none">
                Saya telah membaca dan menyetujui
                <button type="button" id="btn-open-terms"
                        class="text-brand-600 font-semibold underline underline-offset-2
                               hover:text-brand-700 focus:outline-none focus-visible:ring-2
                               focus-visible:ring-brand-500 rounded transition-colors">
                    Syarat &amp; Ketentuan Servis
                </button>
            </label>
        </div>
        <p id="terms-error"
           class="hidden mt-2 ml-8 text-xs text-red-500 flex items-center gap-1">
            <svg class="w-3.5 h-3.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
            </svg>
            Harap baca dan setujui syarat &amp; ketentuan servis terlebih dahulu.
        </p>
    </div>

    {{-- Submit Button --}}
    <button type="submit" id="btn-submit"
            class="w-full bg-brand-600 hover:bg-brand-700 active:bg-brand-700
                   text-white font-semibold text-base rounded-2xl py-4
                   transition shadow-md shadow-brand-100
                   flex items-center justify-center gap-2">
        <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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
        </svg>
        <span id="btn-submit-label">Simpan Tiket</span>
    </button>
</form>

{{-- ══════════════════════════════════════
     Modal Syarat & Ketentuan
══════════════════════════════════════ --}}
<div id="terms-modal"
     class="fixed inset-0 z-50 flex items-end sm:items-center justify-center"
     role="dialog" aria-modal="true" aria-labelledby="terms-title">

    <div id="terms-backdrop"></div>

    <div id="terms-card"
         class="relative bg-white rounded-t-3xl sm:rounded-2xl w-full sm:max-w-lg
                mx-0 sm:mx-4 max-h-[88vh] flex flex-col shadow-2xl">

        {{-- Header --}}
        <div class="flex items-center justify-between px-5 pt-5 pb-4 border-b border-gray-100 flex-shrink-0">
            <div class="flex items-center gap-2.5">
                <div class="w-9 h-9 rounded-full bg-brand-50 flex items-center justify-center flex-shrink-0">
                    <svg class="w-5 h-5 text-brand-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                              d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                    </svg>
                </div>
                <div>
                    <h3 id="terms-title" class="font-semibold text-gray-800 text-base leading-tight">
                        Syarat &amp; Ketentuan Servis
                    </h3>
                    <p class="text-xs text-gray-400 mt-0.5">{{ \App\Models\Setting::get('company_name') }}</p>
                </div>
            </div>
            <button type="button" id="btn-close-terms"
                    class="w-9 h-9 flex items-center justify-center rounded-full
                           text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition flex-shrink-0">
                <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>

        {{-- Scrollable body --}}
        <div id="terms-body"
             class="flex-1 overflow-y-auto px-5 py-5 text-sm text-gray-700 leading-relaxed">
            @php $termsText = \App\Models\Setting::get('form_ticket_terms'); @endphp
            @if(trim($termsText))
                <div class="whitespace-pre-line">{{ $termsText }}</div>
            @else
                <p class="text-gray-400 italic text-center py-6">
                    Syarat dan ketentuan belum diatur.<br>Silakan hubungi kami untuk informasi lebih lanjut.
                </p>
            @endif
        </div>

        {{-- Scroll hint gradient --}}
        <div id="terms-scroll-hint"
             class="absolute left-0 right-0 h-12 bg-gradient-to-t from-white to-transparent"
             style="bottom: 73px;"></div>

        {{-- Footer --}}
        <div class="flex-shrink-0 px-5 py-4 border-t border-gray-100">
            <button type="button" id="btn-agree-terms"
                    class="w-full bg-brand-600 hover:bg-brand-700 active:bg-brand-700
                           text-white font-semibold text-sm rounded-xl py-3.5
                           transition shadow shadow-brand-100
                           flex items-center justify-center gap-2">
                <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.5" d="M5 13l4 4L19 7"/>
                </svg>
                Saya Telah Membaca &amp; Menyetujui
            </button>
            <button type="button" id="btn-close-terms-2"
                    class="w-full mt-2 text-sm text-gray-500 hover:text-gray-700 py-2 transition">
                Tutup
            </button>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
// ──────────────────────────────────────────────
//  0. INTAKE MODE TOGGLE
// ──────────────────────────────────────────────
(function () {
    const walkinSections = ['section-walkin','section-walkin-2','section-walkin-3','section-walkin-4','section-walkin-5'];

    function setIntakeMode(mode) {
        document.getElementById('intake_type_input').value = mode;

        const isWalkin = mode === 'walkin';

        // Toggle section visibility
        walkinSections.forEach(id => {
            const el = document.getElementById(id);
            if (el) el.style.display = isWalkin ? '' : 'none';
        });

        // Toggle pickup_note field
        const noteField = document.getElementById('pickup-note-field');
        if (noteField) noteField.classList.toggle('hidden', isWalkin);

        // Toggle address required star
        const star = document.getElementById('address-required-star');
        if (star) star.classList.toggle('hidden', isWalkin);

        // Toggle WA required indication
        const waLabel = document.querySelector('label[for="customer_whatsapp"]');
        if (waLabel) {
            const star2 = waLabel.querySelector('.courier-required');
            if (!star2 && !isWalkin) {
                const s = document.createElement('span');
                s.className = 'text-red-500 courier-required';
                s.textContent = ' *';
                waLabel.appendChild(s);
            } else if (star2 && isWalkin) {
                star2.remove();
            }
        }

        // Button styles
        const btnWalkin  = document.getElementById('btn-walkin');
        const btnCourier = document.getElementById('btn-courier');

        if (isWalkin) {
            btnWalkin.className  = 'mode-btn flex flex-col items-center gap-2 rounded-2xl border-2 border-brand-600 bg-brand-50 p-4 text-brand-700 font-semibold text-sm transition';
            btnCourier.className = 'mode-btn flex flex-col items-center gap-2 rounded-2xl border-2 border-gray-200 bg-white p-4 text-gray-600 font-semibold text-sm transition';
        } else {
            btnCourier.className = 'mode-btn flex flex-col items-center gap-2 rounded-2xl border-2 border-purple-600 bg-purple-50 p-4 text-purple-700 font-semibold text-sm transition';
            btnWalkin.className  = 'mode-btn flex flex-col items-center gap-2 rounded-2xl border-2 border-gray-200 bg-white p-4 text-gray-600 font-semibold text-sm transition';
        }

        // Heading
        document.getElementById('mode-title').textContent    = isWalkin ? 'Buat Tiket Servis Baru' : 'Ajukan Pickup Kurir';
        document.getElementById('mode-subtitle').textContent = isWalkin ? 'Isi data pelanggan & perangkat, lalu ambil foto dan tanda tangan.' : 'Isi data pelanggan. Kurir akan menjemput dan melengkapi data perangkat.';
        document.getElementById('btn-submit-label').textContent = isWalkin ? 'Simpan Tiket' : 'Ajukan Pickup';
    }

    // Expose globally
    window.setIntakeMode = setIntakeMode;

    // Initialize from old() value
    const initMode = document.getElementById('intake_type_input').value || 'walkin';
    setIntakeMode(initMode);
})();
// ──────────────────────────────────────────────
(function () {
    const input     = document.getElementById('photo_entry');
    const preview   = document.getElementById('photo-preview');
    const icon      = document.getElementById('camera-icon');
    const labelText = document.getElementById('photo-label-text');
    const btnRemove = document.getElementById('btn-remove-photo');

    input.addEventListener('change', function () {
        const file = this.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (e) => {
            preview.src = e.target.result;
            preview.classList.remove('hidden');
            icon.classList.add('hidden');
            labelText.textContent = file.name;
            btnRemove.classList.remove('hidden');
        };
        reader.readAsDataURL(file);
    });

    btnRemove.addEventListener('click', function () {
        input.value = '';
        preview.src = '#';
        preview.classList.add('hidden');
        icon.classList.remove('hidden');
        labelText.textContent = 'Ketuk untuk ambil foto atau pilih dari galeri';
        btnRemove.classList.add('hidden');
    });
})();

// ──────────────────────────────────────────────
//  2. SIGNATURE PAD
// ──────────────────────────────────────────────
(function () {
    const canvas  = document.getElementById('sig-canvas');
    const hint    = document.getElementById('sig-hint');
    const hidden  = document.getElementById('sig_entry_input');
    const btnClear = document.getElementById('btn-clear-sig');
    const btnUndo  = document.getElementById('btn-undo-sig');

    // Sesuaikan resolusi canvas dengan ukuran tampil (untuk retina)
    function resizeCanvas() {
        const ratio  = Math.max(window.devicePixelRatio || 1, 1);
        const width  = canvas.offsetWidth;
        canvas.width  = width  * ratio;
        canvas.height = 180   * ratio;
        canvas.getContext('2d').scale(ratio, ratio);
        signaturePad.clear();
    }

    const signaturePad = new SignaturePad(canvas, {
        backgroundColor: 'rgba(255,255,255,0)',
        penColor: '#1e3a5f',
        minWidth: 1.5,
        maxWidth: 3,
    });

    // Tampilkan/sembunyikan hint
    signaturePad.addEventListener('beginStroke', () => {
        hint.classList.add('hidden');
    });

    signaturePad.addEventListener('endStroke', () => {
        if (signaturePad.isEmpty()) hint.classList.remove('hidden');
    });

    btnClear.addEventListener('click', () => {
        signaturePad.clear();
        hidden.value = '';
        hint.classList.remove('hidden');
    });

    btnUndo.addEventListener('click', () => {
        const data = signaturePad.toData();
        if (data.length > 0) {
            data.pop();
            signaturePad.fromData(data);
        }
        if (signaturePad.isEmpty()) hint.classList.remove('hidden');
    });

    // Resize saat pertama kali & saat orientasi berubah
    window.addEventListener('resize', resizeCanvas);
    resizeCanvas();

    // ──────────────────────────────────────────
    //  3. INTERCEPT SUBMIT → inject base64
    // ──────────────────────────────────────────
    document.getElementById('ticket-form').addEventListener('submit', function (e) {
        const intakeType = document.getElementById('intake_type_input').value;

        if (!signaturePad.isEmpty()) {
            hidden.value = signaturePad.toDataURL('image/png');
        }

        // Validasi client-side sederhana
        const name = document.getElementById('customer_name').value.trim();
        if (!name) {
            e.preventDefault();
            alert('Harap isi nama pelanggan.');
            return;
        }

        if (intakeType === 'walkin') {
            const brand = document.getElementById('brand').value.trim();
            const model = document.getElementById('model').value.trim();
            const problem = document.getElementById('problem_desc').value.trim();
            const deviceType = document.querySelector('input[name="device_type"]:checked');

            if (!brand || !model || !problem || !deviceType) {
                e.preventDefault();
                alert('Harap isi semua field wajib (Nama, Jenis Perangkat, Merek, Tipe, dan Keluhan).');
                return;
            }

            // Validasi persetujuan syarat & ketentuan
            const agreeChk = document.getElementById('agree_terms');
            if (agreeChk && !agreeChk.checked) {
                e.preventDefault();
                document.getElementById('terms-error').classList.remove('hidden');
                agreeChk.closest('div').parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                setTimeout(() => openTermsModal(), 350);
                return;
            }
        }

        // Disable tombol agar tidak double-submit
        const btn = document.getElementById('btn-submit');
        btn.disabled = true;
        btn.innerHTML = `
            <svg class="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"/>
            </svg>
            Menyimpan\u2026`;
    });
})();
// ──────────────────────────────────────────────
//  3. PASSWORD TOGGLE
// ──────────────────────────────────────────────
(function () {
    const btn   = document.getElementById('btn-toggle-pass');
    const input = document.getElementById('device_password');
    const icon  = document.getElementById('eye-icon');
    if (!btn || !input) return;
    btn.addEventListener('click', () => {
        const show = input.type === 'password';
        input.type = show ? 'text' : 'password';
        // Swap eye / eye-slash icon
        icon.innerHTML = show
            ? `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                  d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242"/>
               <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M3 3l18 18"/>`
            : `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                  d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
               <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8"
                  d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7
                     -1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>`;
    });
})();

// ──────────────────────────────────────────────
//  4. AKSESORI LAIN-LAIN TOGGLE
// ──────────────────────────────────────────────
(function () {
    const chk   = document.getElementById('acc_other_chk');
    const input = document.getElementById('acc_other_text');
    if (!chk || !input) return;

    chk.addEventListener('change', () => {
        if (chk.checked) {
            input.classList.remove('hidden');
            input.focus();
        } else {
            input.classList.add('hidden');
            input.value = '';
        }
    });
})();
// ──────────────────────────────────────────────
//  TERMS & CONDITIONS MODAL
// ──────────────────────────────────────────────
(function () {
    const modal      = document.getElementById('terms-modal');
    const backdrop   = document.getElementById('terms-backdrop');
    const card       = document.getElementById('terms-card');
    const termsBody  = document.getElementById('terms-body');
    const scrollHint = document.getElementById('terms-scroll-hint');
    const checkbox   = document.getElementById('agree_terms');
    const termsError = document.getElementById('terms-error');

    window.openTermsModal = function () {
        modal.style.display = 'flex';
        // Force reflow sebelum animasi
        requestAnimationFrame(() => {
            requestAnimationFrame(() => {
                backdrop.style.opacity = '1';
                card.style.opacity     = '1';
                card.style.transform   = 'translateY(0)';
            });
        });
        document.body.style.overflow = 'hidden';
        updateScrollHint();
    };

    window.closeTermsModal = function () {
        backdrop.style.opacity = '0';
        card.style.opacity     = '0';
        card.style.transform   = 'translateY(52px)';
        setTimeout(() => {
            modal.style.display          = 'none';
            document.body.style.overflow = '';
            termsBody.scrollTop          = 0;
        }, 300);
    };

    function updateScrollHint() {
        if (!scrollHint) return;
        const atBottom = termsBody.scrollTop + termsBody.clientHeight >= termsBody.scrollHeight - 24;
        scrollHint.style.opacity = atBottom ? '0' : '1';
    }

    termsBody.addEventListener('scroll', updateScrollHint);

    // Buka modal
    document.getElementById('btn-open-terms')
        .addEventListener('click', openTermsModal);

    // Tutup modal — ikon X
    document.getElementById('btn-close-terms')
        .addEventListener('click', closeTermsModal);

    // Tutup modal — tombol Tutup bawah
    document.getElementById('btn-close-terms-2')
        .addEventListener('click', closeTermsModal);

    // Klik backdrop
    backdrop.addEventListener('click', closeTermsModal);

    // Tombol "Saya Telah Membaca" — centang checkbox + tutup
    document.getElementById('btn-agree-terms').addEventListener('click', function () {
        checkbox.checked = true;
        termsError.classList.add('hidden');
        // Visual feedback singkat sebelum tutup
        this.innerHTML = `
            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
            </svg>
            Disetujui!`;
        this.classList.replace('bg-brand-600', 'bg-green-600');
        this.classList.replace('hover:bg-brand-700', 'hover:bg-green-700');
        setTimeout(closeTermsModal, 700);
    });

    // Tutup dengan tombol ESC
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && modal.style.display !== 'none') {
            closeTermsModal();
        }
    });
})();
</script>
@endpush
