@extends('layouts.app')
@section('title', 'Workforce Intelligence')

@push('styles')
<link rel="stylesheet" href="{{ asset('assets/css/dashboard-final.css') }}">
<style>
    .time-grid {
        display: grid;
        grid-template-columns: 1.5fr 1fr;
        gap: 24px;
        margin-bottom: 24px;
    }
    @media (max-width: 1024px) {
        .time-grid { grid-template-columns: 1fr; }
    }
    .timer-action-group {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 12px;
        margin-top: 24px;
    }
    .stat-mini-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
        margin-top: 24px;
    }
    .stat-mini-card {
        background: rgba(255,255,255,0.02);
        border: 1px solid var(--border-color);
        border-radius: 16px;
        padding: 16px;
        display: flex;
        flex-direction: column;
        gap: 8px;
    }
</style>
@endpush

@section('content')

@php
    $actionsHtml = '
        <div style="display: flex; gap: 12px;">
            <button class="final-btn final-btn-secondary" style="font-size: 11px;"><i class="bi bi-download"></i> Export Logs</button>
            <button class="final-btn final-btn-secondary" style="font-size: 11px; color: var(--accent-color); border-color: var(--accent-soft);"><i class="bi bi-file-earmark-bar-graph"></i> Generate Report</button>
        </div>
    ';
@endphp

@include('components.page-header', [
    'title' => 'Workforce Time Intelligence',
    'description' => 'Track productivity, monitor active work sessions, manage idle time, and analyze performance metrics in real-time.',
    'breadcrumbs' => ['Home' => route('employee.dashboard'), 'Time Tracking' => '#'],
    'actions' => $actionsHtml
])

<div class="time-grid">
    <!-- Timer Control Panel -->
    <div class="final-card final-card-timer">
        <h3 class="final-card-title"><i class="bi bi-stopwatch" style="color: var(--accent-color)"></i> Active Session Controller</h3>
        
        <div style="margin-bottom: 24px;">
            <label class="final-stat-label" style="font-size: 10px;">Select Active Task</label>
            <select class="final-select" id="task_id" style="font-size: 15px; padding: 12px 20px;">
                <option value="">-- Choose a task to begin tracking --</option>
                @foreach($tasks as $task)
                    <option value="{{ $task->id }}" {{ (isset($activeLog) && $activeLog->task_id == $task->id) ? 'selected' : '' }}>{{ $task->title }}</option>
                @endforeach
            </select>
        </div>

        <div class="timer-display {{ (isset($activeLog) && $activeLog->status === 'running') ? 'timer-pulse' : '' }}" id="liveTimer">
            00:00:00
        </div>
        <div style="text-align: center; margin-top: -10px;">
            <span id="timerStatus" class="final-badge {{ (isset($activeLog) && $activeLog->status === 'running') ? 'badge-whatsapp' : 'badge-low' }}" style="font-size: 9px;">
                {{ (isset($activeLog) && $activeLog->status === 'running') ? 'LIVE SESSION ACTIVE' : 'IDLE / READY' }}
            </span>
        </div>

        <div class="timer-action-group">
            <button id="startBtn" class="final-btn timer-btn-start" style="justify-content: center;"><i class="bi bi-play-fill"></i> Start</button>
            <button id="pauseBtn" class="final-btn timer-btn-pause" style="justify-content: center;" disabled><i class="bi bi-pause-fill"></i> Pause</button>
            <button id="resumeBtn" class="final-btn timer-btn-resume" style="justify-content: center;" disabled><i class="bi bi-play-circle"></i> Resume</button>
            <button id="stopBtn" class="final-btn timer-btn-stop" style="justify-content: center;" disabled><i class="bi bi-stop-fill"></i> Stop</button>
        </div>
        
        <div id="timerMessage" style="margin-top: 16px; text-align: center; font-size: 11px; font-weight: 700; color: var(--accent-color);"></div>
    </div>

    <!-- Today's Productivity Summary -->
    <div class="final-card final-card-summary">
        <h3 class="final-card-title"><i class="bi bi-bar-chart-steps" style="color: var(--info-color)"></i> Today's Intelligence Summary</h3>
        
        <div style="display: flex; align-items: center; gap: 24px; margin-top: 20px;">
            <div class="stat-ring-container">
                <svg class="stat-ring-svg" viewBox="0 0 36 36">
                    <path class="stat-ring-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                    <path class="stat-ring-fill" stroke-dasharray="{{ $todaySummary->productivity_score ?? 0 }}, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" style="stroke: var(--info-color);" />
                </svg>
                <div class="stat-ring-value">{{ $todaySummary->productivity_score ?? 0 }}%</div>
            </div>
            <div>
                <div class="final-stat-value" style="font-size: 24px;">{{ $todaySummary->productivity_score ?? 0 }}%</div>
                <div class="final-stat-label">Productivity Excellence</div>
            </div>
        </div>

        <div class="stat-mini-grid">
            <div class="stat-mini-card">
                <span class="final-stat-label" style="font-size: 9px;">Total Tracked</span>
                <span class="final-stat-value" style="font-size: 16px;">{{ isset($todaySummary) ? gmdate('H:i:s', $todaySummary->total_tracked_seconds) : '00:00:00' }}</span>
            </div>
            <div class="stat-mini-card">
                <span class="final-stat-label" style="font-size: 9px; color: var(--danger-color);">Idle Time</span>
                <span class="final-stat-value" style="font-size: 16px;">{{ isset($todaySummary) ? gmdate('H:i:s', $todaySummary->total_idle_seconds) : '00:00:00' }}</span>
            </div>
            <div class="stat-mini-card">
                <span class="final-stat-label" style="font-size: 9px; color: var(--accent-color);">Productive</span>
                <span class="final-stat-value" style="font-size: 16px;">{{ isset($todaySummary) ? gmdate('H:i:s', $todaySummary->productive_seconds) : '00:00:00' }}</span>
            </div>
            <div class="stat-mini-card">
                <span class="final-stat-label" style="font-size: 9px; color: var(--warning-color);">Focus Score</span>
                <span class="final-stat-value" style="font-size: 16px;">{{ $todaySummary->focus_score ?? 84 }}%</span>
            </div>
        </div>
    </div>
</div>

<div class="time-grid">
    <!-- Manual Work Notes -->
    <div class="final-card final-card-notes">
        <h3 class="final-card-title"><i class="bi bi-journal-text" style="color: var(--warning-color)"></i> Manual Session Intelligence</h3>
        <p class="final-secondary-text" style="margin-top: -12px; margin-bottom: 20px;">Provide context for your active work session to improve AI-driven performance insights.</p>
        
        <textarea id="manual_notes" class="final-textarea" placeholder="Describe your current focus... e.g. 'Optimizing database queries for the reports engine and resolving cache invalidation issues.'" style="min-height: 100px;"></textarea>
        
        <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 16px;">
            <button id="saveIdleBtn" class="final-btn final-btn-secondary" style="font-size: 11px; color: var(--warning-color); border-color: rgba(245, 158, 11, 0.2);">
                <i class="bi bi-clock-history"></i> Log 5min Offline Activity
            </button>
            <button class="final-btn final-btn-primary" style="padding: 8px 20px; font-size: 12px;">Save Session Notes</button>
        </div>
    </div>

    <!-- Live Stats / Quick Tips -->
    <div class="final-card">
        <h3 class="final-card-title"><i class="bi bi-lightning"></i> Real-time Tip</h3>
        <div style="padding: 20px; background: rgba(181, 255, 59, 0.03); border: 1px solid rgba(181, 255, 59, 0.1); border-radius: 16px;">
            <p style="font-size: 13px; font-weight: 600; line-height: 1.6; margin: 0;">"Focusing on a single task for more than 45 minutes can improve your overall productivity score by <span style="color: var(--accent-color)">12%</span>."</p>
        </div>
        <div style="margin-top: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                <span class="final-stat-label" style="font-size: 10px;">Daily Goal Progress</span>
                <span style="font-size: 11px; font-weight: 800;">75%</span>
            </div>
            <div class="final-progress-bg">
                <div class="final-progress-fill" style="width: 75%"></div>
            </div>
        </div>
    </div>
</div>

<!-- Recent Logs Table -->
<div class="final-card">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <h3 class="final-card-title" style="margin-bottom: 0;"><i class="bi bi-database-check"></i> Historical Productivity Logs</h3>
        <span class="final-secondary-text" style="font-size: 10px; font-weight: 800; letter-spacing: 0.1em;">AUDITED TIME RECORDS</span>
    </div>

    <div class="final-table-container">
        <table class="final-table">
            <thead>
                <tr>
                    <th>Work Date</th>
                    <th>Gross Tracked</th>
                    <th>Idle Time</th>
                    <th>Net Productive</th>
                    <th>Efficiency</th>
                    <th style="text-align: right;">Status</th>
                </tr>
            </thead>
            <tbody>
                @forelse($dailyLogs as $log)
                <tr>
                    <td><div style="font-weight: 800; font-size: 14px;">{{ $log->work_date->format('M d, Y') }}</div></td>
                    <td><span class="final-badge badge-low">{{ gmdate('H:i:s', $log->total_tracked_seconds) }}</span></td>
                    <td><span style="color: var(--danger-color); font-weight: 700; font-size: 13px;">{{ gmdate('H:i:s', $log->total_idle_seconds) }}</span></td>
                    <td><span style="color: var(--accent-color); font-weight: 700; font-size: 13px;">{{ gmdate('H:i:s', $log->productive_seconds) }}</span></td>
                    <td>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <div class="final-progress-bg" style="width: 60px; height: 4px;">
                                <div class="final-progress-fill" style="width: {{ $log->productivity_score }}%"></div>
                            </div>
                            <span style="font-weight: 800; font-size: 12px;">{{ $log->productivity_score }}%</span>
                        </div>
                    </td>
                    <td style="text-align: right;">
                        @php
                            $statusClass = $log->productivity_score >= 80 ? 'badge-whatsapp' : ($log->productivity_score >= 50 ? 'badge-email' : 'badge-low');
                            $statusText = $log->productivity_score >= 80 ? 'Optimal' : ($log->productivity_score >= 50 ? 'Developing' : 'Critical');
                        @endphp
                        <span class="final-badge {{ $statusClass }}">{{ $statusText }}</span>
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="6">
                        <div class="final-empty-state">
                            <i class="bi bi-calendar-x"></i>
                            <p>No historical work sessions detected</p>
                        </div>
                    </td>
                </tr>
                @endforelse
            </tbody>
        </table>
    </div>
</div>

<script>
let activeLog = @json($activeLog);
let runningInterval = null;
let localSeconds = activeLog ? activeLog.total_seconds : 0;

function formatTime(seconds) {
    const h = String(Math.floor(seconds / 3600)).padStart(2, '0');
    const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
    const s = String(seconds % 60).padStart(2, '0');
    return `${h}:${m}:${s}`;
}

function refreshButtons() {
    const running = activeLog && activeLog.status === 'running';
    const paused = activeLog && activeLog.status === 'paused';
    
    document.getElementById('pauseBtn').disabled = !running;
    document.getElementById('stopBtn').disabled = !activeLog;
    document.getElementById('resumeBtn').disabled = !paused;
    document.getElementById('startBtn').disabled = activeLog && !paused;

    const timerDisplay = document.getElementById('liveTimer');
    const statusBadge = document.getElementById('timerStatus');
    
    if (running) {
        timerDisplay.classList.add('timer-pulse');
        statusBadge.textContent = 'LIVE SESSION ACTIVE';
        statusBadge.className = 'final-badge badge-whatsapp';
    } else {
        timerDisplay.classList.remove('timer-pulse');
        statusBadge.textContent = paused ? 'SESSION PAUSED' : 'IDLE / READY';
        statusBadge.className = paused ? 'final-badge badge-email' : 'final-badge badge-low';
    }
}

function startClock() {
    clearInterval(runningInterval);
    if (activeLog && activeLog.status === 'running') {
        runningInterval = setInterval(() => {
            localSeconds += 1;
            document.getElementById('liveTimer').textContent = formatTime(localSeconds);
        }, 1000);
    }
}

async function callApi(url, method, body = {}) {
    const response = await fetch(url, {
        method,
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json'
        },
        body: Object.keys(body).length ? JSON.stringify(body) : null
    });
    return response.json();
}

document.getElementById('startBtn').addEventListener('click', async () => {
    const taskId = document.getElementById('task_id').value;
    if (!taskId) {
        document.getElementById('timerMessage').textContent = 'Please select a task first.';
        return;
    }
    const data = await callApi('{{ route('time-tracking.start') }}', 'POST', { 
        task_id: taskId, 
        manual_notes: document.getElementById('manual_notes').value 
    });
    activeLog = data.time_log;
    localSeconds = activeLog.total_seconds;
    document.getElementById('timerMessage').textContent = data.message;
    refreshButtons();
    startClock();
});

document.getElementById('pauseBtn').addEventListener('click', async () => {
    if (!activeLog) return;
    const data = await callApi(`/time-tracking/${activeLog.id}/pause`, 'PATCH');
    activeLog = data.time_log;
    localSeconds = activeLog.total_seconds;
    document.getElementById('timerMessage').textContent = data.message;
    refreshButtons();
    startClock();
});

document.getElementById('resumeBtn').addEventListener('click', async () => {
    if (!activeLog) return;
    const data = await callApi(`/time-tracking/${activeLog.id}/resume`, 'PATCH');
    activeLog = data.time_log;
    document.getElementById('timerMessage').textContent = data.message;
    refreshButtons();
    startClock();
});

document.getElementById('stopBtn').addEventListener('click', async () => {
    if (!activeLog) return;
    const data = await callApi(`/time-tracking/${activeLog.id}/stop`, 'PATCH');
    activeLog = null;
    localSeconds = 0;
    document.getElementById('liveTimer').textContent = '00:00:00';
    document.getElementById('timerMessage').textContent = data.message;
    refreshButtons();
    clearInterval(runningInterval);
    setTimeout(() => window.location.reload(), 1500);
});

document.getElementById('saveIdleBtn').addEventListener('click', async () => {
    if (!activeLog) return;
    const data = await callApi('{{ route('time-tracking.idle') }}', 'POST', { 
        time_log_id: activeLog.id, 
        idle_seconds: 300, 
        reason: 'Manual idle mark' 
    });
    document.getElementById('timerMessage').textContent = data.message;
});

if (activeLog) {
    document.getElementById('liveTimer').textContent = formatTime(localSeconds);
}
refreshButtons();
startClock();
</script>
@endsection

