@extends('layouts.app')

@section('title', $employee->name)
@section('heading', $employee->name)

@section('content')
    @include('employees.top-submenu')
    @php
        $employeeSteps = [
            'profile' => ['label' => 'Profile', 'title' => 'Profile', 'subtitle' => 'Basic information', 'formSubtitle' => 'Personal and contact details', 'icon' => 'bi-person', 'theme' => 'teal'],
            'work' => ['label' => 'Work Info', 'title' => 'Work Information', 'subtitle' => 'Employment details', 'formSubtitle' => 'Work-related information', 'icon' => 'bi-briefcase', 'theme' => 'sky'],
            'attendance' => ['label' => 'Attendance', 'title' => 'Attendance', 'subtitle' => 'Recent punch history', 'formSubtitle' => 'Recent attendance (last 30 records)', 'icon' => 'bi-clock-history', 'theme' => 'sky'],
            'leaves' => ['label' => 'Leaves', 'title' => 'Leaves', 'subtitle' => 'Leave request history', 'formSubtitle' => 'Leave history', 'icon' => 'bi-calendar2-week', 'theme' => 'teal'],
        ];

        if (! empty($canViewCompensation)) {
            $employeeSteps['payroll'] = ['label' => 'Payroll', 'title' => 'Payroll', 'subtitle' => 'Payslip history', 'formSubtitle' => 'Payroll history', 'icon' => 'bi-cash-stack', 'theme' => 'rose'];
            $employeeSteps['salary'] = ['label' => 'Salary Details', 'title' => 'Salary Details', 'subtitle' => 'Compensation and pay group', 'formSubtitle' => 'Salary breakup and revisions', 'icon' => 'bi-wallet2', 'theme' => 'rose'];
        }

        if (! empty($canViewFullEmployeeProfile)) {
            $employeeSteps['bank'] = ['label' => 'Bank Account', 'title' => 'Bank Account Details', 'subtitle' => 'Bank, PF, ESI, Tax', 'formSubtitle' => 'Bank account information for salary payments', 'icon' => 'bi-bank', 'theme' => 'violet'];
            $employeeSteps['documents'] = ['label' => 'Documents', 'title' => 'Documents', 'subtitle' => 'Files and assigned assets', 'formSubtitle' => 'Employee documents and compliance', 'icon' => 'bi-folder2-open', 'theme' => 'violet'];
            $employeeSteps['assets'] = ['label' => 'Assets', 'title' => 'Assets', 'subtitle' => 'Company assets', 'formSubtitle' => 'Assets assigned to this employee', 'icon' => 'bi-laptop', 'theme' => 'sky'];
        }

        $tabKeys = array_keys($employeeSteps);
        $requestTab = request('tab');
        $initialTab = in_array($requestTab, $tabKeys, true) ? $requestTab : ($tabKeys[0] ?? 'profile');
    @endphp

    <div class="employee-create employee-profile" x-data="{
        tab: @js($initialTab),
        tabs: @js($tabKeys),
        canScrollUp: false,
        canScrollDown: false,
        next() {
            const index = this.tabs.indexOf(this.tab);
            if (index < this.tabs.length - 1) {
                this.tab = this.tabs[index + 1];
            }
        },
        prev() {
            const index = this.tabs.indexOf(this.tab);
            if (index > 0) {
                this.tab = this.tabs[index - 1];
            }
        },
        isFirst() {
            return this.tab === this.tabs[0];
        },
        isLast() {
            return this.tab === this.tabs[this.tabs.length - 1];
        },
        isDone(key) {
            return this.tabs.indexOf(key) < this.tabs.indexOf(this.tab);
        },
        isActive(key) {
            return this.tab === key;
        },
        timelineNav() {
            return this.$refs.timelineNav || null;
        },
        updateTimelineScrollState() {
            const nav = this.timelineNav();
            if (!nav) {
                this.canScrollUp = false;
                this.canScrollDown = false;
                return;
            }
            const maxScroll = Math.max(0, nav.scrollHeight - nav.clientHeight);
            this.canScrollUp = nav.scrollTop > 2;
            this.canScrollDown = nav.scrollTop < maxScroll - 2;
        },
        scrollTimeline(direction) {
            const nav = this.timelineNav();
            if (!nav) {
                return;
            }
            const amount = Math.max(120, Math.round(nav.clientHeight * 0.45));
            nav.scrollBy({ top: direction * amount, behavior: 'smooth' });
            window.setTimeout(() => this.updateTimelineScrollState(), 280);
        },
        scrollActiveStepIntoView(smooth = true) {
            const nav = this.timelineNav();
            const active = nav ? nav.querySelector('.employee-create__step.is-active') : null;
            if (!nav || !active) {
                return;
            }
            const relativeTop = active.getBoundingClientRect().top - nav.getBoundingClientRect().top + nav.scrollTop;
            const target = relativeTop - ((nav.clientHeight - active.offsetHeight) / 2);
            const maxScroll = Math.max(0, nav.scrollHeight - nav.clientHeight);
            const top = Math.min(Math.max(0, target), maxScroll);
            nav.scrollTo({ top, behavior: smooth ? 'smooth' : 'auto' });
            window.setTimeout(() => this.updateTimelineScrollState(), smooth ? 280 : 0);
        },
        queueScrollActiveStep(smooth = true) {
            this.$nextTick(() => {
                requestAnimationFrame(() => this.scrollActiveStepIntoView(smooth));
            });
        },
        init() {
            this.$watch('tab', () => this.queueScrollActiveStep(true));
            this.$nextTick(() => {
                const nav = this.timelineNav();
                if (nav) {
                    nav.addEventListener('scroll', () => this.updateTimelineScrollState(), { passive: true });
                }
                this.scrollActiveStepIntoView(false);
                this.updateTimelineScrollState();
            });
        }
    }">
        <a href="{{ route('employees.index') }}" class="employee-view__back">
            <span class="employee-view__back-icon" aria-hidden="true">
                <i class="bi bi-chevron-left"></i>
            </span>
            Back to Employees
        </a>

        <div class="employee-create__layout employee-view__layout">
            <aside class="employee-view__card">
                <div class="employee-view__card-head">
                    <x-user-avatar :user="$employee" size="xl" class="employee-view__avatar" />
                    <h2 class="employee-view__name">{{ $employee->name }}</h2>
                    <p class="employee-view__meta">
                        {{ $employee->employee_number ?? '—' }}
                        @if($employee->designation?->name)
                            - {{ $employee->designation->name }}
                        @endif
                    </p>
                    <div class="employee-view__status">
                        <x-badge :status="$employee->status">{{ ucfirst($employee->status) }}</x-badge>
                    </div>
                </div>

                <ul class="employee-view__facts">
                    <li>
                        <i class="bi bi-envelope" aria-hidden="true"></i>
                        <span>{{ $employee->email }}</span>
                    </li>
                    @if(!empty($canViewFullEmployeeProfile))
                        <li>
                            <i class="bi bi-telephone" aria-hidden="true"></i>
                            <span>{{ $employee->phone ? '+91 '.$employee->phone : '—' }}</span>
                        </li>
                    @endif
                    <li>
                        <i class="bi bi-building" aria-hidden="true"></i>
                        <span>{{ $employee->department?->name ?? '—' }}</span>
                    </li>
                    <li>
                        <i class="bi bi-calendar3" aria-hidden="true"></i>
                        <span>
                            @if($employee->joining_date)
                                Joined on {{ $employee->joining_date->format('d M Y') }}
                            @else
                                —
                            @endif
                        </span>
                    </li>
                    <li>
                        <i class="bi bi-geo-alt" aria-hidden="true"></i>
                        <span>{{ $employee->location?->name ?? ($employee->work_state ?? '—') }}</span>
                    </li>
                </ul>

                @if(auth()->user()->hasPermission('users_edit'))
                    <a href="{{ route('employees.edit', $employee) }}"
                       x-bind:href="'{{ route('employees.edit', $employee) }}' + (['profile','work','salary','bank'].includes(tab) ? '?tab=' + ({ profile: 'basic', work: 'work', salary: 'salary', bank: 'bank' }[tab] || 'basic') : '')"
                       class="employee-create__btn employee-create__btn--soft employee-view__edit">
                        <i class="bi bi-pencil-square"></i>
                        Edit Profile
                    </a>
                @endif
            </aside>

            <aside class="employee-create__sidebar employee-view__timeline">
                <button
                    type="button"
                    class="employee-view__timeline-arrow"
                    :class="{ 'is-disabled': !canScrollUp }"
                    :disabled="!canScrollUp"
                    @click="scrollTimeline(-1)"
                    aria-label="Scroll timeline up"
                >
                    <i class="bi bi-chevron-up"></i>
                </button>
                <nav aria-label="Employee sections" x-ref="timelineNav">
                    <ol class="employee-create__steps employee-view__steps">
                        @foreach($employeeSteps as $key => $step)
                            <li
                                class="employee-create__step employee-create__step--{{ $step['theme'] }}"
                                data-step-key="{{ $key }}"
                                :class="{
                                    'is-active': isActive('{{ $key }}'),
                                    'is-done': isDone('{{ $key }}')
                                }"
                            >
                                <span class="employee-create__step-index" aria-hidden="true">
                                    <span x-show="!isDone('{{ $key }}')">{{ $loop->iteration }}</span>
                                    <i class="bi bi-check-lg" x-show="isDone('{{ $key }}')" x-cloak></i>
                                </span>
                                <button type="button" class="employee-create__step-card" @click="tab = '{{ $key }}'">
                                    <span class="employee-create__step-icon">
                                        <i class="bi {{ $step['icon'] }}"></i>
                                    </span>
                                    <span class="employee-create__step-copy">
                                        <span class="employee-create__step-title">{{ $step['label'] }}</span>
                                        <span class="employee-create__step-subtitle">{{ $step['subtitle'] }}</span>
                                    </span>
                                </button>
                            </li>
                        @endforeach
                    </ol>
                </nav>
                <button
                    type="button"
                    class="employee-view__timeline-arrow"
                    :class="{ 'is-disabled': !canScrollDown }"
                    :disabled="!canScrollDown"
                    @click="scrollTimeline(1)"
                    aria-label="Scroll timeline down"
                >
                    <i class="bi bi-chevron-down"></i>
                </button>
            </aside>

            <div class="employee-create__panel">
                <div class="employee-view__panel-top">
                    <div class="employee-view__panel-titles">
                        @foreach($employeeSteps as $key => $step)
                            <div class="employee-create__panel-head employee-create__panel-head--{{ $step['theme'] }}" x-show="tab === '{{ $key }}'" @unless($key === $initialTab) x-cloak @endunless>
                                <span class="employee-create__panel-icon">
                                    <i class="bi {{ $step['icon'] }}"></i>
                                </span>
                                <div>
                                    <h3>{{ $step['title'] }}</h3>
                                    <p>{{ $step['formSubtitle'] }}</p>
                                </div>
                            </div>
                        @endforeach
                    </div>
                    <div class="employee-create__actions employee-view__actions">
                        <button type="button" x-show="!isFirst()" @click="prev()" class="employee-create__btn employee-create__btn--soft">
                            <i class="bi bi-arrow-left"></i>
                            Back
                        </button>
                        <button type="button" x-show="!isLast()" @click="next()" class="employee-create__btn employee-create__btn--primary">
                            Next
                            <i class="bi bi-arrow-right"></i>
                        </button>
                    </div>
                </div>

                <div x-show="tab === 'profile'" @unless($initialTab === 'profile') x-cloak @endunless class="employee-view__details">
                    <div>
                        <label class="employee-view__detail-label">Name</label>
                        <div class="employee-view__detail-value">{{ $employee->name }}</div>
                    </div>
                    <div>
                        <label class="employee-view__detail-label">Employee ID</label>
                        <div class="employee-view__detail-value">{{ $employee->employee_number ?? '—' }}</div>
                    </div>
                    <div>
                        <label class="employee-view__detail-label">Email</label>
                        <div class="employee-view__detail-value">{{ $employee->email }}</div>
                    </div>
                    @if(!empty($canViewFullEmployeeProfile))
                        <div>
                            <label class="employee-view__detail-label">Phone</label>
                            <div class="employee-view__detail-value">{{ $employee->phone ?? '—' }}</div>
                        </div>
                        <div>
                            <label class="employee-view__detail-label">Gender</label>
                            <div class="employee-view__detail-value">{{ $employee->gender ? ucfirst($employee->gender) : '—' }}</div>
                        </div>
                        <div>
                            <label class="employee-view__detail-label">Date of Birth</label>
                            <div class="employee-view__detail-value">{{ $employee->dob?->format('M d, Y') ?? '—' }}</div>
                        </div>
                        <div>
                            <label class="employee-view__detail-label">Father Name</label>
                            <div class="employee-view__detail-value">{{ $employee->father_name ?? '—' }}</div>
                        </div>
                        <div>
                            <label class="employee-view__detail-label">PAN Number</label>
                            <div class="employee-view__detail-value">{{ $employee->pan_number ?? '—' }}</div>
                        </div>
                    @endif
                    <div>
                        <label class="employee-view__detail-label">Status</label>
                        <div class="employee-view__detail-value">
                            <x-badge :status="$employee->status">{{ $employee->status }}</x-badge>
                        </div>
                    </div>
                </div>

                <div x-show="tab === 'work'" @unless($initialTab === 'work') x-cloak @endunless class="employee-create__sections">
                    <section>
                        <h4 class="employee-create__section-title">
                            <i class="bi bi-calendar3"></i>
                            Employment Dates
                        </h4>
                        <div class="employee-view__details">
                            <div>
                                <label class="employee-view__detail-label">Joining Date</label>
                                <div class="employee-view__detail-value">{{ $employee->joining_date?->format('M d, Y') ?? '—' }}</div>
                            </div>
                            @if(!empty($canViewFullEmployeeProfile))
                                <div>
                                    <label class="employee-view__detail-label">Registration Date</label>
                                    <div class="employee-view__detail-value">{{ $employee->registration_date?->format('M d, Y') ?? $employee->created_at?->format('M d, Y') ?? '—' }}</div>
                                </div>
                                <div>
                                    <label class="employee-view__detail-label">Confirmation Date</label>
                                    <div class="employee-view__detail-value">{{ $employee->confirmation_date?->format('M d, Y') ?? '—' }}</div>
                                </div>
                                <div>
                                    <label class="employee-view__detail-label">Probation End Date</label>
                                    <div class="employee-view__detail-value">{{ $employee->probation_end_date?->format('M d, Y') ?? '—' }}</div>
                                </div>
                                <div>
                                    <label class="employee-view__detail-label">PF Join / Registration Date</label>
                                    <div class="employee-view__detail-value">{{ $employee->pf_join_date?->format('M d, Y') ?? '—' }}</div>
                                </div>
                                <div>
                                    <label class="employee-view__detail-label">Last Working Day</label>
                                    <div class="employee-view__detail-value">{{ $employee->last_working_date?->format('M d, Y') ?? '—' }}</div>
                                </div>
                            @endif
                        </div>
                    </section>
                    <section>
                        <h4 class="employee-create__section-title">
                            <i class="bi bi-briefcase"></i>
                            Work Details
                        </h4>
                        <div class="employee-view__details">
                            <div>
                                <label class="employee-view__detail-label">Department</label>
                                <div class="employee-view__detail-value">{{ $employee->department?->name ?? '—' }}</div>
                            </div>
                            <div>
                                <label class="employee-view__detail-label">Designation</label>
                                <div class="employee-view__detail-value">{{ $employee->designation?->name ?? '—' }}</div>
                            </div>
                            <div>
                                <label class="employee-view__detail-label">Location</label>
                                <div class="employee-view__detail-value">{{ $employee->location?->name ?? '—' }}</div>
                            </div>
                            <div>
                                <label class="employee-view__detail-label">Shift</label>
                                <div class="employee-view__detail-value">{{ $employee->shift?->name ?? '—' }}</div>
                            </div>
                            <div>
                                <label class="employee-view__detail-label">Reporting Manager</label>
                                <div class="employee-view__detail-value">{{ $employee->reportingManager?->name ?? '—' }}</div>
                            </div>
                            @if(!empty($canViewFullEmployeeProfile))
                                <div>
                                    <label class="employee-view__detail-label">Work State</label>
                                    <div class="employee-view__detail-value">{{ $employee->work_state ?? '—' }}</div>
                                </div>
                                <div>
                                    <label class="employee-view__detail-label">Attendance mode</label>
                                    <div class="employee-view__detail-value">{{ $employee->attendance_mode ? str_replace('_', ' ', $employee->attendance_mode) : 'Tenant default' }}</div>
                                </div>
                                <div>
                                    <label class="employee-view__detail-label">PT Location</label>
                                    <div class="employee-view__detail-value">{{ $employee->pt_location ?? '—' }}</div>
                                </div>
                                <div>
                                    <label class="employee-view__detail-label">UAN Number</label>
                                    <div class="employee-view__detail-value">{{ $employee->uan_number ?? '—' }}</div>
                                </div>
                            @endif
                        </div>
                    </section>
                </div>
        @if(!empty($canViewCompensation))
        <div x-show="tab === 'salary'" @unless($initialTab === 'salary') x-cloak @endunless>
            <div
                x-data="{
                    openRevise: false,
                    effectiveDate: '{{ now()->format('Y-m-d') }}',
                    currentCtcAnnual: {{ \Illuminate\Support\Js::from((float) ($salaryBreakup['ctc_annual'] ?? ($salaryStructure['annual_total'] ?? 0))) }},
                    initialSalaryGroupId: {{ \Illuminate\Support\Js::from($employee->salary_group_id ? (int) $employee->salary_group_id : null) }},
                    selectedSalaryGroup: {{ \Illuminate\Support\Js::from($employee->salary_group_id ? (int) $employee->salary_group_id : null) }},
                    ctcAnnualInput: 0,
                    ctcPercentInput: 0,
                    ctcPercentDraft: '0.00',
                    isSyncing: false,
                    init() {
                        this.resetRevisionValues();
                    },
                    parseNumber(value) {
                        const parsed = parseFloat(value);
                        return Number.isFinite(parsed) ? parsed : 0;
                    },
                    round2(value) {
                        return Math.round(this.parseNumber(value) * 100) / 100;
                    },
                    formatInr(value) {
                        return new Intl.NumberFormat('en-IN', { maximumFractionDigits: 2 }).format(this.parseNumber(value));
                    },
                    revisionPct(current, revised) {
                        const c = this.parseNumber(current);
                        const r = this.parseNumber(revised);
                        if (c <= 0) return r > 0 ? 100 : 0;
                        return ((r - c) / c) * 100;
                    },
                    get canSaveRevision() {
                        const input = this.parseNumber(this.ctcAnnualInput);
                        const current = this.parseNumber(this.currentCtcAnnual);

                        if (input <= 0) return false;

                        const ctcChanged = Math.abs(input - current) > 0.0049;
                        const groupChanged = String(this.selectedSalaryGroup ?? '') !== String(this.initialSalaryGroupId ?? '');

                        return ctcChanged || groupChanged;
                    },
                    syncSalaryGroupSelect() {
                        const el = this.$root.querySelector('select[name=salary_group]');
                        if (!el || !window.jQuery || typeof window.initSelect2 !== 'function') return;
                        const value = this.selectedSalaryGroup == null || this.selectedSalaryGroup === '' ? '' : String(this.selectedSalaryGroup);
                        const $select = window.jQuery(el);
                        if ($select.data('select2')) {
                            $select.val(value).trigger('change.select2');
                            return;
                        }
                        el.value = value;
                        const dialog = el.closest('.revise-salary-dialog');
                        window.initSelect2(dialog || el.parentElement || el);
                    },
                    syncFromCtcInput() {
                        if (this.isSyncing) return;
                        this.isSyncing = true;
                        const revisedAnnual = Math.max(0, this.round2(this.ctcAnnualInput));
                        this.ctcAnnualInput = revisedAnnual;
                        this.ctcPercentInput = this.revisionPct(this.currentCtcAnnual, revisedAnnual);
                        this.ctcPercentDraft = this.ctcPercentInput.toFixed(2);
                        this.isSyncing = false;
                    },
                    syncFromPctInput() {
                        if (this.isSyncing) return;
                        this.isSyncing = true;
                        const pct = this.parseNumber(this.ctcPercentDraft);
                        this.ctcPercentInput = pct;
                        this.ctcPercentDraft = pct.toFixed(2);
                        const revisedAnnual = Math.max(0, this.round2(this.currentCtcAnnual * (1 + (pct / 100))));
                        this.ctcAnnualInput = revisedAnnual;
                        this.isSyncing = false;
                    },
                    resetRevisionValues() {
                        this.ctcAnnualInput = this.round2(this.currentCtcAnnual);
                        this.ctcPercentInput = 0;
                        this.ctcPercentDraft = '0.00';
                        this.selectedSalaryGroup = this.initialSalaryGroupId;
                    },
                    openReviseModal() {
                        this.effectiveDate = '{{ now()->format('Y-m-d') }}';
                        this.resetRevisionValues();
                        this.openRevise = true;
                        this.$nextTick(() => this.syncSalaryGroupSelect());
                    }
                }"
                class="rounded-lg p-4"
            >
                <h3 class="text-2xl font-semibold text-slate-900">Salary Breakup</h3>
                @if($employee->latestEffectiveSalaryRevision() && $employee->latestEffectiveSalaryRevision()?->ctc_annual > 0)
                    <div class="flex flex-wrap items-center justify-between gap-2">
                        <p class="text-base text-slate-800">Current Salary</p>
                        <p class="text-sm text-slate-700">Effective Date: <span class="font-semibold">{{ $salaryStructure['effective_date'] ?? '—' }}</span></p>
                    </div>                
                    <div class="mt-3 overflow-hidden rounded border border-slate-400 bg-white">
                        <table class="min-w-full divide-y divide-slate-200">
                            <thead class="bg-primary text-white">
                                <tr>
                                    <th class="px-3 py-2 text-left text-xs font-medium font-semibold uppercase tracking-wide">Earnings</th>
                                    <th class="px-3 py-2 text-right text-xs font-medium font-semibold uppercase tracking-wide">Monthly</th>
                                    <th class="px-3 py-2 text-right text-xs font-medium font-semibold uppercase tracking-wide">Annually</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200">
                                @if(!empty($componentDetails))
                                    <tr class="text-slate-700">
                                        <td class="px-3 py-2 text-sm">
                                            <span class="font-medium text-slate-700">Salary Group Components</span>
                                            <p class="text-xs text-slate-500">{{ implode(', ', $componentDetails) }}</p>
                                        </td>
                                        <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($salaryBreakup['salary_group_monthly'], 2) }}</td>
                                        <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($salaryBreakup['salary_group_annual'], 2) }}</td>
                                    </tr>
                                @endif
                                @forelse($salaryBreakup['earning_rows'] as $row)
                                    <tr>
                                        <td class="px-3 py-2 text-sm text-slate-700">{{ $row['name'] }}</td>
                                        <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums text-slate-900">₹{{ number_format($row['monthly'], 2) }}</td>
                                        <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums text-slate-900">₹{{ number_format($row['annual'], 2) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="3" class="px-3 py-4 text-center text-sm text-slate-500">No earning components in salary structure.</td>
                                    </tr>
                                @endforelse
                                <tr class="font-medium text-slate-800 {{!count($salaryBreakup['employer_rows']) > 0 ? 'bg-slate-300' : 'bg-slate-50/80'}}">
                                    <td class="px-3 py-2 text-sm">@if(!count($salaryBreakup['employer_rows']) > 0) Total Earnings (CTC) @else Sub Total @endif</td>
                                    <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($salaryBreakup['subtotal_monthly'], 2) }}</td>
                                    <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($salaryBreakup['subtotal_annual'], 2) }}</td>
                                </tr>
                                @foreach($salaryBreakup['employer_rows'] as $row)
                                    <tr class="text-slate-700">
                                        <td class="px-3 py-2 text-sm">
                                            <span>{{ $row['name'] }}</span>
                                        </td>
                                        <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($row['monthly'], 2) }}</td>
                                        <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($row['annual'], 2) }}</td>
                                    </tr>
                                @endforeach
                                @if(count($salaryBreakup['employer_rows']) > 0)
                                <tr class="font-medium text-slate-800 bg-primary-light">
                                    <td class="px-3 py-2 text-sm">Total Earnings (CTC)</td>
                                    <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($salaryBreakup['total_earnings_monthly'], 2) }}</td>
                                    <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($salaryBreakup['total_earnings_annual'], 2) }}</td>
                                </tr>
                                @endif
                              @if(count($salaryBreakup['deduction_rows']) > 0)
                                <tr class="bg-slate-50/80">
                                    <td class="px-3 py-2 text-xs font-semibold uppercase tracking-wide  text-slate-800">Deductions</td>
                                    <th class="px-3 py-2 text-right text-xs font-medium font-semibold uppercase tracking-wide text-slate-500">Monthly</th>
                                    <th class="px-3 py-2 text-right text-xs font-medium font-semibold uppercase tracking-wide text-slate-500">Annually</th>
                                </tr>
                                @forelse($salaryBreakup['deduction_rows'] as $row)
                                    <tr>
                                        <td class="px-3 py-2 text-sm text-slate-700">{{ $row['name'] }}</td>
                                        <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums text-slate-900">₹{{ number_format($row['monthly'], 2) }}</td>
                                        <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums text-slate-900">₹{{ number_format($row['annual'], 2) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="3" class="px-3 py-2 text-sm text-slate-500">No deductions.</td>
                                    </tr>
                                @endforelse
                                <tr class="font-medium text-slate-800">
                                    <td class="px-3 py-2 text-sm">Total Deductions</td>
                                    <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($salaryBreakup['total_deductions_monthly'], 2) }}</td>
                                    <td class="whitespace-nowrap px-3 py-2 text-right text-sm tabular-nums">₹{{ number_format($salaryBreakup['total_deductions_annual'], 2) }}</td>
                                </tr>
                              @endif
                                <tr class="bg-primary-light">
                                    <td class="px-3 py-2 text-sm font-bold uppercase tracking-wide text-slate-800">Net Pay</td>
                                    <td class="whitespace-nowrap px-3 py-2 text-right text-sm font-bold uppercase tracking-wide text-slate-800">₹{{ number_format($salaryBreakup['net_monthly'], 2) }}</td>
                                    <td class="whitespace-nowrap px-3 py-2 text-right text-sm font-bold uppercase tracking-wide text-slate-800">₹{{ number_format($salaryBreakup['net_annual'], 2) }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-4 flex items-start gap-2 text-xs text-slate-500 bg-green-100 rounded p-3">
                        <svg class="mt-0.5 h-4 w-4 shrink-0 text-amber-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M12 18v-5.25m0 0a6.01 6.01 0 001.5-.189m-1.5.189a6.01 6.01 0 01-1.5-.189m3.75 7.478a12.06 12.06 0 01-4.5 0m3.75 2.383a14.406 14.406 0 01-3 0M14.25 18v-.192c0-.983.658-1.823 1.508-2.316a7.5 7.5 0 10-7.517 0c.85.493 1.509 1.333 1.509 2.316V18" />
                        </svg>
                        <p><span class="font-medium text-slate-600">Note:</span> Figures are indicative for a full month (no attendance adjustments). Salary group components are shown first, followed by statutory PF/ESI/PT as per company settings. Net pay does not include income tax or other statutory/ad-hoc deductions that may apply at payroll.</p>
                    </div>
                @else
                    <div class="mt-3 overflow-hidden rounded border border-slate-300 bg-white">
                        <table class="min-w-full">
                            <tbody>
                                <tr class="border-t border-slate-200">
                                    <td colspan="3" class="px-3 py-4 text-center text-sm text-slate-500">No salary structure available.</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                @endif

                <p class="mt-4 text-sm text-slate-600">@if($employee->salaryGroup?->name) Salary Group: <span class="font-medium text-slate-800">{{ $employee->salaryGroup?->name ?? '—' }}</span> @else No Salary Group available. @endif</p>
                <p class="mt-1 text-xs text-slate-500">Effective date reflects the latest salary history entry applied to this employee.</p>
                @if(auth()->user()->hasPermission('users_edit'))
                    <div class="flex justify-end">
                        <button type="button" @click="openReviseModal()" class="rounded bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700">Revise Salary</button>
                    </div>
                @endif

                <div x-show="openRevise" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
                    <div class="revise-salary-dialog relative z-10 w-full max-w-4xl rounded bg-white shadow-xl">
                        <div class="flex items-center justify-between bg-slate-800 px-4 py-3 text-white">
                            <h4 class="text-xl font-semibold">Revise Salary</h4>
                            <button type="button" @click="openRevise = false" class="text-2xl leading-none">&times;</button>
                        </div>
                        <form action="{{ route('employees.salary-revisions.store', $employee) }}" method="POST" class="p-5">
                            @csrf
                            <div class="mb-4 flex justify-end items-center gap-4">
                                <label class="text-lg text-slate-700">Effective Date:</label>
                                <input type="date" name="effective_date" x-model="effectiveDate" class="rounded border border-slate-300 px-2 py-1" style="width: 220px">
                                <label class="text-lg text-slate-700">Salary Group:</label>
                                <div style="width: 220px">
                                    <select x-model="selectedSalaryGroup" class="js-select2 rounded border border-slate-300 bg-white px-2 py-1" name="salary_group" required data-dropdown-parent=".revise-salary-dialog" style="width: 220px">
                                        <option value="">Select Salary Group</option>
                                        @foreach($salaryGroups as $group)
                                            <option value="{{ $group->id }}" @selected((string) $employee->salary_group_id === (string) $group->id)>
                                                {{ $group->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <table class="w-full border border-slate-300 text-base">
                                <thead class="bg-slate-100">
                                    <tr>
                                        <th class="border border-slate-300 px-3 py-2 text-left">#</th>
                                        <th class="border border-slate-300 px-3 py-2 text-right">Current Annual</th>
                                        <th class="border border-slate-300 px-3 py-2 text-right">Revised Annual</th>
                                        <th class="border border-slate-300 px-3 py-2 text-right">Revision</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="font-semibold">
                                        <td class="border border-slate-300 px-3 py-2">CTC</td>
                                        <td class="border border-slate-300 px-3 py-2 text-right" x-text="formatInr(currentCtcAnnual)"></td>
                                        <td class="border border-slate-300 px-3 py-2 text-right">
                                            <input type="number" step="1" min="0" x-model.number="ctcAnnualInput" @input="syncFromCtcInput()" @wheel.prevent class="w-32 rounded border border-slate-300 px-2 py-1 text-right">
                                        </td>
                                        <td class="border border-slate-300 px-3 py-2 text-right">
                                            <div class="inline-flex items-center gap-1">
                                                <input type="number" step="0.01" x-model="ctcPercentDraft" @change="syncFromPctInput()" @keyup.enter="syncFromPctInput()" @wheel.prevent class="w-24 rounded border border-slate-300 px-2 py-1 text-right">
                                                <span>%</span>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <input type="hidden" name="ctc_annual" :value="parseNumber(ctcAnnualInput).toFixed(2)">
                            <div class="mt-5 flex justify-end gap-3">
                                <button type="button" @click="openRevise = false" class="rounded border border-slate-300 px-5 py-2 font-semibold text-slate-700">Cancel</button>
                                <button type="submit" :disabled="!canSaveRevision" class="rounded bg-blue-600 px-5 py-2 font-semibold text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:text-slate-600">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        @endif
        @if(!empty($canViewFullEmployeeProfile))
        <div x-show="tab === 'bank'" @unless($initialTab === 'bank') x-cloak @endunless class="employee-view__details">
            <div>
                <label class="employee-view__detail-label">Account Holder Name</label>
                <div class="employee-view__detail-value">{{ $employee->account_holder_name ?? '—' }}</div>
            </div>
            <div>
                <label class="employee-view__detail-label">Bank Name</label>
                <div class="employee-view__detail-value">{{ $employee->bank_name ?? '—' }}</div>
            </div>
            <div>
                <label class="employee-view__detail-label">Account Number</label>
                <div class="employee-view__detail-value">{{ $employee->account_number ?? '—' }}</div>
            </div>
            <div>
                <label class="employee-view__detail-label">Branch Name</label>
                <div class="employee-view__detail-value">{{ $employee->branch_name ?? '—' }}</div>
            </div>
            <div>
                <label class="employee-view__detail-label">City</label>
                <div class="employee-view__detail-value">{{ $employee->city ?? '—' }}</div>
            </div>
            <div>
                <label class="employee-view__detail-label">IFSC Code</label>
                <div class="employee-view__detail-value">{{ $employee->ifsc_code ?? '—' }}</div>
            </div>
        </div>
        @endif

        <div x-show="tab === 'attendance'" @unless($initialTab === 'attendance') x-cloak @endunless>
            <p class="mb-4 text-sm text-slate-600">Recent attendance (last 30 records).</p>
            @if($attendances->isEmpty())
                <p class="text-sm text-slate-500">No attendance records.</p>
            @else
                <div class="employee-view__scroll">
                    <x-table>
                        <x-slot name="head">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Date</th>
                                <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Clock In</th>
                                <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Clock Out</th>
                                <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Duration</th>
                                <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Status</th>
                            </tr>
                        </x-slot>
                        @foreach($attendances as $a)
                            <tr>
                                <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-900">{{ $a->date?->format('M d, Y') ?? '—' }}</td>
                                <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $a->clock_in_date_time ? $a->clock_in_date_time->format('h:i A') : '—' }}</td>
                                <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $a->clock_out_date_time ? $a->clock_out_date_time->format('h:i A') : '—' }}</td>
                                <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $a->total_duration ? round($a->total_duration / 3600, 1) . ' h' : '—' }}</td>
                                <td class="whitespace-nowrap px-4 py-3 text-sm"><x-badge :status="$a->status">{{ $a->status ?? '—' }}</x-badge></td>
                            </tr>
                        @endforeach
                    </x-table>
                </div>
            @endif
            <div class="mt-4">
                <a href="{{ route('attendance.index') }}?search={{ urlencode($employee->name) }}" class="inline-flex items-center gap-1 text-sm text-primary hover:underline">
                    View all attendance <i class="bi bi-chevron-right text-[10px]"></i>
                </a>
            </div>
        </div>

        <div x-show="tab === 'leaves'" @unless($initialTab === 'leaves') x-cloak @endunless>
            <p class="mb-4 text-sm text-slate-600">Leave history.</p>
            @if($leaves->isEmpty())
                <p class="text-sm text-slate-500">No leave requests.</p>
            @else
                <x-table>
                    <x-slot name="head">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Leave Type</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Start</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">End</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Days</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Status</th>
                        </tr>
                    </x-slot>
                    @foreach($leaves as $leave)
                        <tr>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-900">{{ $leave->leaveType?->name ?? '—' }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $leave->start_date?->format('M d, Y') ?? '—' }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $leave->end_date?->format('M d, Y') ?? '—' }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $leave->total_days ?? '—' }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm"><x-badge :status="$leave->status">{{ $leave->status }}</x-badge></td>
                        </tr>
                    @endforeach
                </x-table>
            @endif
            <div class="mt-4">
                <a href="{{ route('leaves.index') }}" class="inline-flex items-center gap-1 text-sm text-primary hover:underline">
                    View all leaves <i class="bi bi-chevron-right text-[10px]"></i>
                </a>
            </div>
        </div>

        @if(!empty($canViewCompensation))
        <div x-show="tab === 'payroll'" @unless($initialTab === 'payroll') x-cloak @endunless>
            <p class="mb-4 text-sm text-slate-600">Payroll history.</p>
            @if($payrolls->isEmpty())
                <p class="text-sm text-slate-500">No payroll records.</p>
            @else
                <x-table>
                    <x-slot name="head">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Period</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Basic Salary</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Net Salary</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Status</th>
                        </tr>
                    </x-slot>
                    @foreach($payrolls as $p)
                        @php
                            $cycle = $p->payrollCycle;
                            $period = $cycle ? sprintf('%04d-%02d', $cycle->year, $cycle->month) : '—';
                        @endphp
                        <tr>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-900">{{ $period }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ number_format($p->gross_monthly ?? 0, 2) }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ number_format($p->net_monthly ?? 0, 2) }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm"><x-badge :status="$cycle?->status ?? ($p->status ?? null)">{{ $cycle?->status ?? ($p->status ?? '—') }}</x-badge></td>
                        </tr>
                    @endforeach
                </x-table>
            @endif
            <div class="mt-4"><a href="{{ route('payroll.index') }}" class="text-sm text-primary hover:underline">View payroll →</a></div>
        </div>
        @endif

        @if(!empty($canViewFullEmployeeProfile))
        <div x-show="tab === 'documents'" @unless($initialTab === 'documents') x-cloak @endunless>
            <div class="mb-4 rounded-lg border border-slate-200 bg-slate-50 p-4">
                <div class="flex flex-wrap items-center justify-between gap-2">
                    <p class="text-sm font-medium text-slate-700">
                        Mandatory documents (India): {{ $documentCompliance['completed_count'] }}/{{ $documentCompliance['total_required'] }}
                    </p>
                    <x-badge :variant="$documentCompliance['is_compliant'] ? 'success' : 'warning'">
                        {{ $documentCompliance['is_compliant'] ? 'Compliant' : 'Missing documents' }}
                    </x-badge>
                </div>
                @if(! $documentCompliance['is_compliant'])
                    <p class="mt-2 text-sm text-amber-700">
                        Missing: {{ implode(', ', $documentCompliance['missing_labels']) }}
                    </p>
                    <p class="mt-1 text-xs text-slate-500">Warning only: employee status and payroll are not blocked.</p>
                @endif
            </div>

            @if(auth()->user()->hasPermission('documents_create'))
            <form action="{{ route('employees.documents.store', $employee) }}" method="POST" enctype="multipart/form-data" class="mb-6 flex flex-wrap items-end gap-3 rounded-lg border border-slate-200 bg-slate-50 p-4">
                @csrf
                <div>
                    <label class="block text-xs font-medium text-slate-500">Document category</label>
                    <select name="type" required class="mt-1 rounded-lg border border-slate-300 px-3 py-1.5 text-sm js-select2"  >
                        <option value="">Select category</option>
                        @foreach($uploadCategories as $categoryKey => $categoryLabel)
                            <option value="{{ $categoryKey }}" {{ old('type') === $categoryKey ? 'selected' : '' }}>{{ $categoryLabel }}</option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-slate-500">File</label>
                    <input type="file" name="document" required class="mt-1 block w-full text-sm text-slate-500 file:mr-4 file:rounded-lg file:border-0 file:bg-slate-100 file:px-4 file:py-2 file:text-sm file:font-medium file:text-slate-700 hover:file:bg-slate-200">
                </div>
                <x-button type="submit" variant="primary" size="sm">Upload</x-button>
            </form>
            @endif
            @if($documents->isEmpty())
                <p class="text-sm text-slate-500">No documents uploaded for this employee.</p>
            @else
                <x-table>
                    <x-slot name="head">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Name</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Type</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Uploaded</th>
                            <th class="px-4 py-3 text-right text-xs font-medium uppercase text-slate-500">Actions</th>
                        </tr>
                    </x-slot>
                    @foreach($documents as $doc)
                        <tr>
                            <td class="whitespace-nowrap px-4 py-3 text-sm font-medium text-slate-900">{{ $doc->name }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $uploadCategories[$doc->type] ?? $doc->type ?? '—' }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $doc->created_at?->format('M d, Y') ?? '—' }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-right text-sm">
                                <a href="{{ route('documents.download', $doc) }}" target="_blank" class="btn-icon-action btn-icon-action--view" title="View" aria-label="View"><i class="bi bi-eye"></i></a>
                                @if(auth()->user()->hasPermission('documents_create')) <form action="{{ route('documents.destroy', $doc) }}?redirect={{ urlencode(route('employees.show', $employee)) }}" method="POST" class="inline" onsubmit="return confirm('Delete this document?');">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn-icon-action btn-icon-action--delete" title="Delete" aria-label="Delete"><i class="bi bi-trash3"></i></button>
                                </form>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                </x-table>
            @endif
        </div>
        @endif

        @if(!empty($canViewFullEmployeeProfile))
        <div x-show="tab === 'assets'" @unless($initialTab === 'assets') x-cloak @endunless>
            <p class="mb-4 text-sm text-slate-600">Assets assigned to this employee.</p>
            @if($assets->isEmpty())
                <p class="text-sm text-slate-500">No assets assigned.</p>
            @else
                <x-table>
                    <x-slot name="head">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Name</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Type</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Serial</th>
                            <th class="px-4 py-3 text-left text-xs font-medium uppercase text-slate-500">Status</th>
                        </tr>
                    </x-slot>
                    @foreach($assets as $asset)
                        <tr>
                            <td class="whitespace-nowrap px-4 py-3 text-sm font-medium text-slate-900">{{ $asset->name }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $asset->assetType?->name ?? '—' }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">{{ $asset->serial_number ?? '—' }}</td>
                            <td class="whitespace-nowrap px-4 py-3 text-sm"><x-badge :status="$asset->status">{{ $asset->status ?? '—' }}</x-badge></td>
                        </tr>
                    @endforeach
                </x-table>
            @endif
            <div class="mt-4"><a href="{{ route('assets.index') }}" class="text-sm text-primary hover:underline">Manage assets →</a></div>
        </div>
        @endif
            </div>
        </div>
    </div>
@endsection
