@extends('layouts.app')
@section('title', 'My Timesheet')
@section('breadcrumb')<span class="text-white">Timesheet</span>@endsection

@section('content')
@php
    $isFactoryEmployee = auth()->user()->role?->name === 'factory_employee';
    $isTrades          = auth()->user()->role?->name === 'trades';
    $isProcessor       = auth()->user()->role?->name === 'processor';
@endphp
<script>
    window.__timesheetJobTaskMap  = @json($jobTaskMap ?? []);
    window.__timesheetAllTaskTypes = @json($allTaskTypesJson ?? []);
</script>
<div x-data="{
    running: {{ $running ? 'true' : 'false' }},
    elapsed: '{{ $running ? $running->elapsed : '0m' }}',
    startedAt: {{ $running ? "'" . $running->started_at->toISOString() . "'" : 'null' }},
    taskId: '',
    jobId: '',
    taskErr: false,
    jobErr: false,
    isTradesUser: {{ in_array(auth()->user()->role?->name, ['trades']) ? 'true' : 'false' }},
    isFactoryEmployee: {{ $isFactoryEmployee ? 'true' : 'false' }},
    jobTaskMap: window.__timesheetJobTaskMap,
    allTaskTypes: window.__timesheetAllTaskTypes,
    get filteredTaskTypes() {
        if (!this.isFactoryEmployee) return this.allTaskTypes;
        if (!this.jobId) return [];
        const allowed = this.jobTaskMap[this.jobId] || [];
        return this.allTaskTypes.filter(t => allowed.includes(t.id));
    },
    tick() {
        if (!this.startedAt) return;
        const diff = Math.floor((Date.now() - new Date(this.startedAt)) / 1000);
        const h = Math.floor(diff/3600), m = Math.floor((diff%3600)/60), s = diff%60;
        this.elapsed = (h>0?h+'h ':'')+m+'m '+s+'s';
    },
    tryStart() {
        this.taskErr = !this.isTradesUser && !this.taskId;
        this.jobErr  = !this.jobId;
        if (this.taskErr || this.jobErr) return;
        this.running = true;
        $el.querySelector('form[data-timer-form]').submit();
    }
}" x-init="if(running) setInterval(()=>tick(), 1000)">

<div class="flex items-center justify-between mb-6">
    <div>
        <h1 class="mb-1">My Timesheet</h1>
    </div>
    <div class="flex gap-3">
        @if(in_array(auth()->user()->role?->name, ['office_admin','project_manager']))
        <a href="{{ route('timesheet.admin') }}" class="btn btn-secondary"><i class="fas fa-users"></i> All Staff</a>
        @endif
    </div>
</div>

{{-- ── Weekly Summary (non-factory-employee users including processor and trades) ── --}}
@if(!$isFactoryEmployee && !$isProcessor)
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
    <div class="stat-card">
        <div class="text-xs text-slate-400 mb-1">This Week Hours</div>
        <div class="text-2xl font-bold text-white">{{ number_format($weeklyHours, 1) }}h</div>
        <div class="text-xs text-slate-500 mt-1">{{ Carbon\Carbon::now()->startOfWeek()->format('M j') }} – {{ Carbon\Carbon::now()->endOfWeek()->format('M j') }}</div>
    </div>
    @if(auth()->user()->hourly_rate)
    <div class="stat-card">
        <div class="text-xs text-slate-400 mb-1">This Week Earnings</div>
        <div class="text-2xl font-bold text-green-400">${{ number_format($weeklyEarnings, 2) }}</div>
        <div class="text-xs text-slate-500 mt-1">@ ${{ number_format(auth()->user()->hourly_rate, 2) }}/hr</div>
    </div>
    <div class="stat-card">
        <div class="text-xs text-slate-400 mb-1">Hourly Rate</div>
        <div class="text-2xl font-bold text-blue-400">${{ number_format(auth()->user()->hourly_rate, 2) }}</div>
        <div class="text-xs text-slate-500 mt-1">per hour</div>
    </div>
    @else
    <div class="stat-card col-span-2">
        <div class="text-xs text-slate-400 mb-1">Rate</div>
        <div class="text-sm text-slate-500">No hourly rate set — contact admin</div>
    </div>
    @endif
</div>
@endif

{{-- ── Generic Timer Panel (all non-employee, non-trades, non-processor roles) ── --}}
@if(!$isFactoryEmployee && !$isTrades && !$isProcessor)
<div class="card p-5 mb-6">
    <h3 class="mb-4"><i class="fas fa-stopwatch mr-2 text-blue-400"></i>Timer</h3>

    <div x-show="running" class="flex items-center gap-6 mb-4 p-4 rounded-xl bg-green-900/20 border border-green-700">
        <div class="w-3 h-3 rounded-full bg-green-400 animate-pulse"></div>
        <div>
            <div class="text-green-300 font-semibold text-lg" x-text="elapsed">{{ $running?->elapsed ?? '0m' }}</div>
            <div class="text-green-500 text-xs">Timer running
                @if($running?->taskType) — {{ $running->taskType->name }} @endif
                @if($running?->job) — {{ $running->job->job_number }} @endif
            </div>
        </div>
        <form method="POST" action="{{ route('timesheet.stop') }}" class="ml-auto">
            @csrf
            <button type="submit" class="btn btn-warning"><i class="fas fa-pause"></i> Pause Timer</button>
        </form>
    </div>

    <div x-show="!running">
        @if((auth()->user()->role?->name !== 'trades' && $errors->has('task_type_id')) || $errors->has('job_id'))
        <div class="mb-3 p-3 rounded-lg bg-red-900/30 border border-red-700 text-sm text-red-300">
            @foreach(auth()->user()->role?->name === 'trades' ? ['job_id'] : ['task_type_id','job_id'] as $field)
                @error($field)<div>{{ $message }}</div>@enderror
            @endforeach
        </div>
        @endif
        <form method="POST" action="{{ route('timesheet.start') }}"
              class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end"
              data-timer-form>
            @csrf
            <div>
                <label class="flex items-center gap-1">Task Type <span class="text-red-400">*</span></label>
                <select name="task_type_id" class="input" x-model="taskId"
                        :class="taskErr ? 'border-red-500' : ''"
                        @change="taskErr = !taskId">
                    <option value="">— Select task —</option>
                    @foreach($taskTypes->groupBy('task_category') as $category => $tasks)
                    <optgroup label="{{ ucfirst($category) }} Tasks">
                        @foreach($tasks as $task)
                        <option value="{{ $task->id }}" {{ old('task_type_id') == $task->id ? 'selected' : '' }}>{{ $task->name }}</option>
                        @endforeach
                    </optgroup>
                    @endforeach
                </select>
                <p x-show="taskErr" class="text-xs text-red-400 mt-1">Please select a task type.</p>
            </div>
            <div>
                <label class="flex items-center gap-1">Job <span class="text-red-400">*</span></label>
                <select name="job_id" class="input" x-model="jobId"
                        :class="jobErr ? 'border-red-500' : ''"
                        @change="jobErr = !jobId">
                    <option value="">— Select job —</option>
                    @foreach($jobs as $job)
                    <option value="{{ $job->id }}" {{ old('job_id') == $job->id ? 'selected' : '' }}>{{ $job->job_number }} — {{ $job->contact?->first_name }} {{ $job->contact?->last_name }}</option>
                    @endforeach
                </select>
                <p x-show="jobErr" class="text-xs text-red-400 mt-1">Please select a job.</p>
            </div>
            <div>
                <label>Notes (optional)</label>
                <input type="text" name="notes" class="input" placeholder="e.g. Upper cabinet run" value="{{ old('notes') }}">
            </div>
            <div class="flex items-end">
                <button type="button" class="btn btn-primary w-full" @click="tryStart()">
                    <i class="fas fa-play"></i> Start Timer
                </button>
            </div>
        </form>
    </div>
</div>
@endif

{{-- ── Trades: Job-wise Timer Cards ── --}}
@if($isTrades)

@if(session('success'))
<div class="card p-4 mb-4 border-green-600 bg-green-900/20 text-green-300 flex items-center gap-2">
    <i class="fas fa-check-circle"></i> {{ session('success') }}
</div>
@endif
@if(session('error'))
<div class="card p-4 mb-4 border-red-600 bg-red-900/20 text-red-300 flex items-center gap-2">
    <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
</div>
@endif

<script>
(function() {
    var runningTradeTimers = @json(
        ($runningEntries ?? collect())->mapWithKeys(function($e) {
            return [$e->job_id . ':' => $e->started_at->toISOString()];
        })
    );
    function fmtElapsed(startIso) {
        var diff = Math.floor((Date.now() - new Date(startIso)) / 1000);
        var h = Math.floor(diff / 3600), m = Math.floor((diff % 3600) / 60), s = diff % 60;
        return (h > 0 ? h + 'h ' : '') + m + 'm ' + s + 's';
    }
    function tickTradeTimers() {
        Object.keys(runningTradeTimers).forEach(function(key) {
            var el = document.querySelector('[data-trade-timer="' + key + '"]');
            if (el) el.textContent = fmtElapsed(runningTradeTimers[key]);
        });
    }
    document.addEventListener('DOMContentLoaded', function() {
        if (Object.keys(runningTradeTimers).length > 0) { setInterval(tickTradeTimers, 1000); tickTradeTimers(); }
    });
})();
</script>

@if($jobs->count() > 0)
<div class="card mb-6">
    <div class="p-5 border-b border-slate-700 flex items-center justify-between">
        <div>
            <h3><i class="fas fa-hard-hat mr-2 text-orange-400"></i>My Assigned Jobs</h3>
            <p class="text-xs text-slate-400 mt-0.5">Start, pause, resume and complete your time for each assigned job</p>
        </div>
        <a href="{{ route('staff-invoices.index') }}" class="btn btn-secondary text-xs">
            <i class="fas fa-file-invoice-dollar"></i> My Invoices
        </a>
    </div>
    <div class="p-5 space-y-4">
        @foreach($jobs as $job)
        @php
            $tradeTimerKey = $job->id . ':';
            $tradeRunningEntry = ($runningEntries ?? collect())->where('job_id', $job->id)->first();
            $tradePausedEntry  = ($pausedEntries  ?? collect())->where('job_id', $job->id)->first();
            $isRunningNow  = $tradeRunningEntry !== null;
            $isPausedNow   = $tradePausedEntry  !== null && !$isRunningNow;
            $hasInProgress = $isRunningNow || $isPausedNow;

            $loggedMins = \App\Models\TimeEntry::where('user_id', auth()->id())
                ->where('job_id', $job->id)->whereIn('status', ['paused', 'completed'])->sum('duration_minutes');
            $runningMins    = $isRunningNow ? $tradeRunningEntry->started_at->diffInMinutes(now()) : 0;
            $totalHrs       = round(($loggedMins + $runningMins) / 60, 2);

            $uninvoicedMins = \App\Models\TimeEntry::where('user_id', auth()->id())
                ->where('job_id', $job->id)->where('status', 'completed')->whereNull('invoiced_in')->sum('duration_minutes');
            $uninvoicedHrs  = round($uninvoicedMins / 60, 2);
            $hasUninvoiced  = $uninvoicedMins > 0;

            $invoicedMins = \App\Models\TimeEntry::where('user_id', auth()->id())
                ->where('job_id', $job->id)->where('status', 'completed')->whereNotNull('invoiced_in')->sum('duration_minutes');
            $invoicedHrs  = round($invoicedMins / 60, 2);

            $isinvoicedCompleted = \App\Models\TimeEntry::where('user_id', auth()->id())->where('job_id', $job->id)->first();
            $isinvoicedthejob    = \App\Models\StaffInvoice::where('user_id', auth()->id())->where('job_id', $job->id)->count();
        @endphp
        @if($isinvoicedthejob < 1)
        <div class="rounded-xl p-4" style="background:#0f172a;border:1px solid #1e293b;">
            <div class="flex items-center gap-3 mb-3 flex-wrap">
                <div class="w-9 h-9 rounded-full bg-orange-900 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-hard-hat text-orange-400 text-xs"></i>
                </div>
                <div class="flex-1 min-w-0">
                    <div class="text-sm font-bold text-white">{{ $job->job_number }}</div>
                    <div class="text-xs text-slate-400">{{ $job->contact?->first_name }} {{ $job->contact?->last_name }}</div>
                </div>
                @if($isRunningNow)
                <span class="flex items-center gap-1 text-xs text-green-400">
                    <span class="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse inline-block"></span>
                    <span data-trade-timer="{{ $tradeTimerKey }}" class="font-mono">{{ $tradeRunningEntry->elapsed }}</span>
                </span>
                @endif
            </div>
            <div class="mb-3 flex flex-wrap gap-4 text-xs text-slate-400">
                <span>Total logged: <span class="text-white font-medium">{{ $totalHrs }}h</span></span>
                @if($hasUninvoiced)<span class="text-green-400"><i class="fas fa-clock mr-1"></i>{{ $uninvoicedHrs }}h ready for invoice</span>@endif
                @if($invoicedHrs > 0)<span class="text-blue-400"><i class="fas fa-file-invoice-dollar mr-1"></i>{{ $invoicedHrs }}h invoiced</span>@endif
                @if(auth()->user()->hourly_rate && $uninvoicedHrs > 0)
                <span class="text-amber-400">Est. ${{ number_format($uninvoicedHrs * auth()->user()->hourly_rate, 2) }} (@ ${{ number_format(auth()->user()->hourly_rate, 2) }}/hr)</span>
                @endif
            </div>
            <div class="flex gap-2 flex-wrap">
                @if($isRunningNow)
                <form method="POST" action="{{ route('timesheet.stop') }}">@csrf
                    <input type="hidden" name="job_id" value="{{ $job->id }}">
                    <button type="submit" class="btn btn-warning text-xs"><i class="fas fa-pause"></i> Pause Timer</button>
                </form>
                @elseif($isPausedNow)
                <form method="POST" action="{{ route('timesheet.resume') }}">@csrf
                    <input type="hidden" name="job_id" value="{{ $job->id }}">
                    <button type="submit" class="btn btn-secondary text-xs"><i class="fas fa-play text-green-400"></i> Resume Timer</button>
                </form>
                @else
                @if($isinvoicedCompleted?->status != 'completed')
                <form method="POST" action="{{ route('timesheet.start') }}">@csrf
                    <input type="hidden" name="job_id" value="{{ $job->id }}">
                    <button type="submit" class="btn btn-primary text-xs"><i class="fas fa-play"></i> Start Timer</button>
                </form>
                @endif
                @endif
                @if($hasInProgress)
                <form method="POST" action="{{ route('timesheet.complete-trade-job') }}"
                      onsubmit="return confirm('Mark all time for {{ addslashes($job->job_number) }} as complete?')">@csrf
                    <input type="hidden" name="job_id" value="{{ $job->id }}">
                    <button type="submit" class="btn btn-success text-xs"><i class="fas fa-check-circle"></i> Complete Job</button>
                </form>
                @endif
                @if($hasUninvoiced && !$hasInProgress)
                <form method="POST" action="{{ route('staff-invoices.request-trade-job-approval') }}"
                      onsubmit="return confirm('Send invoice approval request for job {{ addslashes($job->job_number) }} to admin?')">@csrf
                    <input type="hidden" name="job_id" value="{{ $job->id }}">
                    <button type="submit" class="btn btn-primary text-xs"><i class="fas fa-paper-plane"></i> Send for Invoice Approval</button>
                </form>
                @endif
            </div>
        </div>
        @endif
        @endforeach
    </div>
</div>
@else
<div class="card mb-6 p-6 text-center text-slate-400">
    <i class="fas fa-info-circle mr-2 text-xl mb-2 block"></i>
    No jobs are currently assigned to you.
    <div class="text-xs text-slate-500 mt-1">Contact admin to get assigned to jobs.</div>
</div>
@endif

@endif {{-- end $isTrades --}}

{{-- ══════════════════════════════════════════════════════════════
     ── Processor: Multi-Task Timer View ──
     Processor can run, pause, resume and complete multiple tasks
     simultaneously (no assignment table — free-form task + job).
     Completed entries are direct-role, so they immediately affect
     the gross profit report for each job.
     ══════════════════════════════════════════════════════════════ --}}
@if($isProcessor)

@if(session('success'))
<div class="card p-4 mb-4 border-green-600 bg-green-900/20 text-green-300 flex items-center gap-2">
    <i class="fas fa-check-circle"></i> {{ session('success') }}
</div>
@endif
@if(session('error'))
<div class="card p-4 mb-4 border-red-600 bg-red-900/20 text-red-300 flex items-center gap-2">
    <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
</div>
@endif

{{-- Live per-task timer ticker for processor (key = job_id:task_type_id) --}}
<script>
(function() {
    var runningProcessorTimers = @json(
        ($runningEntries ?? collect())->mapWithKeys(function($e) {
            return [$e->job_id . ':' . $e->task_type_id => $e->started_at->toISOString()];
        })
    );
    function fmtElapsed(startIso) {
        var diff = Math.floor((Date.now() - new Date(startIso)) / 1000);
        var h = Math.floor(diff / 3600), m = Math.floor((diff % 3600) / 60), s = diff % 60;
        return (h > 0 ? h + 'h ' : '') + m + 'm ' + s + 's';
    }
    function tickProcessorTimers() {
        Object.keys(runningProcessorTimers).forEach(function(key) {
            var el = document.querySelector('[data-task-timer="' + key + '"]');
            if (el) el.textContent = fmtElapsed(runningProcessorTimers[key]);
        });
    }
    document.addEventListener('DOMContentLoaded', function() {
        if (Object.keys(runningProcessorTimers).length > 0) {
            setInterval(tickProcessorTimers, 1000);
            tickProcessorTimers();
        }
    });
})();
</script>

{{-- Start New Task Form --}}
<div class="card p-5 mb-6">
    <h3 class="mb-1"><i class="fas fa-stopwatch mr-2 text-blue-400"></i>Start a Task Timer</h3>
    <p class="text-xs text-slate-400 mb-4">You can run multiple task timers at the same time. Each task is tracked independently per job and directly affects the gross profit report when completed.</p>
    @error('error')
    <div class="mb-3 p-3 rounded-lg bg-red-900/30 border border-red-700 text-sm text-red-300">{{ $message }}</div>
    @enderror
    <form method="POST" action="{{ route('timesheet.start') }}"
          class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
        @csrf
        <div>
            <label class="flex items-center gap-1">Task Type <span class="text-red-400">*</span></label>
            <select name="task_type_id" class="input" required>
                <option value="">— Select task —</option>
                @foreach($taskTypes as $task)
                <option value="{{ $task->id }}" {{ old('task_type_id') == $task->id ? 'selected' : '' }}>{{ $task->name }}</option>
                @endforeach
            </select>
            @error('task_type_id')<p class="text-xs text-red-400 mt-1">{{ $message }}</p>@enderror
        </div>
        <div>
            <label class="flex items-center gap-1">Job <span class="text-red-400">*</span></label>
            <select name="job_id" class="input" required>
                <option value="">— Select job —</option>
                @foreach($jobs as $job)
                <option value="{{ $job->id }}" {{ old('job_id') == $job->id ? 'selected' : '' }}>
                    {{ $job->job_number }} — {{ $job->contact?->first_name }} {{ $job->contact?->last_name }}
                </option>
                @endforeach
            </select>
            @error('job_id')<p class="text-xs text-red-400 mt-1">{{ $message }}</p>@enderror
        </div>
        <div>
            <label>Notes (optional)</label>
            <input type="text" name="notes" class="input" placeholder="e.g. Cabinet assembly" value="{{ old('notes') }}">
        </div>
        <div>
            <button type="submit" class="btn btn-primary w-full">
                <i class="fas fa-play"></i> Start Timer
            </button>
        </div>
    </form>
</div>

{{-- Running Task Cards --}}
@if(($runningEntries ?? collect())->count() > 0)
<div class="card mb-6">
    <div class="p-5 border-b border-slate-700 flex items-center gap-3">
        <h3><i class="fas fa-play-circle mr-2 text-green-400"></i>Running Timers</h3>
        <span class="badge badge-green text-xs">{{ ($runningEntries ?? collect())->count() }} active</span>
    </div>
    <div class="p-5 space-y-3">
        @foreach($runningEntries ?? collect() as $runEntry)
        @php $procTimerKey = $runEntry->job_id . ':' . $runEntry->task_type_id; @endphp
        <div class="rounded-xl p-4 flex items-center gap-4 flex-wrap" style="background:#0f172a;border:1px solid #1e293b;">
            <div class="w-9 h-9 rounded-full bg-green-900 flex items-center justify-center flex-shrink-0 animate-pulse">
                <i class="fas fa-play text-green-400 text-xs"></i>
            </div>
            <div class="flex-1 min-w-0">
                <div class="text-sm font-bold text-white">{{ $runEntry->taskType?->name ?? '—' }}</div>
                <div class="text-xs text-slate-400">{{ $runEntry->job?->job_number ?? '—' }}
                    @if($runEntry->job?->contact)· {{ $runEntry->job->contact->first_name }} {{ $runEntry->job->contact->last_name }}@endif
                </div>
            </div>
            <span class="flex items-center gap-1.5 text-green-400 text-sm font-mono">
                <span class="w-2 h-2 rounded-full bg-green-400 animate-pulse inline-block"></span>
                <span data-task-timer="{{ $procTimerKey }}">{{ $runEntry->elapsed }}</span>
            </span>
            <div class="flex gap-2 flex-wrap">
                <form method="POST" action="{{ route('timesheet.stop') }}">
                    @csrf
                    <input type="hidden" name="job_id" value="{{ $runEntry->job_id }}">
                    <input type="hidden" name="task_type_id" value="{{ $runEntry->task_type_id }}">
                    <button type="submit" class="btn btn-warning text-xs">
                        <i class="fas fa-pause"></i> Pause
                    </button>
                </form>
                <form method="POST" action="{{ route('timesheet.complete-processor-task') }}"
                      onsubmit="return confirm('Complete {{ addslashes($runEntry->taskType?->name ?? 'this task') }} on {{ addslashes($runEntry->job?->job_number ?? 'this job') }}? Time will be finalized and counted in the gross profit report.')">
                    @csrf
                    <input type="hidden" name="job_id" value="{{ $runEntry->job_id }}">
                    <input type="hidden" name="task_type_id" value="{{ $runEntry->task_type_id }}">
                    <button type="submit" class="btn btn-success text-xs">
                        <i class="fas fa-check-circle"></i> Complete
                    </button>
                </form>
            </div>
        </div>
        @endforeach
    </div>
</div>
@endif

{{-- Paused Task Cards (unique job+task combos that aren't currently running) --}}
@php
    $procRunningKeys = ($runningEntries ?? collect())
        ->mapWithKeys(fn($e) => [$e->job_id . ':' . $e->task_type_id => true]);

    $procPausedCombos = ($pausedEntries ?? collect())
        ->filter(fn($e) => !isset($procRunningKeys[$e->job_id . ':' . $e->task_type_id]))
        ->unique(fn($e) => $e->job_id . ':' . $e->task_type_id)
        ->values();
@endphp

@if($procPausedCombos->count() > 0)
<div class="card mb-6">
    <div class="p-5 border-b border-slate-700">
        <h3><i class="fas fa-pause-circle mr-2 text-yellow-400"></i>Paused Timers</h3>
        <p class="text-xs text-slate-400 mt-0.5">Resume or complete these paused tasks.</p>
    </div>
    <div class="p-5 space-y-3">
        @foreach($procPausedCombos as $pausedEntry)
        @php
            $totalPausedMins = \App\Models\TimeEntry::where('user_id', auth()->id())
                ->where('job_id', $pausedEntry->job_id)
                ->where('task_type_id', $pausedEntry->task_type_id)
                ->whereIn('status', ['paused', 'completed'])
                ->sum('duration_minutes');
            $totalPausedHrs = round($totalPausedMins / 60, 2);
        @endphp
        <div class="rounded-xl p-4 flex items-center gap-4 flex-wrap" style="background:#0f172a;border:1px solid #1e293b;">
            <div class="w-9 h-9 rounded-full bg-yellow-900 flex items-center justify-center flex-shrink-0">
                <i class="fas fa-pause text-yellow-400 text-xs"></i>
            </div>
            <div class="flex-1 min-w-0">
                <div class="text-sm font-bold text-white">{{ $pausedEntry->taskType?->name ?? '—' }}</div>
                <div class="text-xs text-slate-400">{{ $pausedEntry->job?->job_number ?? '—' }}
                    @if($pausedEntry->job?->contact)· {{ $pausedEntry->job->contact->first_name }} {{ $pausedEntry->job->contact->last_name }}@endif
                </div>
                <div class="text-xs text-yellow-400 mt-0.5">
                    {{ $totalPausedHrs }}h logged · paused {{ $pausedEntry->stopped_at?->diffForHumans() }}
                </div>
            </div>
            <div class="flex gap-2 flex-wrap">
                <form method="POST" action="{{ route('timesheet.resume') }}">
                    @csrf
                    <input type="hidden" name="job_id" value="{{ $pausedEntry->job_id }}">
                    <input type="hidden" name="task_type_id" value="{{ $pausedEntry->task_type_id }}">
                    <button type="submit" class="btn btn-secondary text-xs">
                        <i class="fas fa-play text-green-400"></i> Resume
                    </button>
                </form>
                <form method="POST" action="{{ route('timesheet.complete-processor-task') }}"
                      onsubmit="return confirm('Complete {{ addslashes($pausedEntry->taskType?->name ?? 'this task') }}? All time will be finalized and counted in the gross profit report.')">
                    @csrf
                    <input type="hidden" name="job_id" value="{{ $pausedEntry->job_id }}">
                    <input type="hidden" name="task_type_id" value="{{ $pausedEntry->task_type_id }}">
                    <button type="submit" class="btn btn-success text-xs">
                        <i class="fas fa-check-circle"></i> Complete
                    </button>
                </form>
            </div>
        </div>
        @endforeach
    </div>
</div>
@endif

{{-- Processor: no running or paused timers --}}
@if(($runningEntries ?? collect())->count() === 0 && $procPausedCombos->count() === 0)
<div class="card p-6 mb-6 text-center text-slate-500">
    <i class="fas fa-stopwatch text-3xl mb-3 block opacity-20"></i>
    <p class="text-sm">No active timers. Use the form above to start tracking time on a task.</p>
</div>
@endif

@endif {{-- end $isProcessor --}}

{{-- ── Factory Employee: Assigned Tasks (Manufacture Tab) ── --}}
@if($isFactoryEmployee && isset($assignments) && $assignments->count() > 0)
<div class="card mb-6">
    <div class="p-5 border-b border-slate-700 flex items-center justify-between">
        <h3><i class="fas fa-industry mr-2 text-yellow-400"></i>My Assigned Tasks</h3>
        <span class="text-xs text-slate-500">Job-wise task overview with progress</span>
        @if(!$statuscompleted)
        <a href="{{ route('timesheet.timesheetemployeecompleted') }}" class="btn btn-warning text-xs">Previous Completed Tasks</a>
        @endif
        @if($statuscompleted)
        <a href="{{ route('timesheet.index') }}" class="btn btn-warning text-xs">My Tasks</a>
        @endif
    </div>

    <script>
    (function() {
        var runningTimers = @json(
            ($runningEntries ?? collect())->mapWithKeys(function($e) {
                return [$e->job_id . ':' . $e->task_type_id => $e->started_at->toISOString()];
            })
        );
        function fmtElapsed(startIso) {
            var diff = Math.floor((Date.now() - new Date(startIso)) / 1000);
            var h = Math.floor(diff / 3600), m = Math.floor((diff % 3600) / 60), s = diff % 60;
            return (h > 0 ? h + 'h ' : '') + m + 'm ' + s + 's';
        }
        function tickAll() {
            Object.keys(runningTimers).forEach(function(key) {
                var el = document.querySelector('[data-task-timer="' + key + '"]');
                if (el) el.textContent = fmtElapsed(runningTimers[key]);
            });
        }
        document.addEventListener('DOMContentLoaded', function() {
            if (Object.keys(runningTimers).length > 0) { setInterval(tickAll, 1000); tickAll(); }
        });
    })();
    </script>

    <div class="p-5 space-y-4">
        @foreach($assignments->groupBy('job_id') as $jobId => $jobAssignments)
        @php $jobObj = $jobAssignments->first()->job; @endphp
        <div class="rounded-xl p-4" style="background:#0f172a;border:1px solid #1e293b;">
            <div class="flex items-center gap-3 mb-3">
                <div class="w-8 h-8 rounded-full bg-blue-900 flex items-center justify-center">
                    <i class="fas fa-briefcase text-blue-400 text-xs"></i>
                </div>
                <div>
                    <div class="text-sm font-bold text-white">{{ $jobObj?->job_number ?? 'J-?' }}</div>
                    <div class="text-xs text-slate-400">{{ $jobObj?->contact?->first_name }} {{ $jobObj?->contact?->last_name }}</div>
                </div>
            </div>
            <div class="space-y-3">
                @foreach($jobAssignments as $assignment)
                @php
                    $loggedMins = \App\Models\TimeEntry::where('user_id', $assignment->user_id)
                        ->where('job_id', $assignment->job_id)
                        ->where('task_type_id', $assignment->task_type_id)
                        ->whereIn('status', ['paused','completed'])->sum('duration_minutes');

                    $runningEntryForTask = ($runningEntries ?? collect())
                        ->where('job_id', $assignment->job_id)
                        ->where('task_type_id', $assignment->task_type_id)->first();

                    $runningMins = $runningEntryForTask ? $runningEntryForTask->started_at->diffInMinutes(now()) : 0;
                    $loggedHrs = round(($loggedMins + $runningMins) / 60, 2);
                    $pct = ($assignment->allocated_hours > 0) ? min(100, round(($loggedHrs / $assignment->allocated_hours) * 100, 1)) : null;
                    $isRunningNow = $runningEntryForTask !== null;
                    $isPaused = isset($pausedEntries)
                        && $pausedEntries->where('job_id', $assignment->job_id)->where('task_type_id', $assignment->task_type_id)->count() > 0
                        && !$isRunningNow;
                    $statusLabel = $assignment->task_status ?? 'pending';
                    $statusBadge = match($statusLabel) {
                        'completed'   => 'badge-green',
                        'in_progress' => 'badge-blue',
                        'paused'      => 'badge-yellow',
                        default       => 'badge-gray',
                    };
                    $timerKey = $assignment->job_id . ':' . $assignment->task_type_id;
                @endphp
                <div class="rounded-lg p-3" style="background:#1e293b;border:1px solid #2d3748;">
                    <div class="flex items-center gap-2 flex-wrap mb-2">
                        <i class="fas fa-tasks text-xs text-blue-400"></i>
                        <span class="text-sm font-medium text-white">{{ $assignment->taskType?->name ?? '—' }}</span>
                        <span class="badge {{ $statusBadge }} text-xs">{{ ucfirst(str_replace('_',' ', $statusLabel)) }}</span>
                        @if($isRunningNow)
                        <span class="flex items-center gap-1 text-xs text-green-400 ml-1">
                            <span class="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse inline-block"></span>
                            Running — <span data-task-timer="{{ $timerKey }}" class="font-mono">{{ $runningEntryForTask->elapsed }}</span>
                        </span>
                        @endif
                        @if($assignment->allocated_hours)
                        <span class="text-xs text-slate-400 ml-auto">Allocated: <span class="text-white">{{ $assignment->allocated_hours }}h</span></span>
                        @endif
                    </div>
                    @if($assignment->allocated_hours)
                    <div class="mb-3">
                        <div class="flex justify-between text-xs text-slate-400 mb-1">
                            <span>{{ $loggedHrs }}h logged{{ $isRunningNow ? ' (timer running)' : '' }}</span>
                            <span class="{{ $pct !== null && $pct >= 100 ? 'text-green-400 font-bold' : ($pct >= 60 ? 'text-yellow-400' : 'text-slate-400') }}">
                                {{ $pct !== null ? $pct.'%' : '—' }}
                            </span>
                        </div>
                        <div class="h-2 rounded-full bg-slate-700">
                            <div class="h-2 rounded-full transition-all {{ $pct !== null && $pct >= 100 ? 'bg-green-500' : ($pct >= 60 ? 'bg-yellow-500' : 'bg-blue-500') }}"
                                 style="width: {{ $pct ?? 0 }}%"></div>
                        </div>
                    </div>
                    @else
                    <div class="mb-3 text-xs text-slate-500">{{ $loggedHrs }}h logged — no allocated hours set</div>
                    @endif
                    @if($assignment->task_status !== 'completed')
                    <div class="flex gap-2 flex-wrap">
                        @if(!$isRunningNow)
                        <form method="POST" action="{{ route('timesheet.resume') }}">@csrf
                            <input type="hidden" name="job_id" value="{{ $assignment->job_id }}">
                            <input type="hidden" name="task_type_id" value="{{ $assignment->task_type_id }}">
                            <button type="submit" class="btn btn-secondary text-xs">
                                <i class="fas fa-play text-green-400"></i>
                                {{ $isPaused ? 'Resume Timer' : 'Start Timer' }}
                            </button>
                        </form>
                        @else
                        <form method="POST" action="{{ route('timesheet.stop') }}">@csrf
                            <input type="hidden" name="job_id" value="{{ $assignment->job_id }}">
                            <input type="hidden" name="task_type_id" value="{{ $assignment->task_type_id }}">
                            <button type="submit" class="btn btn-warning text-xs"><i class="fas fa-pause"></i> Pause Timer</button>
                        </form>
                        @endif
                        <form method="POST" action="{{ route('timesheet.complete-task') }}"
                              onsubmit="return confirm('Mark this task as completed? This will finalize all time entries and include them in the gross profit report.')">@csrf
                            <input type="hidden" name="assignment_id" value="{{ $assignment->id }}">
                            <button type="submit" class="btn btn-success text-xs"><i class="fas fa-check-circle"></i> Complete Task</button>
                        </form>
                    </div>
                    @else
                    <div class="flex items-center gap-2 text-xs text-green-400">
                        <i class="fas fa-check-circle"></i> Task completed — hours included in gross profit report
                    </div>
                    @endif
                </div>
                @endforeach
            </div>
        </div>
        @endforeach
    </div>
</div>
@else
@if($isFactoryEmployee)
<div class="card mb-6">
    <div class="p-5 text-center text-slate-400">
        <i class="fas fa-info-circle mr-2"></i>
        No assigned tasks at the moment.
        <a href="{{ route('timesheet.timesheetemployeecompleted') }}" class="btn btn-warning text-xs">Previous Completed Tasks</a>
    </div>
</div>
@endif
@endif

{{-- ── Paused timers (other non-employee, non-trades, non-processor roles) ── --}}
@if(!$isFactoryEmployee && !$isTrades && !$isProcessor && isset($pausedEntries) && $pausedEntries->count() > 0)
<div class="card mb-6">
    <div class="p-5 border-b border-slate-700">
        <h3><i class="fas fa-pause-circle mr-2 text-yellow-400"></i>Paused Timers</h3>
        <p class="text-xs text-slate-400 mt-0.5">These timers are paused. Resume to continue counting time.</p>
    </div>
    <div class="divide-y divide-slate-700/50">
        @foreach($pausedEntries as $paused)
        <div class="p-4 flex items-center gap-4">
            <div class="w-8 h-8 rounded-full bg-yellow-900 flex items-center justify-center flex-shrink-0">
                <i class="fas fa-pause text-yellow-400 text-xs"></i>
            </div>
            <div class="flex-1">
                <div class="text-sm font-medium text-white">{{ $paused->taskType?->name ?? '—' }}</div>
                <div class="text-xs text-slate-400">{{ $paused->job?->job_number ?? '—' }} · Paused {{ $paused->stopped_at?->diffForHumans() }}</div>
                <div class="text-xs text-yellow-400 mt-0.5">{{ $paused->elapsed }} recorded so far</div>
            </div>
            <form method="POST" action="{{ route('timesheet.resume') }}">
                @csrf
                <input type="hidden" name="job_id" value="{{ $paused->job_id }}">
                <input type="hidden" name="task_type_id" value="{{ $paused->task_type_id }}">
                <button type="submit" class="btn btn-secondary text-xs">
                    <i class="fas fa-play text-green-400"></i> Resume
                </button>
            </form>
        </div>
        @endforeach
    </div>
</div>
@endif

{{-- ── Invoice CTA (hourly roles that need invoice approval, excluding direct roles) ── --}}
@php $directRoles = ['factory_employee', 'processor', 'lead_installer', 'trades']; @endphp
@if(auth()->user()->hourly_rate && !in_array(auth()->user()->role?->name, $directRoles))
<div class="mt-4 card p-4" x-data="{ showReqModal: false }">
    <div class="flex items-center justify-between">
        <div>
            <div class="text-sm text-white font-medium">Ready to be invoiced?</div>
            <div class="text-xs text-slate-400">Request invoice approval to notify admin &amp; accounts for your time entries.</div>
        </div>
        <div class="flex gap-2">
            <button @click="showReqModal = true" class="btn btn-primary text-sm">
                <i class="fas fa-paper-plane"></i> Request Approval
            </button>
            <a href="{{ route('staff-invoices.index') }}" class="btn btn-secondary text-sm">
                <i class="fas fa-file-invoice-dollar"></i> My Invoices
            </a>
        </div>
    </div>
    <div x-show="showReqModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60" style="display:none">
        <div class="card p-6 w-full max-w-md mx-4">
            <h3 class="mb-2">Request Invoice Approval</h3>
            <p class="text-sm text-slate-400 mb-4">Select your pay period. Admin &amp; accounts will be notified to generate and approve your invoice.</p>
            <form method="POST" action="{{ route('staff-invoices.request-approval') }}">
                @csrf
                <div class="space-y-4">
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label>Period Start</label>
                            <input type="date" name="period_start" class="input" required value="{{ \Carbon\Carbon::now()->startOfWeek()->toDateString() }}">
                        </div>
                        <div>
                            <label>Period End</label>
                            <input type="date" name="period_end" class="input" required value="{{ \Carbon\Carbon::now()->toDateString() }}">
                        </div>
                    </div>
                    <div>
                        <label>Notes (optional)</label>
                        <textarea name="notes" class="input" rows="2" placeholder="Any notes for admin..."></textarea>
                    </div>
                    <div class="flex gap-3">
                        <button type="submit" class="btn btn-primary flex-1"><i class="fas fa-paper-plane"></i> Send Request</button>
                        <button type="button" @click="showReqModal=false" class="btn btn-secondary flex-1">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
@endif

</div>
@endsection
