@extends('layouts.admin')

@section('title', 'General Settings')

@section('page-title', 'General Settings')

@section('breadcrumbs')
    <a href="{{ route('admin.settings.index') }}" class="hover:text-primary">Settings</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">General</span>
@endsection

@section('content')
<div class="max-w-7xl mx-auto">
    <!-- Tabs Navigation -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-6">
        <div class="border-b border-gray-200">
            <nav class="flex -mb-px bg-gray-50/50">

                <a href="{{ route('admin.settings.general', ['tab' => 'company']) }}" class="px-6 py-4 text-sm font-medium border-b-2 {{ ($tab ?? 'company') === 'company' ? 'border-primary text-primary bg-white' : 'border-transparent text-gray-600 hover:text-primary hover:border-gray-300 hover:bg-white/50' }} transition-colors">
                    Company Settings
                </a>
                <a href="{{ route('admin.settings.general', ['tab' => 'localization']) }}" class="px-6 py-4 text-sm font-medium border-b-2 {{ ($tab ?? 'company') === 'localization' ? 'border-primary text-primary bg-white' : 'border-transparent text-gray-600 hover:text-primary hover:border-gray-300 hover:bg-white/50' }} transition-colors">
                    Localization Settings
                </a>
                <a href="{{ route('admin.settings.general', ['tab' => 'signatures']) }}" class="px-6 py-4 text-sm font-medium border-b-2 {{ ($tab ?? 'company') === 'signatures' ? 'border-primary text-primary bg-white' : 'border-transparent text-gray-600 hover:text-primary hover:border-gray-300 hover:bg-white/50' }} transition-colors">
                    Signatures
                </a>
            </nav>
        </div>

        <div class="p-6">
            @if(($tab ?? 'company') === 'company')
                <!-- Company Settings Tab -->
                <form method="POST" action="{{ route('admin.settings.company.update') }}" enctype="multipart/form-data" class="flex flex-col gap-6">
                    @csrf
                    <!-- Card 1: Company Details -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                        <div class="px-6 py-4 border-b border-gray-200 bg-gray-50/50">
                            <h2 class="text-lg font-bold text-gray-900">Company Details</h2>
                        </div>
                        <div class="p-6 grid grid-cols-1 md:grid-cols-2 gap-6 bg-gray-50/30">
                            <div class="flex flex-col gap-1.5">
                                <label class="text-sm font-medium text-gray-700">Company Name <span class="text-red-500">*</span></label>
                                <input name="company_name" value="{{ old('company_name', $companySettings->company_name ?? '') }}" required class="form-input rounded-lg border-gray-300 bg-white text-gray-900 px-3 py-2.5 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-shadow" type="text"/>
                            </div>
                            <div class="flex flex-col gap-1.5">
                                <label class="text-sm font-medium text-gray-700">Company Email <span class="text-red-500">*</span></label>
                                <input name="company_email" value="{{ old('company_email', $companySettings->company_email ?? '') }}" required class="form-input rounded-lg border-gray-300 bg-white text-gray-900 px-3 py-2.5 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-shadow" type="email"/>
                            </div>
                            <div class="flex flex-col gap-1.5">
                                <label class="text-sm font-medium text-gray-700">Mobile Number <span class="text-red-500">*</span></label>
                                <input name="company_phone" value="{{ old('company_phone', $companySettings->company_phone ?? '') }}" required class="form-input rounded-lg border-gray-300 bg-white text-gray-900 px-3 py-2.5 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-shadow" type="tel"/>
                            </div>
                            <div class="flex flex-col gap-1.5">
                                <label class="text-sm font-medium text-gray-700">Fax <span class="text-gray-500 font-normal text-xs ml-1">(Optional)</span></label>
                                <input name="company_fax" value="{{ old('company_fax', $companySettings->company_fax ?? '') }}" class="form-input rounded-lg border-gray-300 bg-white text-gray-900 px-3 py-2.5 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-shadow" placeholder="+1 (555) 000-0000" type="tel"/>
                            </div>
                        </div>
                    </div>
                    <!-- Card 2: Media Uploads -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                        <div class="px-6 py-4 border-b border-gray-200 bg-gray-50/50">
                            <h2 class="text-lg font-bold text-gray-900">Company Media Uploads</h2>
                        </div>
                        <div class="p-6 bg-gray-50/30">
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                                <!-- Logo -->
                                <div class="flex flex-col gap-3">
                                    <div class="flex items-center justify-between">
                                        <label class="text-sm font-medium text-gray-700">Logo</label>
                                        <span class="text-xs text-gray-500">Rec: 250x100px</span>
                                    </div>
                                    <div id="logo-preview" class="w-full h-32 border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center bg-gray-50 relative overflow-hidden group hover:border-primary/50 transition-colors cursor-pointer" onclick="document.getElementById('logo-upload').click()">
                                        @if(($companySettings->company_logo ?? null) && \Illuminate\Support\Facades\Storage::disk('public')->exists($companySettings->company_logo))
                                            <img alt="Logo Preview" id="logo-preview-img" class="max-w-[80%] max-h-[80%] object-contain" src="{{ \Illuminate\Support\Facades\Storage::url($companySettings->company_logo) }}"/>
                                        @else
                                            <span class="material-symbols-outlined text-gray-400 text-4xl">image</span>
                                            <p class="text-xs text-gray-500 mt-2">Click to upload</p>
                                        @endif
                                        <div class="absolute inset-0 bg-white/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                            <span class="material-symbols-outlined text-primary">edit</span>
                                        </div>
                                    </div>
                                    <button type="button" onclick="document.getElementById('logo-upload').click()" class="text-sm font-medium text-primary hover:text-primary/80 transition-colors text-left flex items-center gap-1">
                                        <span class="material-symbols-outlined text-[18px]">upload</span> <span id="logo-text">{{ $companySettings->company_logo ?? null ? 'Change' : 'Upload' }} logo</span>
                                    </button>
                                    <input type="file" name="company_logo" accept="image/*" class="hidden" id="logo-upload" onchange="previewImage(this, 'logo-preview-img', 'logo-preview')">
                                </div>
                                <!-- Favicon -->
                                <div class="flex flex-col gap-3">
                                    <div class="flex items-center justify-between">
                                        <label class="text-sm font-medium text-gray-700">Favicon</label>
                                        <span class="text-xs text-gray-500">Rec: 32x32px</span>
                                    </div>
                                    <div id="favicon-preview" class="w-full h-32 border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center bg-gray-50 relative overflow-hidden group hover:border-primary/50 transition-colors cursor-pointer" onclick="document.getElementById('favicon-upload').click()">
                                        @if(($companySettings->company_favicon ?? null) && \Illuminate\Support\Facades\Storage::disk('public')->exists($companySettings->company_favicon))
                                            <img alt="Favicon Preview" id="favicon-preview-img" class="size-8 object-contain shadow-sm rounded-sm" src="{{ \Illuminate\Support\Facades\Storage::url($companySettings->company_favicon) }}"/>
                                        @else
                                            <span class="material-symbols-outlined text-gray-400 text-4xl">image</span>
                                            <p class="text-xs text-gray-500 mt-2">Click to upload</p>
                                        @endif
                                        <div class="absolute inset-0 bg-white/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                            <span class="material-symbols-outlined text-primary">edit</span>
                                        </div>
                                    </div>
                                    <button type="button" onclick="document.getElementById('favicon-upload').click()" class="text-sm font-medium text-primary hover:text-primary/80 transition-colors text-left flex items-center gap-1">
                                        <span class="material-symbols-outlined text-[18px]">upload</span> <span id="favicon-text">{{ $companySettings->company_favicon ?? null ? 'Change' : 'Upload' }} favicon</span>
                                    </button>
                                    <input type="file" name="company_favicon" accept="image/*" class="hidden" id="favicon-upload" onchange="previewImage(this, 'favicon-preview-img', 'favicon-preview')">
                                </div>
                                <!-- Icon -->
                                <div class="flex flex-col gap-3">
                                    <div class="flex items-center justify-between">
                                        <label class="text-sm font-medium text-gray-700">Company Icon</label>
                                        <span class="text-xs text-gray-500">Rec: 100x100px</span>
                                    </div>
                                    <div id="icon-preview" class="w-full h-32 border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center bg-gray-50 relative overflow-hidden group cursor-pointer hover:border-primary/50 transition-colors" onclick="document.getElementById('icon-upload').click()">
                                        @if(($companySettings->company_icon ?? null) && \Illuminate\Support\Facades\Storage::disk('public')->exists($companySettings->company_icon))
                                            <img alt="Icon Preview" id="icon-preview-img" class="size-16 object-contain rounded-md shadow-sm" src="{{ \Illuminate\Support\Facades\Storage::url($companySettings->company_icon) }}"/>
                                        @else
                                            <span class="material-symbols-outlined text-gray-400 text-4xl">image</span>
                                            <p class="text-xs text-gray-500 mt-2">Click to upload</p>
                                        @endif
                                        <div class="absolute inset-0 bg-white/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                            <span class="material-symbols-outlined text-primary">edit</span>
                                        </div>
                                    </div>
                                    <button type="button" onclick="document.getElementById('icon-upload').click()" class="text-sm font-medium text-primary hover:text-primary/80 transition-colors text-left flex items-center gap-1">
                                        <span class="material-symbols-outlined text-[18px]">upload</span> <span id="icon-text">{{ $companySettings->company_icon ?? null ? 'Change' : 'Upload' }} icon</span>
                                    </button>
                                    <input type="file" name="company_icon" accept="image/*" class="hidden" id="icon-upload" onchange="previewImage(this, 'icon-preview-img', 'icon-preview')">
                                </div>
                                <!-- Collapsed Icon -->
                                <div class="flex flex-col gap-3">
                                    <div class="flex items-center justify-between">
                                        <label class="text-sm font-medium text-gray-700">Collapsed Sidebar Icon</label>
                                        <span class="text-xs text-gray-500">Rec: 64x64px</span>
                                    </div>
                                    <div id="collapsed-icon-preview" class="w-full h-32 border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center bg-gray-50 relative overflow-hidden group cursor-pointer hover:border-primary/50 transition-colors" onclick="document.getElementById('collapsed-icon-upload').click()">
                                        @if($companySettings->company_icon_collapsed ?? null)
                                            <img alt="Collapsed Icon Preview" id="collapsed-icon-preview-img" class="size-16 object-contain rounded-md shadow-sm" src="{{ Storage::disk('public')->exists($companySettings->company_icon_collapsed) ? Storage::url($companySettings->company_icon_collapsed) : asset('logo.svg') }}"/>
                                        @else
                                            <span class="material-symbols-outlined text-gray-400 text-4xl">image</span>
                                            <p class="text-xs text-gray-500 mt-2">Click to upload</p>
                                        @endif
                                        <div class="absolute inset-0 bg-white/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                            <span class="material-symbols-outlined text-primary">edit</span>
                                        </div>
                                    </div>
                                    <button type="button" onclick="document.getElementById('collapsed-icon-upload').click()" class="text-sm font-medium text-primary hover:text-primary/80 transition-colors text-left flex items-center gap-1">
                                        <span class="material-symbols-outlined text-[18px]">upload</span> <span id="collapsed-icon-text">{{ $companySettings->company_icon_collapsed ?? null ? 'Change' : 'Upload' }} collapsed icon</span>
                                    </button>
                                    <input type="file" name="company_icon_collapsed" accept="image/*" class="hidden" id="collapsed-icon-upload" onchange="previewImage(this, 'collapsed-icon-preview-img', 'collapsed-icon-preview')">
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Card 3: Address Information -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                        <div class="px-6 py-4 border-b border-gray-200 bg-gray-50/50">
                            <h2 class="text-lg font-bold text-gray-900">Address Information</h2>
                        </div>
                        <div class="p-6 grid grid-cols-1 md:grid-cols-3 gap-6 bg-gray-50/30">
                            <div class="col-span-1 md:col-span-3 flex flex-col gap-1.5">
                                <label class="text-sm font-medium text-gray-700">Address <span class="text-red-500">*</span></label>
                                <textarea name="company_address" required class="form-textarea rounded-lg border-gray-300 bg-white text-gray-900 px-3 py-2.5 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-shadow resize-none" rows="3">{{ old('company_address', $companySettings->company_address ?? '') }}</textarea>
                            </div>
                            <div class="flex flex-col gap-1.5">
                                <label class="text-sm font-medium text-gray-700">Country <span class="text-red-500">*</span></label>
                                <div class="relative">
                                    <select name="company_country" id="company_country" required class="form-select w-full rounded-lg border-gray-300 bg-white text-gray-900 px-3 py-2.5 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-shadow">
                                        <option value="">Select Country</option>
                                        <option value="US" {{ old('company_country', $companySettings->company_country ?? '') === 'US' ? 'selected' : '' }}>United States</option>
                                        <option value="CA" {{ old('company_country', $companySettings->company_country ?? '') === 'CA' ? 'selected' : '' }}>Canada</option>
                                        <option value="GB" {{ old('company_country', $companySettings->company_country ?? '') === 'GB' ? 'selected' : '' }}>United Kingdom</option>
                                        <option value="AU" {{ old('company_country', $companySettings->company_country ?? '') === 'AU' ? 'selected' : '' }}>Australia</option>
                                        <option value="DE" {{ old('company_country', $companySettings->company_country ?? '') === 'DE' ? 'selected' : '' }}>Germany</option>
                                        <option value="FR" {{ old('company_country', $companySettings->company_country ?? '') === 'FR' ? 'selected' : '' }}>France</option>
                                        <option value="IT" {{ old('company_country', $companySettings->company_country ?? '') === 'IT' ? 'selected' : '' }}>Italy</option>
                                        <option value="ES" {{ old('company_country', $companySettings->company_country ?? '') === 'ES' ? 'selected' : '' }}>Spain</option>
                                        <option value="NL" {{ old('company_country', $companySettings->company_country ?? '') === 'NL' ? 'selected' : '' }}>Netherlands</option>
                                        <option value="BE" {{ old('company_country', $companySettings->company_country ?? '') === 'BE' ? 'selected' : '' }}>Belgium</option>
                                        <option value="CH" {{ old('company_country', $companySettings->company_country ?? '') === 'CH' ? 'selected' : '' }}>Switzerland</option>
                                        <option value="AT" {{ old('company_country', $companySettings->company_country ?? '') === 'AT' ? 'selected' : '' }}>Austria</option>
                                        <option value="SE" {{ old('company_country', $companySettings->company_country ?? '') === 'SE' ? 'selected' : '' }}>Sweden</option>
                                        <option value="NO" {{ old('company_country', $companySettings->company_country ?? '') === 'NO' ? 'selected' : '' }}>Norway</option>
                                        <option value="DK" {{ old('company_country', $companySettings->company_country ?? '') === 'DK' ? 'selected' : '' }}>Denmark</option>
                                        <option value="FI" {{ old('company_country', $companySettings->company_country ?? '') === 'FI' ? 'selected' : '' }}>Finland</option>
                                        <option value="PL" {{ old('company_country', $companySettings->company_country ?? '') === 'PL' ? 'selected' : '' }}>Poland</option>
                                        <option value="CZ" {{ old('company_country', $companySettings->company_country ?? '') === 'CZ' ? 'selected' : '' }}>Czech Republic</option>
                                        <option value="IE" {{ old('company_country', $companySettings->company_country ?? '') === 'IE' ? 'selected' : '' }}>Ireland</option>
                                        <option value="PT" {{ old('company_country', $companySettings->company_country ?? '') === 'PT' ? 'selected' : '' }}>Portugal</option>
                                        <option value="GR" {{ old('company_country', $companySettings->company_country ?? '') === 'GR' ? 'selected' : '' }}>Greece</option>
                                        <option value="JP" {{ old('company_country', $companySettings->company_country ?? '') === 'JP' ? 'selected' : '' }}>Japan</option>
                                        <option value="CN" {{ old('company_country', $companySettings->company_country ?? '') === 'CN' ? 'selected' : '' }}>China</option>
                                        <option value="IN" {{ old('company_country', $companySettings->company_country ?? '') === 'IN' ? 'selected' : '' }}>India</option>
                                        <option value="KR" {{ old('company_country', $companySettings->company_country ?? '') === 'KR' ? 'selected' : '' }}>South Korea</option>
                                        <option value="SG" {{ old('company_country', $companySettings->company_country ?? '') === 'SG' ? 'selected' : '' }}>Singapore</option>
                                        <option value="MY" {{ old('company_country', $companySettings->company_country ?? '') === 'MY' ? 'selected' : '' }}>Malaysia</option>
                                        <option value="TH" {{ old('company_country', $companySettings->company_country ?? '') === 'TH' ? 'selected' : '' }}>Thailand</option>
                                        <option value="ID" {{ old('company_country', $companySettings->company_country ?? '') === 'ID' ? 'selected' : '' }}>Indonesia</option>
                                        <option value="PH" {{ old('company_country', $companySettings->company_country ?? '') === 'PH' ? 'selected' : '' }}>Philippines</option>
                                        <option value="VN" {{ old('company_country', $companySettings->company_country ?? '') === 'VN' ? 'selected' : '' }}>Vietnam</option>
                                        <option value="NZ" {{ old('company_country', $companySettings->company_country ?? '') === 'NZ' ? 'selected' : '' }}>New Zealand</option>
                                        <option value="ZA" {{ old('company_country', $companySettings->company_country ?? '') === 'ZA' ? 'selected' : '' }}>South Africa</option>
                                        <option value="AE" {{ old('company_country', $companySettings->company_country ?? '') === 'AE' ? 'selected' : '' }}>United Arab Emirates</option>
                                        <option value="SA" {{ old('company_country', $companySettings->company_country ?? '') === 'SA' ? 'selected' : '' }}>Saudi Arabia</option>
                                        <option value="IL" {{ old('company_country', $companySettings->company_country ?? '') === 'IL' ? 'selected' : '' }}>Israel</option>
                                        <option value="TR" {{ old('company_country', $companySettings->company_country ?? '') === 'TR' ? 'selected' : '' }}>Turkey</option>
                                        <option value="BR" {{ old('company_country', $companySettings->company_country ?? '') === 'BR' ? 'selected' : '' }}>Brazil</option>
                                        <option value="MX" {{ old('company_country', $companySettings->company_country ?? '') === 'MX' ? 'selected' : '' }}>Mexico</option>
                                        <option value="AR" {{ old('company_country', $companySettings->company_country ?? '') === 'AR' ? 'selected' : '' }}>Argentina</option>
                                        <option value="CL" {{ old('company_country', $companySettings->company_country ?? '') === 'CL' ? 'selected' : '' }}>Chile</option>
                                        <option value="CO" {{ old('company_country', $companySettings->company_country ?? '') === 'CO' ? 'selected' : '' }}>Colombia</option>
                                        <option value="PE" {{ old('company_country', $companySettings->company_country ?? '') === 'PE' ? 'selected' : '' }}>Peru</option>
                                        <option value="RU" {{ old('company_country', $companySettings->company_country ?? '') === 'RU' ? 'selected' : '' }}>Russia</option>
                                        <option value="EG" {{ old('company_country', $companySettings->company_country ?? '') === 'EG' ? 'selected' : '' }}>Egypt</option>
                                        <option value="NG" {{ old('company_country', $companySettings->company_country ?? '') === 'NG' ? 'selected' : '' }}>Nigeria</option>
                                        <option value="KE" {{ old('company_country', $companySettings->company_country ?? '') === 'KE' ? 'selected' : '' }}>Kenya</option>
                                    </select>
                                </div>
                            </div>
                            <div class="flex flex-col gap-1.5">
                                <label class="text-sm font-medium text-gray-700">State / Province <span class="text-red-500">*</span></label>
                                <input name="company_state" value="{{ old('company_state', $companySettings->company_state ?? '') }}" required class="form-input rounded-lg border-gray-300 bg-white text-gray-900 px-3 py-2.5 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-shadow" placeholder="Enter state or province" type="text"/>
                            </div>
                            <div class="flex flex-col gap-1.5">
                                <label class="text-sm font-medium text-gray-700">City <span class="text-red-500">*</span></label>
                                <input name="company_city" value="{{ old('company_city', $companySettings->company_city ?? '') }}" required class="form-input rounded-lg border-gray-300 bg-white text-gray-900 px-3 py-2.5 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-shadow" placeholder="Enter city" type="text"/>
                            </div>
                            <div class="flex flex-col gap-1.5">
                                <label class="text-sm font-medium text-gray-700">Postal Code <span class="text-red-500">*</span></label>
                                <input name="company_zip" value="{{ old('company_zip', $companySettings->company_zip ?? '') }}" required class="form-input rounded-lg border-gray-300 bg-white text-gray-900 px-3 py-2.5 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-shadow" type="text"/>
                            </div>
                        </div>
                    </div>
                    <!-- Sticky Footer Action Bar -->
                    <div class="sticky bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-6 py-4 flex items-center justify-end gap-3 z-30 shadow-lg -mx-6 -mb-6">
                        <button type="button" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 transition-colors">
                            Cancel
                        </button>
                        <button type="submit" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 shadow-sm transition-colors flex items-center gap-2">
                            <span class="material-symbols-outlined text-[18px]">save</span> Save Changes
                        </button>
                    </div>
                </form>
            @elseif(($tab ?? 'company') === 'localization')
                <!-- Localization Settings Tab -->
                <form method="POST" action="{{ route('admin.settings.localization.update') }}" class="flex flex-col gap-6">
                    @csrf
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                        <div class="px-6 py-4 border-b border-gray-200 bg-gray-50/50">
                            <h2 class="text-lg font-semibold text-gray-900">Basic Information</h2>
                        </div>
                        <div class="p-6 md:p-8 bg-gray-50/30">
                            <div class="grid grid-cols-1 gap-x-8 gap-y-6 md:grid-cols-2">
                                <div class="md:col-span-2">
                                    <label class="block text-sm font-medium leading-6 text-gray-900" for="timezone">
                                        Time Zone <span class="text-red-500">*</span>
                                    </label>
                                    <div class="relative mt-2">
                                        <div class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                                            <span class="material-symbols-outlined text-gray-400 text-[20px]">schedule</span>
                                        </div>
                                        <select name="timezone" id="timezone" class="block w-full rounded-lg border border-gray-300 py-2.5 pl-10 pr-10 text-gray-900 bg-white placeholder:text-gray-400 focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm sm:leading-6">
                                            <option value="Pacific/Midway" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Pacific/Midway' ? 'selected' : '' }}>(UTC-11:00) Midway Island, Samoa</option>
                                            <option value="America/Adak" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Adak' ? 'selected' : '' }}>(UTC-10:00) Hawaii-Aleutian</option>
                                            <option value="Pacific/Honolulu" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Pacific/Honolulu' ? 'selected' : '' }}>(UTC-10:00) Hawaii</option>
                                            <option value="America/Anchorage" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Anchorage' ? 'selected' : '' }}>(UTC-09:00) Alaska</option>
                                            <option value="America/Los_Angeles" {{ old('timezone', $localizationSettings->timezone ?? 'America/Los_Angeles') === 'America/Los_Angeles' ? 'selected' : '' }}>(UTC-08:00) Pacific Time (US & Canada)</option>
                                            <option value="America/Tijuana" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Tijuana' ? 'selected' : '' }}>(UTC-08:00) Tijuana, Baja California</option>
                                            <option value="America/Denver" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Denver' ? 'selected' : '' }}>(UTC-07:00) Mountain Time (US & Canada)</option>
                                            <option value="America/Phoenix" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Phoenix' ? 'selected' : '' }}>(UTC-07:00) Arizona</option>
                                            <option value="America/Chicago" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Chicago' ? 'selected' : '' }}>(UTC-06:00) Central Time (US & Canada)</option>
                                            <option value="America/Mexico_City" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Mexico_City' ? 'selected' : '' }}>(UTC-06:00) Mexico City</option>
                                            <option value="America/New_York" {{ old('timezone', $localizationSettings->timezone ?? 'America/New_York') === 'America/New_York' ? 'selected' : '' }}>(UTC-05:00) Eastern Time (US & Canada)</option>
                                            <option value="America/Toronto" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Toronto' ? 'selected' : '' }}>(UTC-05:00) Toronto</option>
                                            <option value="America/Caracas" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Caracas' ? 'selected' : '' }}>(UTC-04:00) Caracas</option>
                                            <option value="America/Sao_Paulo" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Sao_Paulo' ? 'selected' : '' }}>(UTC-03:00) Brasilia</option>
                                            <option value="America/Argentina/Buenos_Aires" {{ old('timezone', $localizationSettings->timezone ?? '') === 'America/Argentina/Buenos_Aires' ? 'selected' : '' }}>(UTC-03:00) Buenos Aires</option>
                                            <option value="Atlantic/South_Georgia" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Atlantic/South_Georgia' ? 'selected' : '' }}>(UTC-02:00) Mid-Atlantic</option>
                                            <option value="Atlantic/Azores" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Atlantic/Azores' ? 'selected' : '' }}>(UTC-01:00) Azores</option>
                                            <option value="Europe/London" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Europe/London' ? 'selected' : '' }}>(UTC+00:00) London, Dublin, Lisbon</option>
                                            <option value="Africa/Casablanca" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Africa/Casablanca' ? 'selected' : '' }}>(UTC+00:00) Casablanca</option>
                                            <option value="Europe/Paris" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Europe/Paris' ? 'selected' : '' }}>(UTC+01:00) Paris, Amsterdam, Berlin, Rome</option>
                                            <option value="Europe/Berlin" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Europe/Berlin' ? 'selected' : '' }}>(UTC+01:00) Berlin</option>
                                            <option value="Europe/Rome" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Europe/Rome' ? 'selected' : '' }}>(UTC+01:00) Rome</option>
                                            <option value="Africa/Lagos" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Africa/Lagos' ? 'selected' : '' }}>(UTC+01:00) Lagos</option>
                                            <option value="Europe/Athens" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Europe/Athens' ? 'selected' : '' }}>(UTC+02:00) Athens, Cairo</option>
                                            <option value="Africa/Johannesburg" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Africa/Johannesburg' ? 'selected' : '' }}>(UTC+02:00) Johannesburg</option>
                                            <option value="Europe/Moscow" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Europe/Moscow' ? 'selected' : '' }}>(UTC+03:00) Moscow, Istanbul</option>
                                            <option value="Asia/Dubai" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Asia/Dubai' ? 'selected' : '' }}>(UTC+04:00) Dubai, Abu Dhabi</option>
                                            <option value="Asia/Karachi" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Asia/Karachi' ? 'selected' : '' }}>(UTC+05:00) Karachi, Islamabad</option>
                                            <option value="Asia/Dhaka" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Asia/Dhaka' ? 'selected' : '' }}>(UTC+06:00) Dhaka</option>
                                            <option value="Asia/Bangkok" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Asia/Bangkok' ? 'selected' : '' }}>(UTC+07:00) Bangkok, Jakarta</option>
                                            <option value="Asia/Singapore" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Asia/Singapore' ? 'selected' : '' }}>(UTC+08:00) Singapore, Kuala Lumpur</option>
                                            <option value="Asia/Hong_Kong" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Asia/Hong_Kong' ? 'selected' : '' }}>(UTC+08:00) Hong Kong</option>
                                            <option value="Asia/Shanghai" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Asia/Shanghai' ? 'selected' : '' }}>(UTC+08:00) Beijing, Shanghai</option>
                                            <option value="Asia/Tokyo" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Asia/Tokyo' ? 'selected' : '' }}>(UTC+09:00) Tokyo, Seoul</option>
                                            <option value="Australia/Adelaide" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Australia/Adelaide' ? 'selected' : '' }}>(UTC+09:30) Adelaide</option>
                                            <option value="Australia/Sydney" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Australia/Sydney' ? 'selected' : '' }}>(UTC+10:00) Sydney, Melbourne</option>
                                            <option value="Pacific/Auckland" {{ old('timezone', $localizationSettings->timezone ?? '') === 'Pacific/Auckland' ? 'selected' : '' }}>(UTC+12:00) Auckland, Wellington</option>
                                        </select>
                                    </div>
                                    <p class="mt-2 text-xs text-gray-500">Used to calculate dates for reports and analytics.</p>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium leading-6 text-gray-900" for="start-week">Start Week On</label>
                                    <div class="mt-2">
                                        <select name="start_week" id="start-week" class="block w-full rounded-lg border border-gray-300 py-2.5 text-gray-900 bg-white focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm sm:leading-6">
                                            <option value="sunday" {{ old('start_week', $localizationSettings->start_week ?? 'monday') === 'sunday' ? 'selected' : '' }}>Sunday</option>
                                            <option value="monday" {{ old('start_week', $localizationSettings->start_week ?? 'monday') === 'monday' ? 'selected' : '' }}>Monday</option>
                                            <option value="saturday" {{ old('start_week', $localizationSettings->start_week ?? 'monday') === 'saturday' ? 'selected' : '' }}>Saturday</option>
                                        </select>
                                    </div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium leading-6 text-gray-900" for="currency">Default Currency</label>
                                    <div class="mt-2">
                                        <select name="default_currency" id="currency" class="block w-full rounded-lg border border-gray-300 py-2.5 text-gray-900 bg-white focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm sm:leading-6" style="font-size: 14px;">
                                            @php
                                                $selectedDefaultCurrency = old('default_currency', $localizationSettings->default_currency ?? \App\Models\Currency::getDefaultCode());
                                            @endphp
                                            @foreach(($currencies ?? []) as $currency)
                                                <option value="{{ $currency->code }}" {{ $selectedDefaultCurrency === $currency->code ? 'selected' : '' }}>
                                                    {{ $currency->code }} ({{ $currency->symbol }}) - {{ $currency->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium leading-6 text-gray-900" for="date-format">Date Format</label>
                                    <div class="mt-2">
                                        <select name="date_format" id="date-format" class="block w-full rounded-lg border border-gray-300 py-2.5 text-gray-900 bg-white focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm sm:leading-6">
                                            <option selected>MM/DD/YYYY (12/31/2023)</option>
                                            <option>DD/MM/YYYY (31/12/2023)</option>
                                            <option>YYYY-MM-DD (2023-12-31)</option>
                                            <option>MMM D, YYYY (Dec 31, 2023)</option>
                                        </select>
                                    </div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium leading-6 text-gray-900" for="time-format">Time Format</label>
                                    <div class="mt-2">
                                        <select name="time_format" id="time-format" class="block w-full rounded-lg border border-gray-300 py-2.5 text-gray-900 bg-white focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm sm:leading-6">
                                            <option value="12" {{ old('time_format', $localizationSettings->time_format ?? '12') === '12' ? 'selected' : '' }}>12 Hour (1:00 PM)</option>
                                            <option value="24" {{ old('time_format', $localizationSettings->time_format ?? '12') === '24' ? 'selected' : '' }}>24 Hour (13:00)</option>
                                        </select>
                                    </div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium leading-6 text-gray-900" for="datetime-display-format">Date & Time Display Format</label>
                                    <div class="mt-2">
                                        <select name="datetime_display_format" id="datetime-display-format" class="block w-full rounded-lg border border-gray-300 py-2.5 text-gray-900 bg-white focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm sm:leading-6">
                                            <option selected>Full Date & Time (Dec 31, 2023 1:00 PM)</option>
                                            <option>Short Date & Time (12/31/2023 13:00)</option>
                                            <option>Date Only (Dec 31, 2023)</option>
                                            <option>Time Only (1:00 PM)</option>
                                        </select>
                                    </div>
                                    <p class="mt-2 text-xs text-gray-500">Choose how dates and times are displayed throughout the application.</p>
                                </div>
                            </div>
                        </div>
                        <div class="flex items-center justify-end gap-3 rounded-b-xl border-t border-gray-200 bg-gray-50 px-6 py-4">
                            <button type="button" class="rounded-lg px-4 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 hover:text-gray-900 transition-colors">Cancel</button>
                            <button type="submit" class="inline-flex items-center justify-center rounded-lg bg-primary px-5 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary transition-colors">Save Changes</button>
                        </div>
                    </div>
                    <div class="rounded-lg bg-blue-50 p-4 border border-blue-100">
                        <div class="flex gap-3">
                            <span class="material-symbols-outlined text-blue-600">info</span>
                            <div>
                                <h3 class="text-sm font-medium text-blue-900">Language Preferences</h3>
                                <p class="mt-1 text-sm text-blue-700">Changing the language settings for the entire organization requires administrator approval. Please contact support to change the base language.</p>
                            </div>
                        </div>
                    </div>
                </form>
            @elseif(($tab ?? 'company') === 'signatures')
                <!-- Signatures Tab -->
                <div class="space-y-6">
                    <!-- Action Bar -->
                    <div class="flex flex-col sm:flex-row justify-between gap-4">
                        <!-- Search -->
                        <div class="relative w-full max-w-md">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <span class="material-symbols-outlined text-slate-400">search</span>
                            </div>
                            <input id="signature-search" class="block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg bg-white text-gray-900 shadow-sm placeholder:text-gray-400 focus:ring-2 focus:ring-primary/20 focus:border-primary sm:text-sm sm:leading-6" placeholder="Search signatures..." type="text" onkeyup="searchSignatures(this.value)"/>
                        </div>
                        <!-- Add Button -->
                        <button onclick="document.getElementById('add-signature-modal').classList.remove('hidden')" class="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-primary/90 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary transition-all">
                            <span class="material-symbols-outlined" style="font-size: 20px;">add</span>
                            New Signature
                        </button>
                        <select id="signature-per-page" class="px-3 py-2 text-sm border border-gray-300 rounded-lg bg-white text-gray-700 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" onchange="loadSignatures()">
                            <option value="10" {{ request('per_page', 10) == 10 ? 'selected' : '' }}>10 / page</option>
                            <option value="25" {{ request('per_page', 10) == 25 ? 'selected' : '' }}>25 / page</option>
                            <option value="50" {{ request('per_page', 10) == 50 ? 'selected' : '' }}>50 / page</option>
                            <option value="100" {{ request('per_page', 10) == 100 ? 'selected' : '' }}>100 / page</option>
                        </select>
                    </div>
                    
                    <!-- Table Card -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                        <div class="overflow-x-auto">
                            <table class="w-full text-left border-collapse">
                                <thead>
                                    <tr class="bg-gray-50 border-b border-gray-200">
                                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-600">#</th>
                                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-600">SIGNATURE NAME</th>
                                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-600">SIGNATURE</th>
                                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-600">STATUS</th>
                                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-600">DEFAULT</th>
                                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-600 text-right">ACTIONS</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-200 bg-white">
                                    @forelse($signatures ?? [] as $index => $signature)
                                        @php
                                            $sigContent = $signature->content ?? null;
                                            $sigIsStoredFile = $sigContent && \Illuminate\Support\Facades\Storage::disk('public')->exists($sigContent);
                                        @endphp
                                        <tr class="group hover:bg-gray-50 transition-colors">
                                            <td class="py-4 px-6 whitespace-nowrap text-sm text-gray-700">{{ $index + 1 }}</td>
                                            <td class="py-4 px-6 whitespace-nowrap">
                                                <a href="#" class="text-sm font-medium text-primary hover:underline">{{ $signature->name ?? 'Signature Name' }}</a>
                                            </td>
                                            <td class="py-4 px-6 whitespace-nowrap">
                                                <div class="h-12 w-20 bg-white border border-gray-200 rounded p-1 flex items-center justify-center overflow-hidden">
                                                    @if($sigIsStoredFile)
                                                        <img alt="Signature Preview" class="max-h-full max-w-full object-contain" src="{{ \Illuminate\Support\Facades\Storage::url($sigContent) }}"/>
                                                    @elseif(($signature->type ?? '') === 'text' && $sigContent)
                                                        <span class="text-[10px] leading-tight text-gray-600 font-medium text-center line-clamp-3 break-words px-0.5" title="{{ e($sigContent) }}">{{ \Illuminate\Support\Str::limit($sigContent, 22) }}</span>
                                                    @else
                                                        <span class="text-xs text-gray-400">No Preview</span>
                                                    @endif
                                                </div>
                                            </td>
                                            <td class="py-4 px-6 whitespace-nowrap">
                                                <form method="POST" action="{{ route('admin.settings.signatures.update-status', $signature) }}" class="inline">
                                                    @csrf
                                                    @method('PATCH')
                                                    <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                                        <input type="checkbox" name="is_active" value="1" {{ ($signature->is_active ?? true) ? 'checked' : '' }} onchange="this.form.submit()" class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                                                        <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300 {{ ($signature->is_active ?? true) ? 'bg-primary' : '' }}"></span>
                                                    </label>
                                                </form>
                                            </td>
                                            <td class="py-4 px-6 whitespace-nowrap text-center">
                                                <form method="POST" action="{{ route('admin.settings.signatures.update-status', $signature) }}" class="inline">
                                                    @csrf
                                                    @method('PATCH')
                                                    <label class="cursor-pointer">
                                                        @if($signature->is_default ?? false)
                                                            <input type="hidden" name="is_default" value="1">
                                                            <span class="material-symbols-outlined text-primary" style="font-size: 20px;">check_circle</span>
                                                        @else
                                                            <input type="checkbox" name="is_default" value="1" onchange="this.form.submit()" class="sr-only">
                                                            <div class="size-5 mx-auto rounded-full border-2 border-gray-300 hover:border-primary transition-colors"></div>
                                                        @endif
                                                    </label>
                                                </form>
                                            </td>
                                            <td class="py-4 px-6 whitespace-nowrap text-right">
                                                <div class="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                                    <button type="button" onclick="openEditSignatureModal({{ $signature->id }}, {{ json_encode($signature->name) }}, {{ json_encode($sigIsStoredFile ? \Illuminate\Support\Facades\Storage::url($sigContent) : '') }}, {{ $signature->is_active ? 'true' : 'false' }}, {{ $signature->is_default ? 'true' : 'false' }})" class="p-1.5 text-gray-400 hover:text-primary rounded-md hover:bg-primary/5 transition-colors">
                                                        <span class="material-symbols-outlined" style="font-size: 20px;">edit</span>
                                                    </button>
                                                    <button type="button" onclick="openDeleteSignatureModal({{ $signature->id }}, '{{ addslashes($signature->name) }}')" class="p-1.5 text-gray-400 hover:text-red-500 rounded-md hover:bg-red-50 transition-colors" title="Delete signature">
                                                        <span class="material-symbols-outlined" style="font-size: 20px;">delete</span>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="6" class="py-12 px-6 text-center text-gray-500">
                                                <span class="material-symbols-outlined text-4xl mb-2 block">ink_pen</span>
                                                <p>No signatures found</p>
                                            </td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                        <!-- Pagination -->
                        <div class="bg-white px-6 py-4 border-t border-gray-200 flex items-center justify-between">
                            <p class="text-sm text-gray-600">
                                @if($signatures && $signatures->count() > 0)
                                    Showing <span class="font-medium">{{ ($signatures->currentPage() - 1) * $signatures->perPage() + 1 }}</span> to <span class="font-medium">{{ min($signatures->currentPage() * $signatures->perPage(), $signatures->total()) }}</span> of <span class="font-medium">{{ $signatures->total() }}</span> entries
                                @else
                                    Showing <span class="font-medium">0</span> to <span class="font-medium">0</span> of <span class="font-medium">0</span> entries
                                @endif
                            </p>
                            <nav class="flex gap-2">
                                @if($signatures && $signatures->hasPages())
                                    @if($signatures->onFirstPage())
                                        <button class="relative inline-flex items-center rounded-md px-3 py-2 text-sm font-semibold text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 disabled:opacity-50" disabled>Previous</button>
                                    @else
                                        <a href="{{ $signatures->previousPageUrl() }}" class="relative inline-flex items-center rounded-md px-3 py-2 text-sm font-semibold text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50">Previous</a>
                                    @endif
                                    
                                    @foreach($signatures->getUrlRange(1, min(5, $signatures->lastPage())) as $page => $url)
                                        @if($page == $signatures->currentPage())
                                            <button class="relative inline-flex items-center rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary">{{ $page }}</button>
                                        @else
                                            <a href="{{ $url }}" class="relative inline-flex items-center rounded-md px-3 py-2 text-sm font-semibold text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50">{{ $page }}</a>
                                        @endif
                                    @endforeach
                                    
                                    @if($signatures->hasMorePages())
                                        <a href="{{ $signatures->nextPageUrl() }}" class="relative inline-flex items-center rounded-md px-3 py-2 text-sm font-semibold text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50">Next</a>
                                    @else
                                        <button class="relative inline-flex items-center rounded-md px-3 py-2 text-sm font-semibold text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 disabled:opacity-50" disabled>Next</button>
                                    @endif
                                @else
                                    <button class="relative inline-flex items-center rounded-md px-3 py-2 text-sm font-semibold text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 disabled:opacity-50" disabled>Previous</button>
                                    <button class="relative inline-flex items-center rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary">1</button>
                                    <button class="relative inline-flex items-center rounded-md px-3 py-2 text-sm font-semibold text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 disabled:opacity-50" disabled>Next</button>
                                @endif
                            </nav>
                        </div>
                    </div>
                </div>

                <!-- Add Signature Modal -->
                <div id="add-signature-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
                    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
                        <div class="fixed inset-0 transition-opacity bg-gray-900/40 backdrop-blur-sm" onclick="document.getElementById('add-signature-modal').classList.add('hidden')"></div>
                        <div class="fixed inset-y-0 right-0 z-40 w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300 ease-in-out flex flex-col h-full border-l border-gray-200">
                            <!-- Drawer Header -->
                            <div class="px-6 py-5 border-b border-gray-200 bg-gray-50/50 flex items-center justify-between">
                                <h2 class="text-lg font-bold text-gray-900">Add New Signature</h2>
                                <button onclick="document.getElementById('add-signature-modal').classList.add('hidden')" class="text-gray-400 hover:text-gray-600 transition-colors">
                                    <span class="material-symbols-outlined">close</span>
                                </button>
                            </div>
                            <!-- Drawer Content -->
                            <form method="POST" action="{{ route('admin.settings.signatures.store') }}" enctype="multipart/form-data" class="flex-1 overflow-y-auto p-6 space-y-6 bg-white">
                                @csrf
                                <!-- File Upload -->
                                <div class="space-y-2">
                                    <label class="block text-sm font-medium text-gray-900">Signature Image <span class="text-red-500">*</span></label>
                                    <div id="signature-upload-preview" class="mt-2 flex justify-center rounded-lg border border-dashed border-gray-300 px-6 py-10 hover:bg-gray-50 transition-colors cursor-pointer group">
                                        <div class="text-center">
                                            <span class="material-symbols-outlined mx-auto h-12 w-12 text-gray-300 group-hover:text-primary transition-colors" style="font-size: 48px;">cloud_upload</span>
                                            <div class="mt-4 flex text-sm leading-6 text-gray-600 justify-center">
                                                <label class="relative cursor-pointer rounded-md bg-transparent font-semibold text-primary focus-within:outline-none focus-within:ring-2 focus-within:ring-primary focus-within:ring-offset-2 hover:text-primary/80" for="file-upload">
                                                    <span>Upload a file</span>
                                                    <input class="sr-only" id="file-upload" name="signature_image" type="file" accept="image/png,image/jpeg,image/jpg" onchange="previewSignatureUpload(this)"/>
                                                </label>
                                                <p class="pl-1">or drag and drop</p>
                                            </div>
                                            <p class="text-xs leading-5 text-gray-500">PNG, JPG up to 5MB</p>
                                        </div>
                                    </div>
                                    <div id="signature-preview-container" class="hidden mt-4">
                                        <img id="signature-preview-img" src="" alt="Signature Preview" class="max-w-full max-h-32 mx-auto border border-gray-300 rounded"/>
                                    </div>
                                </div>
                                <!-- Name Input -->
                                <div class="space-y-2">
                                    <label class="block text-sm font-medium text-gray-900" for="sig-name">Signature Name <span class="text-red-500">*</span></label>
                                    <input name="name" id="sig-name" required class="block w-full rounded-md border border-gray-300 py-2.5 text-gray-900 shadow-sm placeholder:text-gray-400 focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white sm:text-sm sm:leading-6" placeholder="e.g. John Doe Official" type="text"/>
                                </div>
                                <!-- Toggles -->
                                <div class="space-y-4 pt-4 border-t border-gray-200">
                                    <div class="flex items-center justify-between">
                                        <div class="flex flex-col">
                                            <span class="text-sm font-medium text-gray-900">Active Status</span>
                                            <span class="text-xs text-gray-500">Enable this signature for use</span>
                                        </div>
                                        <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                            <input name="is_active" type="checkbox" checked class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                                            <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300 bg-primary"></span>
                                        </label>
                                    </div>
                                    <div class="flex items-center justify-between">
                                        <div class="flex flex-col">
                                            <span class="text-sm font-medium text-gray-900">Set as Default</span>
                                            <span class="text-xs text-gray-500">Use automatically on new invoices</span>
                                        </div>
                                        <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                            <input name="is_default" type="checkbox" class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                                            <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300"></span>
                                        </label>
                                    </div>
                                </div>
                                <!-- Drawer Footer -->
                                <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex items-center justify-end gap-3 -mx-6 -mb-6 sticky bottom-0">
                                    <button type="button" onclick="document.getElementById('add-signature-modal').classList.add('hidden')" class="px-4 py-2 text-sm font-semibold text-gray-700 hover:text-gray-900 transition-colors">
                                        Cancel
                                    </button>
                                    <button type="submit" class="px-4 py-2 bg-primary hover:bg-primary/90 text-white text-sm font-semibold rounded-lg shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary transition-all">
                                        Save Changes
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Edit Signature Modal -->
                <div id="edit-signature-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
                    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
                        <div class="fixed inset-0 transition-opacity bg-gray-900/40 backdrop-blur-sm" onclick="document.getElementById('edit-signature-modal').classList.add('hidden')"></div>
                        <div class="fixed inset-y-0 right-0 z-40 w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300 ease-in-out flex flex-col h-full border-l border-gray-200">
                            <!-- Drawer Header -->
                            <div class="px-6 py-5 border-b border-gray-200 bg-gray-50/50 flex items-center justify-between">
                                <h2 class="text-lg font-bold text-gray-900">Edit Signature</h2>
                                <button onclick="document.getElementById('edit-signature-modal').classList.add('hidden')" class="text-gray-400 hover:text-gray-600 transition-colors">
                                    <span class="material-symbols-outlined">close</span>
                                </button>
                            </div>
                            <!-- Drawer Content -->
                            <form id="edit-signature-form" method="POST" enctype="multipart/form-data" class="flex-1 overflow-y-auto p-6 space-y-6 bg-white">
                                @csrf
                                @method('PUT')
                                <!-- File Upload -->
                                <div class="space-y-2">
                                    <label class="block text-sm font-medium text-gray-900">Signature Image</label>
                                    <div id="edit-signature-upload-preview" class="mt-2 flex justify-center rounded-lg border border-dashed border-gray-300 px-6 py-10 hover:bg-gray-50 transition-colors cursor-pointer group" onclick="document.getElementById('edit-file-upload').click()">
                                        <div class="text-center">
                                            <span class="material-symbols-outlined mx-auto h-12 w-12 text-gray-300 group-hover:text-primary transition-colors" style="font-size: 48px;">cloud_upload</span>
                                            <div class="mt-4 flex text-sm leading-6 text-gray-600 justify-center">
                                                <label class="relative cursor-pointer rounded-md bg-transparent font-semibold text-primary focus-within:outline-none focus-within:ring-2 focus-within:ring-primary focus-within:ring-offset-2 hover:text-primary/80" for="edit-file-upload">
                                                    <span>Upload a file</span>
                                                    <input class="sr-only" id="edit-file-upload" name="signature_image" type="file" accept="image/png,image/jpeg,image/jpg" onchange="previewEditSignatureUpload(this)"/>
                                                </label>
                                                <p class="pl-1">or drag and drop</p>
                                            </div>
                                            <p class="text-xs leading-5 text-gray-500">PNG, JPG up to 5MB</p>
                                        </div>
                                    </div>
                                    <div id="edit-signature-preview-container" class="mt-4 relative">
                                        <img id="edit-signature-preview-img" src="" alt="Signature Preview" class="max-w-full max-h-32 mx-auto border border-gray-300 rounded"/>
                                        <button type="button" onclick="removeEditSignatureImage()" class="absolute top-0 right-0 mt-2 mr-2 p-1.5 bg-red-500 text-white rounded-full hover:bg-red-600 transition-colors shadow-sm" title="Remove image">
                                            <span class="material-symbols-outlined text-sm" style="font-size: 16px;">close</span>
                                        </button>
                                    </div>
                                </div>
                                <!-- Name Input -->
                                <div class="space-y-2">
                                    <label class="block text-sm font-medium text-gray-900" for="edit-sig-name">Signature Name <span class="text-red-500">*</span></label>
                                    <input name="name" id="edit-sig-name" required class="block w-full rounded-md border border-gray-300 py-2.5 text-gray-900 shadow-sm placeholder:text-gray-400 focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white sm:text-sm sm:leading-6" placeholder="e.g. John Doe Official" type="text"/>
                                </div>
                                <!-- Toggles -->
                                <div class="space-y-4 pt-4 border-t border-gray-200">
                                    <div class="flex items-center justify-between">
                                        <div class="flex flex-col">
                                            <span class="text-sm font-medium text-gray-900">Active Status</span>
                                            <span class="text-xs text-gray-500">Enable this signature for use</span>
                                        </div>
                                        <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                            <input name="is_active" id="edit-is-active" type="checkbox" value="1" class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                                            <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300"></span>
                                        </label>
                                    </div>
                                    <div class="flex items-center justify-between">
                                        <div class="flex flex-col">
                                            <span class="text-sm font-medium text-gray-900">Set as Default</span>
                                            <span class="text-xs text-gray-500">Use automatically on new invoices</span>
                                        </div>
                                        <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                            <input name="is_default" id="edit-is-default" type="checkbox" value="1" class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                                            <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300"></span>
                                        </label>
                                    </div>
                                </div>
                                <!-- Drawer Footer -->
                                <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex items-center justify-end gap-3 -mx-6 -mb-6 sticky bottom-0">
                                    <button type="button" onclick="document.getElementById('edit-signature-modal').classList.add('hidden')" class="px-4 py-2 text-sm font-semibold text-gray-700 hover:text-gray-900 transition-colors">
                                        Cancel
                                    </button>
                                    <button type="submit" class="px-4 py-2 bg-primary hover:bg-primary/90 text-white text-sm font-semibold rounded-lg shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary transition-all">
                                        Save Changes
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Delete Signature Confirmation Modal -->
                <div id="delete-signature-modal" data-admin-modal class="hidden fixed inset-0 z-[100] overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
                    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                        <!-- Background overlay -->
                        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" onclick="document.getElementById('delete-signature-modal').classList.add('hidden')"></div>
                        
                        <!-- Center the modal -->
                        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
                        
                        <!-- Modal panel -->
                        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                                <div class="sm:flex sm:items-start">
                                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                                        <span class="material-symbols-outlined text-red-600" style="font-size: 24px;">warning</span>
                                    </div>
                                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
                                        <h3 class="text-lg leading-6 font-medium text-gray-900" id="delete-signature-title">
                                            Delete Signature
                                        </h3>
                                        <div class="mt-2">
                                            <p class="text-sm text-gray-500">
                                                Are you sure you want to delete <strong id="delete-signature-name" class="text-gray-900"></strong>? This action cannot be undone.
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                                <form id="delete-signature-form" method="POST" class="inline">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm transition-colors">
                                        Delete
                                    </button>
                                </form>
                                <button type="button" onclick="document.getElementById('delete-signature-modal').classList.add('hidden')" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm transition-colors">
                                    Cancel
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Delete success -->
                <div id="signature-delete-success-modal" data-admin-modal class="hidden fixed inset-0 z-[100] overflow-y-auto" role="dialog" aria-modal="true" aria-labelledby="signature-delete-success-title">
                    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" onclick="closeSignatureDeleteSuccessModal()"></div>
                        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
                        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                                <div class="sm:flex sm:items-start">
                                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-emerald-100 sm:mx-0 sm:h-10 sm:w-10">
                                        <span class="material-symbols-outlined text-emerald-600" style="font-size: 28px;">check_circle</span>
                                    </div>
                                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
                                        <h3 class="text-lg leading-6 font-medium text-gray-900" id="signature-delete-success-title">
                                            Deleted successfully
                                        </h3>
                                        <p class="mt-2 text-sm text-gray-500" id="signature-delete-success-message"></p>
                                    </div>
                                </div>
                            </div>
                            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                                <button type="button" onclick="closeSignatureDeleteSuccessModal()" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary text-base font-medium text-white hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:w-auto sm:text-sm transition-colors">
                                    OK
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            @endif
        </div>
    </div>
</div>

<script>
function openEditSignatureModal(id, name, imageUrl, isActive, isDefault) {
    const form = document.getElementById('edit-signature-form');
    form.action = '{{ route("admin.settings.signatures.update", ":id") }}'.replace(':id', id);
    
    // Reset form
    document.getElementById('edit-sig-name').value = name || '';
    document.getElementById('edit-is-active').checked = isActive === true || isActive === 'true';
    document.getElementById('edit-is-default').checked = isDefault === true || isDefault === 'true';
    
    // Reset file input
    const fileInput = document.getElementById('edit-file-upload');
    if (fileInput) {
        fileInput.value = '';
    }
    
    const previewContainer = document.getElementById('edit-signature-preview-container');
    const previewImg = document.getElementById('edit-signature-preview-img');
    const uploadArea = document.getElementById('edit-signature-upload-preview');
    
    if (imageUrl && imageUrl.trim() !== '') {
        previewImg.src = imageUrl;
        previewContainer.classList.remove('hidden');
        uploadArea.classList.add('hidden');
    } else {
        previewContainer.classList.add('hidden');
        uploadArea.classList.remove('hidden');
    }
    
    document.getElementById('edit-signature-modal').classList.remove('hidden');
}

function openDeleteSignatureModal(id, name) {
    const form = document.getElementById('delete-signature-form');
    if (!form) return;
    form.action = '{{ route("admin.settings.signatures.destroy", ":id") }}'.replace(':id', id);

    document.getElementById('delete-signature-name').textContent = name || 'this signature';
    document.getElementById('delete-signature-modal').classList.remove('hidden');
}

function closeSignatureDeleteSuccessModal() {
    const modal = document.getElementById('signature-delete-success-modal');
    if (modal) {
        modal.classList.add('hidden');
    }
}

@if(session('signature_deleted'))
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('signature-delete-success-modal');
    const msg = document.getElementById('signature-delete-success-message');
    if (modal && msg) {
        msg.textContent = @json(session('signature_deleted'));
        modal.classList.remove('hidden');
    }
});
@endif

function previewEditSignatureUpload(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const previewContainer = document.getElementById('edit-signature-preview-container');
            const previewImg = document.getElementById('edit-signature-preview-img');
            const uploadArea = document.getElementById('edit-signature-upload-preview');
            
            if (previewContainer && previewImg) {
                previewImg.src = e.target.result;
                previewContainer.classList.remove('hidden');
                uploadArea.classList.add('hidden');
            }
        };
        reader.readAsDataURL(input.files[0]);
    } else {
        // If no file selected, show upload area again
        removeEditSignatureImage();
    }
}

function removeEditSignatureImage() {
    const previewContainer = document.getElementById('edit-signature-preview-container');
    const previewImg = document.getElementById('edit-signature-preview-img');
    const uploadArea = document.getElementById('edit-signature-upload-preview');
    const fileInput = document.getElementById('edit-file-upload');
    
    if (fileInput) {
        fileInput.value = '';
    }
    
    if (previewContainer && uploadArea) {
        previewContainer.classList.add('hidden');
        uploadArea.classList.remove('hidden');
        if (previewImg) {
            previewImg.src = '';
        }
    }
}
function previewImage(input, imageId, containerId) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            const imageElement = document.getElementById(imageId);
            
            if (imageElement) {
                // Update existing image
                imageElement.src = e.target.result;
                imageElement.style.display = 'block';
                
                // Hide placeholder elements if they exist
                const placeholders = container.querySelectorAll('.material-symbols-outlined, p');
                placeholders.forEach(el => {
                    if (el !== imageElement) {
                        el.style.display = 'none';
                    }
                });
            } else {
                // Create image element if it doesn't exist
                // First, hide all placeholder content
                const placeholders = container.querySelectorAll('.material-symbols-outlined, p');
                placeholders.forEach(el => el.style.display = 'none');
                
                // Create and add image element
                const img = document.createElement('img');
                img.id = imageId;
                img.alt = 'Preview';
                img.className = 'size-16 object-contain rounded-md shadow-sm';
                img.src = e.target.result;
                container.appendChild(img);
            }
            
            // Update button text if exists
            const textElement = document.getElementById(containerId.replace('-preview', '-text'));
            if (textElement && textElement.textContent.includes('Upload')) {
                textElement.textContent = textElement.textContent.replace('Upload', 'Change');
            }
        };
        reader.readAsDataURL(input.files[0]);
    }
}

function previewSignatureUpload(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const previewContainer = document.getElementById('signature-preview-container');
            const previewImg = document.getElementById('signature-preview-img');
            const uploadArea = document.getElementById('signature-upload-preview');
            
            if (previewContainer && previewImg) {
                previewImg.src = e.target.result;
                previewContainer.classList.remove('hidden');
                uploadArea.classList.add('hidden');
            }
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// Logo upload handlers
document.addEventListener('DOMContentLoaded', function() {
    const logoUpload = document.getElementById('logo-upload');
    const faviconUpload = document.getElementById('favicon-upload');
    
    if (logoUpload) {
        logoUpload.addEventListener('change', function(e) {
            previewImage(e.target, 'logo-preview-img', 'logo-preview');
        });
    }
    
    if (faviconUpload) {
        faviconUpload.addEventListener('change', function(e) {
            previewImage(e.target, 'favicon-preview-img', 'favicon-preview');
        });
    }
});

// Signature search functionality
let searchTimeout;
function searchSignatures(query) {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(function() {
        const perPage = document.getElementById('signature-per-page')?.value || 10;
        const url = new URL('{{ route('admin.settings.signatures.search') }}', window.location.origin);
        url.searchParams.set('q', query);
        url.searchParams.set('per_page', perPage);
        
        fetch(url, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.html) {
                const tbody = document.querySelector('table tbody');
                if (tbody) {
                    tbody.innerHTML = data.html;
                }
            }
        })
        .catch(error => console.error('Error searching signatures:', error));
    }, 300);
}

function loadSignatures() {
    const perPage = document.getElementById('signature-per-page')?.value || 10;
    const search = document.getElementById('signature-search')?.value || '';
    const url = new URL('{{ route('admin.settings.general', ['tab' => 'signatures']) }}', window.location.origin);
    url.searchParams.set('per_page', perPage);
    if (search) {
        url.searchParams.set('q', search);
    }
    window.location.href = url.toString();
}

// Calendar functionality for profile settings
document.addEventListener('DOMContentLoaded', function() {
    const calendarDays = document.getElementById('calendar-days');
    const calendarMonthYear = document.getElementById('calendar-month-year');
    const calendarPrev = document.getElementById('calendar-prev');
    const calendarNext = document.getElementById('calendar-next');
    const selectedTime = document.getElementById('selected-time');
    const selectedDatetime = document.getElementById('selected-datetime');
    const dateOfBirthInput = document.getElementById('date-of-birth-input');
    const openDatePicker = document.getElementById('open-date-picker');
    
    if (!calendarDays || !calendarMonthYear) return;
    
    let currentDate = new Date();
    let selectedDate = new Date();
    
    function renderCalendar() {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        
        // Update month/year display
        const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 
                          'July', 'August', 'September', 'October', 'November', 'December'];
        calendarMonthYear.textContent = `${monthNames[month]} ${year}`;
        
        // Get first day of month and number of days
        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);
        const daysInMonth = lastDay.getDate();
        const startingDayOfWeek = firstDay.getDay();
        
        // Clear calendar
        calendarDays.innerHTML = '';
        
        // Add empty cells for days before month starts
        for (let i = 0; i < startingDayOfWeek; i++) {
            const emptyCell = document.createElement('span');
            emptyCell.className = 'p-2 text-gray-300';
            calendarDays.appendChild(emptyCell);
        }
        
        // Add days of month
        for (let day = 1; day <= daysInMonth; day++) {
            const dayCell = document.createElement('button');
            dayCell.type = 'button';
            dayCell.className = 'p-2 hover:bg-primary hover:text-white rounded-lg transition-colors';
            
            // Highlight today
            const cellDate = new Date(year, month, day);
            const today = new Date();
            if (cellDate.toDateString() === today.toDateString()) {
                dayCell.className += ' bg-primary text-white';
            }
            
            // Highlight selected date
            if (cellDate.toDateString() === selectedDate.toDateString()) {
                dayCell.className += ' ring-2 ring-primary';
            }
            
            dayCell.textContent = day;
            dayCell.addEventListener('click', function() {
                selectedDate = new Date(year, month, day);
                updateSelectedDateTime();
                renderCalendar();
            });
            calendarDays.appendChild(dayCell);
        }
    }
    
    function updateSelectedDateTime() {
        const time = selectedTime.value || '00:00';
        const [hours, minutes] = time.split(':');
        const dateTime = new Date(selectedDate);
        dateTime.setHours(parseInt(hours), parseInt(minutes));
        
        const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
                          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        const formattedDate = `${monthNames[dateTime.getMonth()]} ${dateTime.getDate()}, ${dateTime.getFullYear()} ${formatTime(dateTime)}`;
        
        if (selectedDatetime) {
            selectedDatetime.textContent = formattedDate;
        }
        
        // Update date of birth input if it exists
        if (dateOfBirthInput) {
            const year = dateTime.getFullYear();
            const month = String(dateTime.getMonth() + 1).padStart(2, '0');
            const day = String(dateTime.getDate()).padStart(2, '0');
            dateOfBirthInput.value = `${year}-${month}-${day}`;
        }
    }
    
    function formatTime(date) {
        const hours = date.getHours();
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const ampm = hours >= 12 ? 'PM' : 'AM';
        const displayHours = hours % 12 || 12;
        return `${displayHours}:${minutes} ${ampm}`;
    }
    
    // Navigation
    if (calendarPrev) {
        calendarPrev.addEventListener('click', function() {
            currentDate.setMonth(currentDate.getMonth() - 1);
            renderCalendar();
        });
    }
    
    if (calendarNext) {
        calendarNext.addEventListener('click', function() {
            currentDate.setMonth(currentDate.getMonth() + 1);
            renderCalendar();
        });
    }
    
    // Time change
    if (selectedTime) {
        selectedTime.addEventListener('change', updateSelectedDateTime);
    }
    
    // Open date picker button
    if (openDatePicker) {
        openDatePicker.addEventListener('click', function() {
            // Scroll to calendar if it exists
            const calendarWidget = document.querySelector('.bg-white.dark\\:bg-white.p-6.rounded-xl');
            if (calendarWidget) {
                calendarWidget.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        });
    }
    
    // Initial render
    renderCalendar();
    updateSelectedDateTime();
});
</script>
@endsection

