@extends('layouts.app')

@section('title', 'Lead Create')

@section('content')
    @include('leads.partials.contact-method-multiselect-style')
    <style>
        .lead-create-page { padding-top: 20px; }
        .lead-create-card { border: 1px solid #e5e9f0 !important; border-radius: 15px !important; box-shadow: 0 9px 30px rgba(15, 23, 42, .055) !important; overflow: hidden; }
        .lead-create-intro { display: flex; align-items: center; gap: 14px; padding: 20px 22px; border-bottom: 1px solid #e8ebf0; background: linear-gradient(135deg, #fff 0%, #f7f9ff 100%); }
        .lead-create-intro-icon { display: inline-flex; width: 46px; height: 46px; flex: 0 0 auto; align-items: center; justify-content: center; border-radius: 13px; background: #3454d1; color: #fff; font-size: 18px; box-shadow: 0 7px 16px rgba(52, 84, 209, .2); }
        .lead-create-grid > [class*="col-"] { margin-bottom: 18px !important; }
        .lead-form-section { grid-column: 1 / -1; width: 100%; margin: 8px 0 2px !important; padding-top: 18px; border-top: 1px solid #edf0f4; }
        .lead-form-section:first-child { margin-top: 0 !important; padding-top: 0; border-top: 0; }
        .lead-form-section-title { display: flex; align-items: center; gap: 9px; margin-bottom: 3px; color: #253047; font-size: 13px; font-weight: 750; }
        .lead-form-section-title i { display: inline-flex; width: 28px; height: 28px; align-items: center; justify-content: center; border-radius: 8px; background: #eef2ff; color: #3454d1; }
        .lead-form-section small { margin-left: 37px; color: #8792a2; }
        .lead-create-page .input-group .btn { min-width: 43px; border-radius: 0 9px 9px 0; }
        .lead-create-page .contact-value-group { flex-wrap: nowrap; }
        .lead-create-page .contact-value-group .contact-type-select {
            width: 108px !important;
            min-width: 108px !important;
            max-width: 108px !important;
            flex: 0 0 108px !important;
            padding-right: 28px;
            border-radius: 0 !important;
        }
        .lead-create-page .contact-value-group input.form-control { min-width: 0; flex: 1 1 auto; }
        .lead-create-page .social-value-group { flex-wrap: nowrap; }
        .lead-create-page .social-value-group .social-type-select {
            width: 112px !important;
            min-width: 112px !important;
            max-width: 112px !important;
            flex: 0 0 112px !important;
            padding-right: 28px;
            border-radius: 0 !important;
        }
        .lead-create-page .social-value-group input.form-control { min-width: 0; flex: 1 1 auto; }
        .lead-create-page .form-check { padding: 13px 14px 13px 38px; border: 1px solid #e4e8ef; border-radius: 10px; background: #fafbfc; }
        .lead-create-actions { position: sticky; bottom: 0; z-index: 5; display: flex; justify-content: flex-end; gap: 9px; padding: 15px 22px; border-top: 1px solid #e5e9f0; background: rgba(255, 255, 255, .96); backdrop-filter: blur(8px); }
        .lead-validation-modal .modal-content { border: 0; border-radius: 16px; box-shadow: 0 24px 70px rgba(15, 23, 42, .2); overflow: hidden; }
        .lead-validation-modal .modal-header { padding: 22px 24px 12px; border: 0; }
        .lead-validation-modal .modal-body { padding: 8px 24px 20px; }
        .lead-validation-modal .modal-footer { padding: 14px 24px 20px; border: 0; }
        .lead-validation-icon { display: inline-flex; width: 48px; height: 48px; flex: 0 0 auto; align-items: center; justify-content: center; border-radius: 14px; background: #fff1f2; color: #e11d48; font-size: 21px; }
        .lead-validation-list { max-height: 260px; margin: 0; padding: 0; overflow-y: auto; list-style: none; }
        .lead-validation-list li { display: flex; gap: 10px; padding: 10px 12px; color: #3f4757; background: #f8f9fb; border: 1px solid #eceff3; border-radius: 9px; }
        .lead-validation-list li + li { margin-top: 8px; }
        .lead-validation-list li i { flex: 0 0 auto; margin-top: 2px; color: #e11d48; }
        @media (max-width: 767.98px) {
            .lead-create-page { padding-top: 12px; }
            .lead-create-card { border-radius: 11px !important; }
            .lead-create-actions { padding: 12px 16px; }
            .lead-create-actions .btn { flex: 1 1 0; }
            .lead-create-page .contact-value-group .contact-type-select {
                width: 96px !important;
                min-width: 96px !important;
                max-width: 96px !important;
                flex-basis: 96px !important;
            }
            .lead-create-page .social-value-group .social-type-select {
                width: 100px !important;
                min-width: 100px !important;
                max-width: 100px !important;
                flex-basis: 100px !important;
            }
        }
    </style>
    <form id="createLeadForm" method="POST" action="{{ route('leads.store') }}">
    @csrf
    @if (!empty($ticketId))
        <input type="hidden" name="source_ticket_id" value="{{ $ticketId }}">
    @endif

        @if($viaContact)
            <input type="hidden" name="via_contact" value="1">
            <input type="hidden" name="contact_id" value="{{ $contactId }}">
        @endif

        <div class="page-header">
            <div class="page-header-left d-flex align-items-center">
                <a href="{{ route('leads') }}" class="avatar-text avatar-md me-3" title="Back to Leads" aria-label="Back to Leads">
                    <i class="feather-arrow-left"></i>
                </a>
                <div class="page-header-title">
                    <h5 class="mb-1">Create Lead</h5>
                    <small class="text-muted d-none d-lg-block">Add a new prospect to the sales pipeline</small>
                </div>
            </div>
            <div class="page-header-right ms-auto">
                <div class="page-header-right-items">
                    <div class="d-flex d-md-none">
                        <a href="javascript:void(0)" class="page-header-right-close-toggle">
                            <i class="feather-arrow-left me-2"></i>
                            <span>Back</span>
                        </a>
                    </div>
                    <div class="d-flex align-items-center gap-2 page-header-right-items-wrapper">
                        <a href="{{ route('leads') }}" class="btn btn-light-brand">
                            <i class="feather-x me-2"></i>
                            <span>Cancel</span>
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="feather-user-plus me-2"></i>
                            <span>Create Lead</span>
                        </button>
                    </div>
                </div>
                <div class="d-md-none d-flex align-items-center">
                    <a href="javascript:void(0)" class="page-header-right-open-toggle">
                        <i class="feather-align-right fs-20"></i>
                    </a>
                </div>
            </div>
        </div>
        <!-- [ page-header ] end -->
        <!-- [ Main Content ] start -->
        <div class="main-content lead-create-page">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card border-top-0 lead-create-card">
                        {{-- <div class="card-header p-0">
                                <!-- Nav tabs -->
                                <ul class="nav nav-tabs flex-wrap w-100 text-center customers-nav-tabs" id="myTab"
                                    role="tablist">
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link active" data-bs-toggle="tab"
                                            data-bs-target="#profileTab" role="tab">Profile</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#passwordTab" role="tab">Password</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#billingTab" role="tab">Billing & Shipping</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#subscriptionTab" role="tab">Subscription</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#notificationsTab" role="tab">Notifications</a>
                                    </li>
                                    <li class="nav-item flex-fill border-top" role="presentation">
                                        <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                            data-bs-target="#connectionTab" role="tab">Connection</a>
                                    </li>
                                </ul>
                            </div> --}}


                        <div class="tab-content">
                            <div class="tab-pane fade show active" id="profileTab" role="tabpanel">
                                <div class="lead-create-intro">
                                    <span class="lead-create-intro-icon"><i class="feather-user-plus"></i></span>
                                    <div>
                                        <h5 class="fw-bold mb-1">New Lead Information</h5>
                                        <p class="text-muted mb-0">Capture ownership, contact details and qualification information.</p>
                                    </div>
                                </div>
                                <div class="card-body personal-info">
                                    {{-- <div class="row mb-4 align-items-center">
                                                <div class="col-lg-4">
                                                    <label class="fw-semibold">Avatar: </label>
                                                </div>
                                                <div class="col-lg-8">
                                                    <div class="mb-4 mb-md-0 d-flex gap-4 your-brand">
                                                        <div
                                                            class="wd-100 ht-100 position-relative overflow-hidden border border-gray-2 rounded">
                                                            <img src="assets/images/avatar/1.png"
                                                                class="upload-pic img-fluid rounded h-100 w-100"
                                                                alt="">
                                                            <div
                                                                class="position-absolute start-50 top-50 end-0 bottom-0 translate-middle h-100 w-100 hstack align-items-center justify-content-center c-pointer upload-button">
                                                                <i class="feather feather-camera"
                                                                    aria-hidden="true"></i>
                                                            </div>
                                                            <input class="file-upload" type="file" accept="image/*">
                                                        </div>
                                                        <div class="d-flex flex-column gap-1">
                                                            <div class="fs-11 text-gray-500 mt-2"># Upload your prifile
                                                            </div>
                                                            <div class="fs-11 text-gray-500"># Avatar size 150x150</div>
                                                            <div class="fs-11 text-gray-500"># Max upload size 2mb</div>
                                                            <div class="fs-11 text-gray-500"># Allowed file types: png,
                                                                jpg, jpeg</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div> --}}

                                    <div class="row lead-create-grid">
                                        @php
                                            $selectedContactId = request('id');
                                            $primaryContactId = old('primary_contact', $selectedContactId);
                                            $selectedContact = null;

                                            if ($selectedContactId) {
                                                $selectedContact = $contacts->firstWhere('id', $selectedContactId);

                                                // Fetch phones and emails if $selectedContact exists
                                                $phones = $selectedContact ? $selectedContact->phones ?? [] : [];
                                                $emails = $selectedContact ? $selectedContact->emails ?? [] : [];
                                                $socialMedias = $selectedContact ? $selectedContact->socialMedias ?? [] : [];
                                                $selectedLanguages = $selectedContact ? $selectedContact->contactLanguages ?? [] : [];

                                            } else {
                                                $phones = [];
                                                $emails = [];
                                                $socialMedias = [];
                                                $selectedLanguages = [];
                                            }

                                        @endphp

                                        <div class="col-12 lead-form-section">
                                            <div class="lead-form-section-title"><i class="feather-compass"></i>Lead Assignment</div>
                                            <small>Define the source, owner and purpose of this Lead.</small>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="primary-contact-dropdown" class="fw-semibold">Contact:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group lead-contact-search">
                                                    <div class="input-group-text"><i
                                                            class="feather-user"></i>
                                                    </div>
                                                    <select class="form-control" name="primary_contact"
                                                        id="primary-contact-dropdown"
                                                        data-lead-contact-search data-placeholder="Search and select contact"
                                                        {{ $selectedContactId ? 'disabled' : '' }}>
                                                        {{-- Disable if `id` is passed --}}
                                                        <option value="" @selected(blank($primaryContactId))></option>
                                                        @foreach ($contacts as $contact)
                                                            <option value="{{ $contact->id }}" @selected((int) $primaryContactId === (int) $contact->id)>
                                                                {{ trim($contact->first_name.' '.$contact->last_name) ?: 'Contact #'.$contact->id }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                @if ($selectedContactId)
                                                    <input type="hidden" name="primary_contact"
                                                        value="{{ $selectedContactId }}">
                                                    {{-- Add hidden input to submit contact ID when disabled --}}
                                                @endif
                                            </div>
                                        </div>



                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Contact Owner <span class="text-danger">*</span></label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-user"></i>
                                                    </div>
                                                    <select class="form-control @error('contact_owner') is-invalid @enderror" name="contact_owner" id="contact-owner-dropdown" required>
                                                        @foreach ($users as $user)
                                                            <option value="{{ $user->id }}" @selected((int) old('contact_owner', auth()->id()) === (int) $user->id)>
                                                                {{ $user->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                @error('contact_owner')
                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                @enderror
                                            </div>
                                        </div>




                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Lead Source: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-minus-circle"></i>
                                                    </div>
                                                    <select class="form-control" name="lead_source" id="lead-source-dropdown">
                                                        <option value="">Select Lead Source</option>
                                                        <option value="1">Social Media</option>
                                                        <option value="2">Referral</option>
                                                        <option value="3">Email Campaign</option>
                                                        <option value="4">Cold Call</option>
                                                        <option value="5">Trade Show</option>
                                                        <option value="6">Website</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="topicInput" class="fw-semibold">Topic <span class="text-danger">*</span></label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-message-square"></i>
                                                    </div>
                                                    <input type="text" class="form-control" name="topic"
                                                        id="topicInput" placeholder="e.g. Enterprise CRM enquiry" value="{{ old('topic') }}" required>
                                                </div>
                                                @error('topic')
                                                    <small class="text-danger">{{ $message }}</small>
                                                @enderror
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="qualificationInput" class="fw-semibold">Qualification</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-award"></i></div>
                                                    <input type="text" class="form-control"
                                                        name="qualification" id="qualificationInput" maxlength="255"
                                                        value="{{ old('qualification') }}"
                                                        placeholder="e.g. Budget and authority confirmed">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center" id="unqualifiedReasonField">
                                            <label class="fw-semibold mb-2">Unqualified Reason:</label>
                                            <textarea class="form-control" name="unqualified_reason" rows="3"
                                                placeholder="Required when Lead Status is Unqualified">{{ old('unqualified_reason') }}</textarea>
                                        </div>
                                        <div class="col-md-6 mb-4 d-flex align-items-center">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="confirm_duplicate" value="1"
                                                    id="confirmDuplicate" @checked(old('confirm_duplicate'))>
                                                <label class="form-check-label" for="confirmDuplicate">
                                                    Confirm creation if a possible duplicate is detected
                                                </label>
                                                @error('duplicate')<div class="text-danger mt-1">{{ $message }}</div>@enderror
                                            </div>
                                        </div>


                                        <div class="col-12 lead-form-section">
                                            <div class="lead-form-section-title"><i class="feather-user"></i>Contact Information</div>
                                            <small>Add the person, company and direct communication details.</small>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="firstNameInput" class="fw-semibold">First Name</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                                    <input type="text" class="form-control" name="first_name"
                                                        id="firstNameInput" placeholder="First Name"
                                                        value="{{ old('first_name', $selectedContact->first_name ?? '') }}">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="lastNameInput" class="fw-semibold">Last Name:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                                    <input type="text" class="form-control" name="last_name"
                                                        id="lastNameInput" placeholder="Last Name"
                                                        value="{{ $selectedContact->last_name ?? '' }}">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Company Name: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-home"></i>
                                                    </div>
                                                    <select class="form-control" name="company_id" id="company-dropdown">
                                                        <option value="">Select Company</option>
                                                        @foreach ($companies as $company)
                                                            <option value="{{ $company->id }}"
                                                                {{ $selectedContact && $selectedContact->company_id == $company->id ? 'selected' : '' }}>
                                                                {{ $company->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>

                                                    <button type="button" class="btn btn-primary" onclick="openAddCompanyModal()">
                                                        <i class="feather-plus"></i>
                                                    </button>
                                                </div>

                                                {{-- If disabled, keep hidden value --}}
                                                @if ($selectedContactId)
                                                    <input type="hidden" name="company_id" value="{{ $selectedContact->company_id }}">
                                                @endif
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Industry: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i
                                                            class="feather-minus-square"></i>
                                                    </div>
                                                <select class="form-control" name="industry_id" id="industry-dropdown">
                                                    <option value="">Select Industry</option>
                                                    <option value="1">Technology</option>
                                                    <option value="2">Finance</option>
                                                    <option value="3">Healthcare</option>
                                                    <option value="4">Retail</option>
                                                    <option value="5">Manufacturing</option>
                                                    <option value="6">Energy</option>
                                                </select>
                                                </div>
                                            </div>
                                        </div>


                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="jobTitleInput" class="fw-semibold">Job Title:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-briefcase"></i>
                                                    </div>
                                                    <input type="text" class="form-control" name="job_title"
                                                        id="jobTitleInput" value="{{ $selectedContact->job_title ?? '' }}" placeholder="Job Title">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="zipCodeInput" class="fw-semibold">Zip Code:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-tag"></i>
                                                    </div>
                                                    <input type="number" name="zipcode" class="form-control"
                                                        id="zipCodeInput" value="{{ $selectedContact->zip_code ?? '' }}" placeholder="Zip Code">
                                                </div>
                                            </div>
                                        </div>

                                        <div id="phoneContainer" class="col-md-6 mb-4">
                                            <div class="col-lg-4 mb-2">
                                                <label for="phoneInput" class="fw-semibold">Phone Number <span class="text-danger">*</span></label>
                                                <small class="text-muted d-block">Use + to add multiple numbers</small>
                                            </div>
                                            <div class="col-lg-12">
                                                @forelse ($phones as $phone)
                                            <div class="row align-items-center mb-2 phone-row">
                                                <div class="col-md-12">
                                                    <div class="input-group contact-value-group">
                                                        <div class="input-group-text">
                                                            <i class="feather-phone"></i>
                                                        </div>
                                                        <select class="form-select contact-type-select" name="phone_types[]">
                                                            <option value="1" {{ $phone->phone_type_id == 1 ? 'selected' : '' }}>Mobile</option>
                                                            <option value="2" {{ $phone->phone_type_id == 2 ? 'selected' : '' }}>Home</option>
                                                            <option value="3" {{ $phone->phone_type_id == 3 ? 'selected' : '' }}>Work</option>
                                                            <option value="4" {{ $phone->phone_type_id == 4 ? 'selected' : '' }}>Other</option>
                                                        </select>
                                                        <input type="tel" name="phones[]" class="form-control @if($errors->has('phones') || $errors->has('phones.*')) is-invalid @endif" value="{{ $phone->phone }}" maxlength="50" required>
                                                        <button type="button" class="btn btn-primary" onclick="addPhoneField()">
                                                            <i class="feather-plus"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        @empty
                                            {{-- default empty row if no phones --}}
                                            <div class="row align-items-center mb-2 phone-row">
                                                <div class="col-md-12">
                                                    <div class="input-group contact-value-group">
                                                        <div class="input-group-text">
                                                            <i class="feather-phone"></i>
                                                        </div>
                                                        <select class="form-select contact-type-select" name="phone_types[]">
                                                            <option value="1">Mobile</option>
                                                            <option value="2">Home</option>
                                                            <option value="3">Work</option>
                                                            <option value="4">Other</option>
                                                        </select>
                                                        <input type="tel" name="phones[]" class="form-control @if($errors->has('phones') || $errors->has('phones.*')) is-invalid @endif" placeholder="Phone Number" maxlength="50" required>
                                                        <button type="button" class="btn btn-primary" onclick="addPhoneField()">
                                                            <i class="feather-plus"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        @endforelse
                                                @error('phones')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                                                @error('phones.*')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                                            </div>
                                        </div>

                                        <div id="emailContainer" class="col-md-6 mb-4">
                                            <div class="col-lg-4 mb-2">
                                                <label for="mailInput" class="fw-semibold">Email: </label>
                                                <small class="text-muted d-block">Use + to add multiple addresses</small>
                                            </div>
                                            <div class="col-lg-12">
                                                @forelse ($emails as $email)
                                                    <div class="row align-items-center mb-2 email-row">
                                                        <div class="col-md-12">
                                                            <div class="input-group contact-value-group">
                                                                <div class="input-group-text">
                                                                    <i class="feather-mail"></i>
                                                                </div>
                                                                <select class="form-select contact-type-select" name="email_types[]">
                                                                    <option value="1" {{ $email->type == 1 ? 'selected' : '' }}>Personal</option>
                                                                    <option value="2" {{ $email->type == 2 ? 'selected' : '' }}>Work</option>
                                                                    <option value="3" {{ $email->type == 3 ? 'selected' : '' }}>Other</option>
                                                                </select>
                                                                <input type="email" name="emails[]" class="form-control" placeholder="Email Address" value="{{ $email->email }}">
                                                                <button type="button" class="btn btn-primary" onclick="addEmailField()">
                                                                    <i class="feather-plus"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @empty
                                                    {{-- Default empty row if no emails --}}
                                                    <div class="row align-items-center mb-2 email-row">
                                                        <div class="col-md-12">
                                                            <div class="input-group contact-value-group">
                                                                <div class="input-group-text">
                                                                    <i class="feather-mail"></i>
                                                                </div>
                                                                <select class="form-select contact-type-select" name="email_types[]">
                                                                    <option value="1">Personal</option>
                                                                    <option value="2">Work</option>
                                                                    <option value="3">Other</option>
                                                                </select>
                                                                <input type="email" name="emails[]" class="form-control" placeholder="Email Address">
                                                                <button type="button" class="btn btn-primary" onclick="addEmailField()">
                                                                    <i class="feather-plus"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endforelse
                                            </div>
                                        </div>


                                        <div class="col-12 lead-form-section">
                                            <div class="lead-form-section-title"><i class="feather-map-pin"></i>Location</div>
                                            <small>Record the Lead's primary address and regional information.</small>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="addressInput_2" class="fw-semibold">Address 1:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-map-pin"></i>
                                                    </div>
                                                    <textarea class="form-control" name="address1" id="addressInput_2" cols="30" rows="3"
                                                        placeholder="Address">{{ $selectedContact->address_1 ?? '' }}</textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label for="addressInput_2" class="fw-semibold">Address 2:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-map-pin"></i>
                                                    </div>
                                                    <textarea class="form-control" name="address2" id="addressInput_2" cols="30" rows="3"
                                                        placeholder="Address">{{ $selectedContact->address_2 ?? '' }}</textarea>
                                                </div>
                                            </div>
                                        </div>


                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="cityInput" class="fw-semibold">City: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-map-pin"></i></div>
                                                    <input type="text" name="city" class="form-control"
                                                        id="cityInput" value="{{ $selectedContact->city ?? '' }}" placeholder="Enter City">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-4 col-md-6">
                                            <div class="col-lg-4 mb-2">
                                                <label for="provinceInput" class="fw-semibold">Province:
                                                </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-map"></i>
                                                    </div>
                                                    <input type="text" name="province" class="form-control"
                                                        id="provinceInput" value="{{ $selectedContact->province ?? '' }}" placeholder="Enter Province">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Country: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-globe"></i></div>
                                                    @php
                                                        $selectedCountryId = old('country_id', $selectedContact?->country_id);
                                                    @endphp
                                                    <select class="form-control" name="country_id" id="countrySelect" data-select2-selector="country">
                                                        <option value="" disabled @selected(blank($selectedCountryId))>Select Country</option>
                                                        @foreach ($countries as $country)
                                                            <option value="{{ $country->id }}" data-country="{{ strtolower($country->country_code ?? '') }}"
                                                                @selected((int) $selectedCountryId === (int) $country->id)>
                                                                {{ $country->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                        </div>



                                        <div class="col-12 lead-form-section">
                                            <div class="lead-form-section-title"><i class="feather-message-circle"></i>Communication Preferences</div>
                                            <small>Set social channels, preferred contact methods and languages.</small>
                                        </div>

                                        <div id="socialMediaContainer" class="col-md-6 mb-4">
                                            <div class="col-lg-4 mb-2">
                                                <label for="socialMediaInput" class="fw-semibold">Social Media:</label>
                                                <small class="text-muted d-block">Use + to add multiple profiles</small>
                                            </div>
                                            <div class="col-lg-12">

                                                @if(!empty($socialMedias) && count($socialMedias) > 0)
                                                    @foreach($socialMedias as $media)
                                                        <div class="row align-items-center mb-2 social-media-row">
                                                            <div class="col-md-12">
                                                                <div class="input-group social-value-group">
                                                                    <!-- Social Media Icon -->
                                                                    <div class="input-group-text">
                                                                        @php
                                                                            $icons = [
                                                                                1 => 'facebook',
                                                                                2 => 'twitter',
                                                                                3 => 'linkedin',
                                                                                4 => 'instagram',
                                                                                5 => 'globe' // generic for "other"
                                                                            ];
                                                                            $icon = $icons[$media['social_media_type_id']] ?? 'facebook';
                                                                        @endphp
                                                                        <i class="feather-{{ $icon }}"></i>
                                                                    </div>

                                                                    <!-- Social Media Type -->
                                                                    <select class="form-select social-type-select"
                                                                        name="social_media_types[]" onchange="changeSocialMediaIcon(this)">
                                                                        <option data-id="1" value="facebook" {{ $media['social_media_type_id'] == 1 ? 'selected' : '' }}>Facebook</option>
                                                                        <option data-id="2" value="twitter" {{ $media['social_media_type_id'] == 2 ? 'selected' : '' }}>Twitter</option>
                                                                        <option data-id="3" value="linkedin" {{ $media['social_media_type_id'] == 3 ? 'selected' : '' }}>LinkedIn</option>
                                                                        <option data-id="4" value="instagram" {{ $media['social_media_type_id'] == 4 ? 'selected' : '' }}>Instagram</option>
                                                                        <option data-id="5" value="other" {{ $media['social_media_type_id'] == 5 ? 'selected' : '' }}>Other</option>
                                                                    </select>

                                                                    <!-- Social Media Input -->
                                                                    <input type="text" name="social_media_values[]" class="form-control"
                                                                        placeholder="Social Media URL"
                                                                        value="{{ $media['value'] ?? '' }}">

                                                                    <!-- Add Button -->
                                                                    <button type="button" class="btn btn-primary" onclick="addSocialMediaField()">
                                                                        <i class="feather-plus"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    @endforeach
                                                @else
                                                    <!-- Default Empty Row -->
                                                    <div class="row align-items-center mb-2 social-media-row">
                                                        <div class="col-md-12">
                                                            <div class="input-group social-value-group">
                                                                <div class="input-group-text">
                                                                    <i class="feather-facebook" id="icon-facebook"></i>
                                                                </div>
                                                                <select class="form-select social-type-select"
                                                                    name="social_media_types[]" onchange="changeSocialMediaIcon(this)">
                                                                    <option value="">Select Platform</option>
                                                                    <option data-id="1" value="facebook">Facebook</option>
                                                                    <option data-id="2" value="twitter">Twitter</option>
                                                                    <option data-id="3" value="linkedin">LinkedIn</option>
                                                                    <option data-id="4" value="instagram">Instagram</option>
                                                                    <option data-id="5" value="other">Other</option>
                                                                </select>
                                                                <input type="text" name="social_media_values[]" class="form-control @if($errors->has('social_media_values.*')) is-invalid @endif"
                                                                    placeholder="Social Media URL">
                                                                <button type="button" class="btn btn-primary" onclick="addSocialMediaField()">
                                                                    <i class="feather-plus"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endif
                                                @error('social_media_types.*')
                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                @enderror
                                                @error('social_media_values.*')
                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                @enderror

                                            </div>
                                        </div>




                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Contact Method: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group contact-method-field lead-one-line-multiselect">
                                                    <div class="input-group-text"><i class="feather-paperclip"></i></div>
                                                    <select class="form-control contact-method-one-line lead-one-line-select @error('contact_methods') is-invalid @enderror"
                                                        name="contact_methods[]" id="contactMethodSelect" multiple
                                                        data-lead-multiselect data-placeholder="Select contact methods">
                                                        @foreach (['Phone', 'Email', 'Social Media', 'Postal Mail', 'Fax'] as $method)
                                                            <option value="{{ $method }}" @selected(in_array($method, old('contact_methods', []), true))>{{ $method }}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                @error('contact_methods')
                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                @enderror
                                            </div>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Languages: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group language-field lead-one-line-multiselect">
                                                    <div class="input-group-text"><i class="feather-globe"></i></div>
                                                    @php
                                                        $oldLanguageIds = array_map('intval', old('languages', []));
                                                    @endphp
                                                    <select class="form-control lead-one-line-select @error('languages') is-invalid @enderror"
                                                        name="languages[]" multiple data-lead-multiselect
                                                        data-placeholder="Select languages">
                                                        @foreach ($languages as $language)
                                                            <option value="{{ $language->id }}"
                                                                @selected(in_array((int) $language->id, $oldLanguageIds, true))>
                                                                {{ $language->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                @error('languages')
                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                @enderror
                                            </div>
                                        </div>


                                        <div class="col-12 lead-form-section">
                                            <div class="lead-form-section-title"><i class="feather-trending-up"></i>Qualification</div>
                                            <small>Set the initial pipeline status, product interest and record availability.</small>
                                        </div>

                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Lead Status</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-activity"></i></div>
                                                    <select class="form-control" name="stage_id" id="leadStageSelect"
                                                        data-select2-selector="stage">
                                                        @foreach ($stages as $stage)
                                                            <option value="{{ $stage->id }}" @selected((int) old('stage_id', $stages->first()?->id) === (int) $stage->id)>
                                                                {{ $stage->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                        </div>



                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Interest Product:</label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group lead-one-line-multiselect">
                                                    <div class="input-group-text"><i class="feather-shopping-bag"></i></div>
                                                    <select class="form-control lead-one-line-select" name="interest_products[]"
                                                        multiple data-select2-selector="default">
                                                        @foreach ($products as $product)
                                                            <option value="{{ $product->id }}" @selected(in_array($product->id, array_map('intval', old('interest_products', [])), true))>
                                                                {{ $product->product_name }}{{ $product->product_code ? ' · '.$product->product_code : '' }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                        </div>




                                        <div class="col-md-6 mb-4 align-items-center">
                                            <div class="col-lg-4 mb-2">
                                                <label class="fw-semibold">Status: </label>
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-alert-circle"></i></div>
                                                    <select class="form-control" name="status"
                                                        data-select2-selector="status">
                                                        <option value="active" data-bg="bg-success" selected>
                                                            Active
                                                        </option>
                                                        <option value="inactive" data-bg="bg-warning">Inactive
                                                        </option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="lead-create-actions">
                                    <a href="{{ route('leads') }}" class="btn btn-light"><i class="feather-x me-1"></i>Cancel</a>
                                    <button type="submit" class="btn btn-primary"><i class="feather-user-plus me-1"></i>Create Lead</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <div class="modal fade lead-validation-modal" id="leadValidationModal" tabindex="-1"
        aria-labelledby="leadValidationModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header align-items-start">
                    <div class="d-flex align-items-center gap-3">
                        <span class="lead-validation-icon"><i class="feather-alert-triangle"></i></span>
                        <div>
                            <h5 class="modal-title mb-1" id="leadValidationModalLabel">Please review the form</h5>
                            <p class="text-muted mb-0">We could not create the Lead until these fields are corrected.</p>
                        </div>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <ul class="lead-validation-list" id="leadValidationList" aria-live="polite"></ul>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">
                        <i class="feather-edit-3 me-1"></i>Review Form
                    </button>
                </div>
            </div>
        </div>
    </div>


@endsection

<style>
    .input-group .select2-container {
        flex: 1;
    }
</style>

@section('scripts')
    <script>
        function addPhoneField() {
            const newPhoneRow = `
        <div class="row align-items-center mb-2 phone-row">
            <div class="col-md-12">
                <div class="input-group contact-value-group">
                    <div class="input-group-text">
                        <i class="feather-phone"></i>
                    </div>
                    <select class="form-select contact-type-select" name="phone_types[]">
                        <option value="1">Mobile</option>
                        <option value="2">Home</option>
                        <option value="3">Work</option>
                        <option value="4">Other</option>
                    </select>
                    <input type="tel" name="phones[]" class="form-control" placeholder="Phone Number" maxlength="50" required>
                    <button type="button" class="btn btn-danger" onclick="removePhoneField(this)">
                        <i class="feather-trash-2"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
            document.querySelector("#phoneContainer .col-lg-12").insertAdjacentHTML('beforeend', newPhoneRow);
        }

        function removePhoneField(button) {
            button.closest(".phone-row").remove();
        }

        function addEmailField() {
            const newEmailRow = `
        <div class="row align-items-center mb-2 email-row">
            <div class="col-md-12">
                <div class="input-group contact-value-group">
                    <div class="input-group-text">
                        <i class="feather-mail"></i>
                    </div>
                    <select class="form-select contact-type-select" name="email_types[]">
                        <option value="1">Personal</option>
                        <option value="2">Work</option>
                        <option value="3">Other</option>
                    </select>
                    <input type="email" name="emails[]" class="form-control" placeholder="Email Address">
                    <button type="button" class="btn btn-danger" onclick="removeEmailField(this)">
                        <i class="feather-trash-2"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
            document.querySelector("#emailContainer .col-lg-12").insertAdjacentHTML('beforeend', newEmailRow);
        }

        function removeEmailField(button) {
            button.closest(".email-row").remove();
        }


        function addSocialMediaField() {
            const newSocialMediaRow = `
        <div class="row align-items-center mb-2 social-media-row">
            <div class="col-md-12">
                <div class="input-group social-value-group">
                    <!-- Default Social Media Icon -->
                    <div class="input-group-text">
                        <i class="feather-facebook" id="icon-facebook"></i>
                    </div>
                    <!-- Social Media Type -->
                    <select class="form-select social-type-select" name="social_media_types[]" onchange="changeSocialMediaIcon(this)">
                        <option value="">Select Platform</option>
                        <option data-id="1" value="facebook">Facebook</option>
                        <option data-id="2" value="twitter">Twitter</option>
                        <option data-id="3" value="linkedin">LinkedIn</option>
                        <option data-id="4" value="instagram">Instagram</option>
                        <option data-id="5" value="other">Other</option>
                    </select>
                    <!-- Social Media Input -->
                    <input type="text" class="form-control" name="social_media_values[]" placeholder="Social Media URL">
                    <!-- Remove Button -->
                    <button type="button" class="btn btn-danger" onclick="removeSocialMediaField(this)">
                        <i class="feather-trash-2"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
            document.querySelector("#socialMediaContainer .col-lg-12").insertAdjacentHTML('beforeend', newSocialMediaRow);
        }

        function removeSocialMediaField(button) {
            button.closest(".social-media-row").remove();
        }

        function changeSocialMediaIcon(selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const selectedId = selectedOption.getAttribute('data-id'); // Get the id of the selected social media
            const iconElement = selectElement.closest('.input-group').querySelector('.input-group-text i');

            // Change the icon based on the selected id
            switch (selectedId) {
                case "1":
                    iconElement.className = "feather-facebook";
                    break;
                case "2":
                    iconElement.className = "feather-twitter";
                    break;
                case "3":
                    iconElement.className = "feather-linkedin";
                    break;
                case "4":
                    iconElement.className = "feather-instagram";
                    break;
                default:
                    iconElement.className = "feather-globe"; // Default icon for 'other'
                    break;
            }
        }

    </script>

    <!-- <script>
        $(document).ready(function() {
            $('#lead-source-dropdown').select2({
                placeholder: "Select Lead Source",
                minimumResultsForSearch: 0,
                width: 'resolve'
            });
        });
    </script> -->

    <!-- <script>
        $(document).ready(function() {
            $('#contact-owner-dropdown').select2({
                placeholder: "Select Owner",
                minimumResultsForSearch: 0,
                width: 'resolve'
            });
        });
    </script> -->

    <script>
        $(document).ready(function() {
            $('#company-dropdown').select2({
                placeholder: "Select Company",
                minimumResultsForSearch: 0,
                width: 'resolve'
            });
        });
    </script>

    <script>
        function openAddCompanyModal() {
            const addCompanyModal = new bootstrap.Modal(document.getElementById('addCompanyModal'));
            addCompanyModal.show();
        }

        function saveNewCompany() {
            const companyName = document.getElementById('newCompanyName').value.trim();

            if (companyName) {
                // Perform an AJAX request to save the company to the backend
                fetch("{{ route('companies.store') }}", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        },
                        body: JSON.stringify({
                            name: companyName
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Add the new company to the dropdown
                            const companyDropdown = document.getElementById('company-dropdown');
                            const newOption = document.createElement('option');
                            newOption.text = data.data.name; // Use the company name from the response
                            newOption.value = data.data.id; // Use the company ID from the response
                            newOption.selected = true; // Select the new company by default
                            companyDropdown.add(newOption);

                            // Close the modal
                            const addCompanyModal = bootstrap.Modal.getInstance(document.getElementById(
                                'addCompanyModal'));
                            addCompanyModal.hide();

                            // Clear the input field for next use
                            document.getElementById('newCompanyName').value = '';
                        } else {
                            alert('Failed to add company. Please try again.');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('An error occurred. Please try again.');
                    });
            } else {
                alert('Please enter a valid company name.');
            }
        }
    </script>
    
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const stageSelect = document.getElementById('leadStageSelect');
            const reasonField = document.getElementById('unqualifiedReasonField');
            const reasonInput = reasonField?.querySelector('textarea');
            const toggleUnqualifiedReason = function () {
                const isUnqualified = String(stageSelect?.value) === '7';
                reasonField?.classList.toggle('d-none', !isUnqualified);
            };

            toggleUnqualifiedReason();
            stageSelect?.addEventListener('change', toggleUnqualifiedReason);
            if (window.jQuery) $(stageSelect).on('change.select2', toggleUnqualifiedReason);
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const form = document.getElementById('createLeadForm');
            const modalElement = document.getElementById('leadValidationModal');
            const errorList = document.getElementById('leadValidationList');
            if (!form || !modalElement || !errorList || !window.bootstrap) return;

            const validationModal = bootstrap.Modal.getOrCreateInstance(modalElement);
            let focusAfterClose = null;
            let popupQueued = false;

            const fieldLabel = function (field) {
                const wrapper = field.closest('.col-md-6, .col-md-12, .form-check') || form;
                const label = (field.id && form.querySelector(`label[for="${field.id}"]`)) || wrapper.querySelector('label');
                if (label) return label.textContent.replace('*', '').replace(':', '').replace(/\s+/g, ' ').trim();
                return (field.name || 'This field')
                    .replace(/\[\]|\.\d+/g, '')
                    .replace(/_/g, ' ')
                    .replace(/\b\w/g, character => character.toUpperCase());
            };

            const focusField = function (field) {
                if (!field) return;
                const section = field.closest('.col-md-6, .col-md-12, .form-check') || field;
                section.scrollIntoView({ behavior: 'smooth', block: 'center' });
                window.setTimeout(function () {
                    if (field.matches('select') && window.jQuery && jQuery.fn.select2 && jQuery(field).hasClass('select2-hidden-accessible')) {
                        jQuery(field).select2('open');
                    } else {
                        field.focus({ preventScroll: true });
                    }
                }, 350);
            };

            const showValidationPopup = function (messages, firstField) {
                const uniqueMessages = [...new Set(messages.filter(Boolean))];
                errorList.replaceChildren();
                uniqueMessages.forEach(function (message) {
                    const item = document.createElement('li');
                    const icon = document.createElement('i');
                    const text = document.createElement('span');
                    icon.className = 'feather-alert-circle';
                    text.textContent = message;
                    item.append(icon, text);
                    errorList.appendChild(item);
                });
                focusAfterClose = firstField || null;
                validationModal.show();
            };

            modalElement.addEventListener('hidden.bs.modal', function () {
                const field = focusAfterClose;
                focusAfterClose = null;
                focusField(field);
            });

            form.addEventListener('invalid', function (event) {
                event.preventDefault();
                event.target.classList.add('is-invalid');
                if (popupQueued) return;
                popupQueued = true;
                window.setTimeout(function () {
                    popupQueued = false;
                    const invalidFields = [...form.querySelectorAll(':invalid')]
                        .filter(field => !field.disabled && field.type !== 'hidden');
                    const messages = invalidFields.map(function (field) {
                        const label = fieldLabel(field);
                        return field.validity.valueMissing
                            ? `${label} is required.`
                            : `${label} has an invalid value.`;
                    });
                    showValidationPopup(messages, invalidFields[0]);
                }, 0);
            }, true);

            form.addEventListener('input', function (event) {
                if (event.target.validity?.valid) event.target.classList.remove('is-invalid');
            });
            form.addEventListener('change', function (event) {
                if (event.target.validity?.valid) event.target.classList.remove('is-invalid');
            });

            @if ($errors->any())
                const serverErrors = @json($errors->all());
                const firstErrorName = @json(array_key_first($errors->toArray()));
                const baseErrorName = String(firstErrorName || '').split('.')[0];
                const firstErrorField = [...form.elements].find(function (field) {
                    return field.name === firstErrorName || field.name === baseErrorName || field.name === `${baseErrorName}[]`;
                }) || form.querySelector('.is-invalid');

                if (firstErrorField) firstErrorField.classList.add('is-invalid');
                showValidationPopup(serverErrors, firstErrorField);
            @endif
        });
    </script>
@endsection
