<x-app-layout>
    <x-module-hero
        title="Create Election Cycle"
        description="Define a new election cycle for leadership positions"
        icon="fa-calendar-alt">

        <x-slot name="backButton">
            <a href="{{ route('organization.election-cycles.index') }}"
               class="inline-flex items-center gap-2 text-[#475569] hover:text-[#1e293b] text-sm transition">
                <i class="fas fa-arrow-left text-xs"></i> Back to List
            </a>
        </x-slot>

        <x-slot name="tabs">
            @can('view organizations')
            <a href="{{ route('organization.details.index') }}"
               class="module-hero-tab {{ request()->routeIs('organization.details.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-building text-sm"></i> Organization Details
            </a>
            @endcan
            @can('view leadership positions')
            <a href="{{ route('organization.leadership-positions.index') }}"
               class="module-hero-tab {{ request()->routeIs('organization.leadership-positions.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-sitemap text-sm"></i> Leadership Positions
            </a>
            @endcan
            @can('view leadership history')
            <a href="{{ route('organization.leadership-history.index') }}"
               class="module-hero-tab {{ request()->routeIs('organization.leadership-history.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-history text-sm"></i> Leadership History
            </a>
            @endcan
            @can('view staff history')
            <a href="{{ route('organization.staff-history.index') }}"
               class="module-hero-tab {{ request()->routeIs('organization.staff-history.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-user-tie text-sm"></i> Staff History
            </a>
            @endcan
            @can('view election cycles')
            <a href="{{ route('organization.election-cycles.index') }}"
               class="module-hero-tab {{ request()->routeIs('organization.election-cycles.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-calendar-alt text-sm"></i> Election Cycles
            </a>
            @endcan
            @can('view voting procedures')
            <a href="{{ route('organization.voting-procedures.index') }}"
               class="module-hero-tab {{ request()->routeIs('organization.voting-procedures.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-vote-yea text-sm"></i> Voting Procedures
            </a>
            @endcan
            @can('view organogram')
            <a href="{{ route('organization.organogram.show') }}"
               class="module-hero-tab {{ request()->routeIs('organization.organogram.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-project-diagram text-sm"></i> Organogram
            </a>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-6" x-data="electionCycleForm()">
        <form action="{{ route('organization.election-cycles.store') }}" method="POST">
            @csrf

            {{-- Basic Info --}}
            <h3 class="text-lg font-semibold text-gray-800 border-b pb-2 mb-4">Basic Information</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="organization_id">
                        Organization <span class="text-red-500">*</span>
                    </label>
                    <select id="organization_id" name="organization_id"
                        x-model="selectedOrganization"
                        @change="loadPositions()"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-800 focus:ring-2 focus:ring-green-500 focus:border-transparent"
                        required>
                        <option value="">Select Organization</option>
                        @foreach($organizations as $org)
                            <option value="{{ $org->id }}" {{ old('organization_id') == $org->id ? 'selected' : '' }}>{{ $org->name }}</option>
                        @endforeach
                    </select>
                    @error('organization_id')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="name">
                        Cycle Name <span class="text-red-500">*</span>
                    </label>
                    <input type="text" id="name" name="name" value="{{ old('name') }}"
                        placeholder="e.g., 2024-2026 Board Election"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-800 focus:ring-2 focus:ring-green-500 focus:border-transparent"
                        required>
                    @error('name')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="duration_years">
                        Duration (Years) <span class="text-red-500">*</span>
                    </label>
                    <select id="duration_years" name="duration_years"
                        @change="calculateEndDate()"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-800 focus:ring-2 focus:ring-green-500 focus:border-transparent"
                        required>
                        <option value="">Select Duration</option>
                        <option value="0.5" {{ old('duration_years') == '0.5' ? 'selected' : '' }}>6 Months</option>
                        <option value="1" {{ old('duration_years') == '1' ? 'selected' : '' }}>1 Year</option>
                        <option value="2" {{ old('duration_years') == '2' ? 'selected' : '' }}>2 Years</option>
                        <option value="3" {{ old('duration_years') == '3' ? 'selected' : '' }}>3 Years</option>
                        <option value="4" {{ old('duration_years') == '4' ? 'selected' : '' }}>4 Years</option>
                        <option value="5" {{ old('duration_years') == '5' ? 'selected' : '' }}>5 Years</option>
                    </select>
                    @error('duration_years')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="start_date">
                        Start Date <span class="text-red-500">*</span>
                    </label>
                    <input type="date" id="start_date" name="start_date" value="{{ old('start_date') }}"
                        @change="calculateEndDate()"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-800 focus:ring-2 focus:ring-green-500 focus:border-transparent"
                        required>
                    @error('start_date')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
            </div>

            {{-- Applicable Positions --}}
            <h3 class="text-lg font-semibold text-gray-800 border-b pb-2 mb-4">Applicable Positions</h3>
            <p class="text-sm text-gray-500 mb-4">Select the leadership positions included in this election cycle. Select an organization first.</p>
            <div id="positions-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 mb-6">
                <p class="text-sm text-gray-400 italic col-span-full">Select an organization to see available positions.</p>
            </div>
            @error('applicable_positions')<p class="mb-4 text-xs text-red-600">{{ $message }}</p>@enderror

            {{-- Voting Procedures --}}
            <h3 class="text-lg font-semibold text-gray-800 border-b pb-2 mb-4">Voting Procedures <span class="text-gray-400 text-sm font-normal">(optional)</span></h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-6">
                @if($votingProcedures && $votingProcedures->count() > 0)
                    @foreach($votingProcedures as $procedure)
                    <label class="flex items-center gap-3 p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer">
                        <input type="checkbox" name="voting_procedures[]" value="{{ $procedure->id }}"
                            {{ in_array($procedure->id, old('voting_procedures', [])) ? 'checked' : '' }}
                            class="rounded text-green-600 focus:ring-green-500">
                        <div>
                            <div class="text-sm font-medium text-gray-800">{{ $procedure->name }}</div>
                            <div class="text-xs text-gray-500">{{ $procedure->voting_method_label }}</div>
                        </div>
                    </label>
                    @endforeach
                @else
                    <p class="text-sm text-gray-400 italic col-span-full">No voting procedures available. Create voting procedures first.</p>
                @endif
            </div>

            <div class="flex justify-end gap-3 pt-4 border-t border-gray-200">
                <a href="{{ route('organization.election-cycles.index') }}"
                   class="px-5 py-2 bg-gray-200 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-300 transition">
                    <i class="fas fa-times mr-1"></i>Cancel
                </a>
                <button type="submit" class="theme-btn-primary px-5 py-2 rounded-lg text-sm font-medium">
                    <i class="fas fa-save mr-1"></i>Create Election Cycle
                </button>
            </div>
        </form>
    </div>
</x-app-layout>

@push('scripts')
<script>
function electionCycleForm() {
    return {
        selectedOrganization: '{{ old('organization_id') }}',

        loadPositions() {
            if (!this.selectedOrganization) {
                document.getElementById('positions-container').innerHTML = '<p class="text-sm text-gray-400 italic col-span-full">Select an organization to see available positions.</p>';
                return;
            }
            const url = '{{ route('organization.election-cycles.positions', ['organization' => '__ORG__']) }}'.replace('__ORG__', this.selectedOrganization);
            fetch(url)
                .then(r => r.json())
                .then(data => {
                    if (!data.length) {
                        document.getElementById('positions-container').innerHTML = '<p class="text-sm text-gray-400 italic col-span-full">No positions found for this organization.</p>';
                        return;
                    }
                    document.getElementById('positions-container').innerHTML = data.map(p => `
                        <label class="flex items-center gap-3 p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer">
                            <input type="checkbox" name="applicable_positions[]" value="${p.id}" class="rounded text-green-600 focus:ring-green-500">
                            <div>
                                <div class="text-sm font-medium text-gray-800">${p.title}</div>
                                <div class="text-xs text-gray-500 capitalize">${(p.hierarchy_level || '').replace('_', ' ')}</div>
                            </div>
                        </label>
                    `).join('');
                });
        },

        calculateEndDate() {
            const duration = document.getElementById('duration_years').value;
            const startDate = document.getElementById('start_date').value;
            if (duration && startDate) {
                const start = new Date(startDate);
                const years = Math.floor(parseFloat(duration));
                const months = Math.round((parseFloat(duration) - years) * 12);
                const end = new Date(start);
                end.setFullYear(end.getFullYear() + years);
                end.setMonth(end.getMonth() + months);
                // Could display calculated end date somewhere if needed
            }
        }
    }
}
</script>
@endpush
