<?php
$pageTitle = 'Dashboard';
$dashboardUser = Auth::user();
$displayName = trim((string)($dashboardUser['name'] ?? 'Admin'));
$firstName = $displayName !== '' ? explode(' ', $displayName)[0] : 'Admin';
$hour = (int)date('G');
$greeting = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
$documentAttention = count($expiringDocuments ?? []);
$alertTotal = (int)($stats['temperature_alerts'] ?? 0) + (int)($stats['carrier_compliance'] ?? 0) + count($overdueInvoices ?? []) + $documentAttention + count($maintenanceDue ?? []);

$dashboardIcon = static function (string $name): string {
    $icons = [
        'load' => '<path d="M5 7h10v10H5z"/><path d="M15 10h3l2 3v4h-5z"/><circle cx="8" cy="18" r="1.7"/><circle cx="17.5" cy="18" r="1.7"/>',
        'carrier' => '<circle cx="9" cy="8" r="3"/><path d="M3 20a6 6 0 0 1 12 0M16 6a3 3 0 0 1 0 6M17 15a5 5 0 0 1 4 5"/>',
        'capacity' => '<path d="M3 7h11v10H3zM14 10h4l3 3v4h-7z"/><circle cx="7" cy="18" r="2"/><circle cx="18" cy="18" r="2"/>',
        'driver' => '<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>',
        'temperature' => '<path d="M10 14.8V5a2 2 0 0 1 4 0v9.8a4.5 4.5 0 1 1-4 0Z"/><path d="M12 9v7"/>',
        'invoice' => '<path d="M7 3h10v18l-2-1.4-2 1.4-2-1.4L9 21l-2-1.4Z"/><path d="M10 8h4M10 12h4M10 16h2"/>',
        'border' => '<path d="M12 3 5 6v5c0 4.7 2.8 8.1 7 10 4.2-1.9 7-5.3 7-10V6Z"/><path d="m9 12 2 2 4-5"/>',
        'expense' => '<path d="M6 3h12v18H6z"/><path d="M9 8h6M9 12h6M9 16h3"/>',
        'tracking' => '<circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/><circle cx="12" cy="12" r="8"/>',
        'cold' => '<path d="M12 2v20M4.2 6.5l15.6 11M19.8 6.5l-15.6 11M8 4l4 2 4-2M8 20l4-2 4 2"/>',
        'compliance' => '<path d="M12 3 5 6v5c0 4.7 2.8 8.1 7 10 4.2-1.9 7-5.3 7-10V6Z"/><path d="m9 12 2 2 4-5"/>',
        'document' => '<path d="M6 2h8l4 4v16H6z"/><path d="M14 2v5h5M9 12h6M9 16h6"/>',
        'arrow' => '<path d="M5 12h14M14 7l5 5-5 5"/>',
        'calendar' => '<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18"/>',
        'alert' => '<path d="M10.3 4.4 2.6 18a2 2 0 0 0 1.8 3h15.2a2 2 0 0 0 1.8-3L13.7 4.4a2 2 0 0 0-3.4 0Z"/><path d="M12 9v4M12 17h.01"/>',
        'activity' => '<path d="M3 12h4l2-6 4 12 2-6h6"/>',
        'plus' => '<path d="M12 5v14M5 12h14"/>',
        'map' => '<path d="m3 6 6-3 6 3 6-3v15l-6 3-6-3-6 3Z"/><path d="M9 3v15M15 6v15"/>',
    ];
    return '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">'.($icons[$name] ?? $icons['load']).'</svg>';
};
?>

<section class="dashboard-welcome">
    <div class="dashboard-welcome-copy">
        <p class="dashboard-kicker">Fleet operations overview</p>
        <h1><?= e($greeting) ?>, <?= e($firstName) ?><span aria-hidden="true">.</span></h1>
        <p>Here is what needs your attention across dispatch, carrier capacity, compliance, and finance today.</p>
        <div class="dashboard-health-row" aria-label="Operations health summary">
            <a href="<?= url('/tracking') ?>" class="health-chip"><span class="health-icon blue"><?= $dashboardIcon('tracking') ?></span><span><strong>Live tracking</strong><small>Driver location visibility</small></span></a>
            <a href="<?= url('/trailers') ?>" class="health-chip"><span class="health-icon cyan"><?= $dashboardIcon('cold') ?></span><span><strong>Cold chain</strong><small><?= (int)$stats['temperature_alerts'] === 0 ? 'All readings normal' : e((string)$stats['temperature_alerts']).' need attention' ?></small></span></a>
            <a href="<?= url('/carriers') ?>" class="health-chip"><span class="health-icon green"><?= $dashboardIcon('compliance') ?></span><span><strong>Compliance</strong><small><?= (int)$stats['carrier_compliance'] === 0 ? 'Carrier network current' : e((string)$stats['carrier_compliance']).' reviews pending' ?></small></span></a>
            <a href="<?= url('/documents') ?>" class="health-chip"><span class="health-icon purple"><?= $dashboardIcon('document') ?></span><span><strong>Documents</strong><small><?= $documentAttention ? e((string)$documentAttention).' expiring soon' : 'No expiry alerts' ?></small></span></a>
        </div>
    </div>
    <div class="dashboard-welcome-side">
        <div class="dashboard-welcome-actions">
            <a class="btn btn-primary btn-with-icon" href="<?= url('/loads/create') ?>"><?= $dashboardIcon('plus') ?><span>Book a Load</span></a>
            <a class="btn btn-white" href="<?= url('/carriers/create') ?>">Onboard Carrier</a>
        </div>
        <a class="dashboard-revenue-pill" href="<?= url('/reports') ?>"><span>Monthly dispatch fees</span><strong><?= money($stats['monthly_dispatch_fees']) ?></strong></a>
    </div>
    <div class="dashboard-route-art" aria-hidden="true"><span class="route-line route-line-one"></span><span class="route-line route-line-two"></span><span class="route-pin">●</span><span class="route-truck"><?= $dashboardIcon('capacity') ?></span></div>
</section>

<section class="dashboard-metrics" aria-label="Key performance indicators">
    <a class="metric-card metric-blue" href="<?= url('/loads') ?>"><span class="metric-icon"><?= $dashboardIcon('load') ?></span><span class="metric-content"><small>Active Loads</small><strong><?= e((string)$stats['active_loads']) ?></strong><em>Moving or pending assignment</em></span></a>
    <a class="metric-card metric-purple" href="<?= url('/carriers') ?>"><span class="metric-icon"><?= $dashboardIcon('carrier') ?></span><span class="metric-content"><small>Active Carriers</small><strong><?= e((string)$stats['active_carriers']) ?></strong><em>Approved carrier partners</em></span></a>
    <a class="metric-card metric-green" href="<?= url('/trucks') ?>"><span class="metric-icon"><?= $dashboardIcon('capacity') ?></span><span class="metric-content"><small>Available Capacity</small><strong><?= e((string)($stats['available_trucks'] + $stats['available_trailers'])) ?></strong><em><?= e((string)$stats['available_trucks']) ?> trucks · <?= e((string)$stats['available_trailers']) ?> trailers</em></span></a>
    <a class="metric-card metric-indigo" href="<?= url('/drivers') ?>"><span class="metric-icon"><?= $dashboardIcon('driver') ?></span><span class="metric-content"><small>Available Drivers</small><strong><?= e((string)$stats['available_drivers']) ?></strong><em>Ready for assignment</em></span></a>
    <a class="metric-card metric-orange" href="<?= url('/trailers') ?>"><span class="metric-icon"><?= $dashboardIcon('temperature') ?></span><span class="metric-content"><small>Temperature Alerts</small><strong><?= e((string)$stats['temperature_alerts']) ?></strong><em>Latest reefer readings</em></span></a>
    <a class="metric-card metric-emerald" href="<?= url('/invoices') ?>"><span class="metric-icon"><?= $dashboardIcon('invoice') ?></span><span class="metric-content"><small>Pending Invoices</small><strong><?= money($stats['pending_invoices']) ?></strong><em>Open receivables</em></span></a>
    <a class="metric-card metric-rose" href="<?= url('/borders') ?>"><span class="metric-icon"><?= $dashboardIcon('border') ?></span><span class="metric-content"><small>Border Attention</small><strong><?= e((string)$stats['border_attention']) ?></strong><em>Documents, queues, or holds</em></span></a>
    <a class="metric-card metric-violet" href="<?= url('/accounting/expenses') ?>"><span class="metric-icon"><?= $dashboardIcon('expense') ?></span><span class="metric-content"><small>Expense Review</small><strong><?= e((string)$stats['pending_expenses']) ?></strong><em>Waiting for approval</em></span></a>
</section>

<section class="dashboard-primary-grid">
    <article class="panel dashboard-card recent-loads-card">
        <header class="dashboard-card-header"><div><span class="section-icon blue"><?= $dashboardIcon('load') ?></span><div><h2>Recent Loads</h2><p>Latest booked and active shipments</p></div></div><a class="text-link" href="<?= url('/loads') ?>">View all loads <?= $dashboardIcon('arrow') ?></a></header>
        <div class="table-wrap dashboard-table-wrap"><table class="dashboard-load-table"><thead><tr><th>Load / Route</th><th>Carrier</th><th>Assignment</th><th>Status</th><th>Dispatch Fee</th><th aria-label="Actions"></th></tr></thead><tbody>
        <?php foreach($recentLoads as $load): ?>
            <tr>
                <td><a class="load-id" href="<?= url('/loads/edit?id='.$load['id']) ?>"><?= e($load['load_number']) ?></a><span class="route-copy"><?= e($load['pickup_location']) ?> <b>→</b> <?= e($load['delivery_location']) ?></span><?php if(!empty($load['temperature_controlled'])): ?><span class="inline-meta reefer-meta"><?= $dashboardIcon('temperature') ?> <?= e((string)$load['temperature_setpoint'].($load['temperature_unit'] ?? 'F')) ?></span><?php endif; ?></td>
                <td><strong class="cell-primary"><?= e($load['carrier_name'] ?? 'Unassigned') ?></strong><small>Carrier</small></td>
                <td><strong class="cell-primary"><?= e($load['driver_name'] ?? 'No driver') ?></strong><small>Trailer <?= e($load['trailer_number'] ?? '—') ?></small></td>
                <td><span class="badge badge-<?= status_class($load['status']) ?>"><?= e(readable_status($load['status'])) ?></span></td>
                <td><strong class="cell-primary"><?= money($load['dispatch_fee_amount'] ?? 0) ?></strong></td>
                <td><a class="row-action" href="<?= url('/loads/edit?id='.$load['id']) ?>" aria-label="Open <?= e($load['load_number']) ?>">›</a></td>
            </tr>
        <?php endforeach; ?>
        <?php if(!$recentLoads): ?><tr><td colspan="6" class="empty dashboard-empty">No loads have been added yet.</td></tr><?php endif; ?>
        </tbody></table></div>
    </article>

    <article class="panel dashboard-card workflow-card">
        <header class="dashboard-card-header"><div><span class="section-icon indigo"><?= $dashboardIcon('map') ?></span><div><h2>Operational Workflow</h2><p>Your daily dispatch sequence</p></div></div></header>
        <ol class="workflow-list">
            <li><span>1</span><div><strong>Verify capacity</strong><p>Confirm authority, insurance, drivers, equipment, and dispatch agreement.</p></div></li>
            <li><span>2</span><div><strong>Book and assign</strong><p>Capture broker rate, carrier rate, dispatch fee, route, and equipment requirements.</p></div></li>
            <li><span>3</span><div><strong>Track and protect</strong><p>Monitor GPS, stops, reefer temperatures, documents, delays, and border activity.</p></div></li>
            <li><span>4</span><div><strong>Close and collect</strong><p>Complete POD, invoicing, carrier settlement, and profitability review.</p></div></li>
        </ol>
        <div class="workflow-route" aria-hidden="true"><span></span><i></i></div>
    </article>
</section>

<section class="dashboard-secondary-grid">
    <article class="panel dashboard-card schedule-card">
        <header class="dashboard-card-header"><div><span class="section-icon blue"><?= $dashboardIcon('calendar') ?></span><div><h2>Today's Schedule</h2><p>Pickups and deliveries</p></div></div><a class="text-link" href="<?= url('/loads/calendar') ?>">View calendar <?= $dashboardIcon('arrow') ?></a></header>
        <div class="dashboard-list">
            <?php foreach($todaySchedule as $item): ?><a class="dashboard-list-item" href="<?= url('/loads/edit?id='.$item['id']) ?>"><span class="list-dot blue"></span><span><strong><?= e($item['load_number']) ?> · <?= e(readable_status($item['status'])) ?></strong><small><?= e($item['pickup_location']) ?> → <?= e($item['delivery_location']) ?></small></span><b>›</b></a><?php endforeach; ?>
            <?php if(!$todaySchedule): ?><div class="empty-state"><span class="empty-state-icon"><?= $dashboardIcon('calendar') ?></span><strong>No pickups or deliveries today</strong><p>You are all caught up. New appointments will appear here.</p></div><?php endif; ?>
        </div>
    </article>

    <article class="panel dashboard-card alerts-card">
        <header class="dashboard-card-header"><div><span class="section-icon orange"><?= $dashboardIcon('alert') ?></span><div><h2>Operational Alerts</h2><p><?= $alertTotal ?> item<?= $alertTotal === 1 ? '' : 's' ?> need attention</p></div></div><a class="text-link" href="<?= url('/notifications') ?>">View all <?= $dashboardIcon('arrow') ?></a></header>
        <div class="dashboard-list alert-list">
            <?php if($stats['temperature_alerts']): ?><a class="dashboard-list-item alert-danger" href="<?= url('/trailers') ?>"><span class="alert-symbol"><?= $dashboardIcon('temperature') ?></span><span><strong>Reefer temperature alert</strong><small><?= e((string)$stats['temperature_alerts']) ?> reading(s) outside the required range</small></span><b>›</b></a><?php endif; ?>
            <?php if($stats['carrier_compliance']): ?><a class="dashboard-list-item alert-warning" href="<?= url('/carriers') ?>"><span class="alert-symbol"><?= $dashboardIcon('compliance') ?></span><span><strong>Carrier compliance review</strong><small><?= e((string)$stats['carrier_compliance']) ?> carrier(s) require attention</small></span><b>›</b></a><?php endif; ?>
            <?php foreach(array_slice($maintenanceDue, 0, 2) as $record): ?><a class="dashboard-list-item alert-warning" href="<?= url('/maintenance') ?>"><span class="alert-symbol"><?= $dashboardIcon('alert') ?></span><span><strong>Maintenance due</strong><small><?= e($record['truck_number'] ?: $record['trailer_number'] ?: 'Equipment') ?> · <?= e($record['service_type']) ?></small></span><time><?= e(date_display($record['next_service_date'])) ?></time></a><?php endforeach; ?>
            <?php foreach(array_slice($overdueInvoices, 0, 1) as $invoice): ?><a class="dashboard-list-item alert-danger" href="<?= url('/invoices/view?id='.$invoice['id']) ?>"><span class="alert-symbol"><?= $dashboardIcon('invoice') ?></span><span><strong>Invoice <?= e($invoice['invoice_number']) ?> is overdue</strong><small><?= e($invoice['broker_name'] ?? 'Customer') ?> · <?= money($invoice['total']) ?></small></span><time><?= e(date_display($invoice['due_date'])) ?></time></a><?php endforeach; ?>
            <?php if(!$alertTotal): ?><div class="empty-state compact"><span class="empty-state-icon success"><?= $dashboardIcon('compliance') ?></span><strong>Operations are clear</strong><p>No urgent alerts right now.</p></div><?php endif; ?>
        </div>
    </article>

    <article class="panel dashboard-card activity-card">
        <header class="dashboard-card-header"><div><span class="section-icon cyan"><?= $dashboardIcon('activity') ?></span><div><h2>Recent Activity</h2><p>Latest system updates</p></div></div><a class="text-link" href="<?= url('/notifications') ?>">Audit trail <?= $dashboardIcon('arrow') ?></a></header>
        <div class="activity-list">
            <?php foreach(array_slice($activities, 0, 5) as $index => $activity): ?><div class="activity-item"><span class="activity-marker <?= $index % 3 === 0 ? 'blue' : ($index % 3 === 1 ? 'green' : 'orange') ?>"><?= $dashboardIcon($index % 3 === 0 ? 'activity' : ($index % 3 === 1 ? 'compliance' : 'document')) ?></span><span><strong><?= e(readable_status($activity['action'])) ?></strong><small><?= e($activity['user_name'] ?? 'System') ?> · <?= e(datetime_display($activity['created_at'])) ?></small></span><i></i></div><?php endforeach; ?>
            <?php if(!$activities): ?><div class="empty-state compact"><span class="empty-state-icon"><?= $dashboardIcon('activity') ?></span><strong>No recent activity</strong><p>System changes will appear here.</p></div><?php endif; ?>
        </div>
    </article>
</section>

<?php
$statusTotal = array_sum($loadStatusBreakdown ?? []);
$mapLoad = $recentLoads[0] ?? null;
$shortLocation = static function (?string $location): string {
    if (!$location) return 'Not assigned';
    $parts = array_map('trim', explode(',', $location));
    return implode(', ', array_slice($parts, 0, 2));
};
?>
<section class="dashboard-visual-grid">
    <article class="panel dashboard-card dashboard-map-panel">
        <header class="dashboard-card-header"><div><span class="section-icon cyan"><?= $dashboardIcon('map') ?></span><div><h2>Live Operations Map</h2><p><?= $mapLoad ? e($mapLoad['load_number']).' · current route overview' : 'Active route visibility' ?></p></div></div><a class="text-link" href="<?= url('/tracking') ?>">View full map <?= $dashboardIcon('arrow') ?></a></header>
        <div class="fleet-map-visual" aria-label="Current active route visualization">
            <div class="fleet-route"></div>
            <span class="fleet-map-label start"><?= e($shortLocation($mapLoad['pickup_location'] ?? null)) ?></span>
            <span class="fleet-map-label end"><?= e($shortLocation($mapLoad['delivery_location'] ?? null)) ?></span>
            <span class="fleet-map-truck"><?= $dashboardIcon('capacity') ?></span>
        </div>
    </article>
    <article class="panel dashboard-card dashboard-status-panel">
        <header class="dashboard-card-header"><div><span class="section-icon indigo"><?= $dashboardIcon('activity') ?></span><div><h2>Load Status Overview</h2><p>Current distribution across operations</p></div></div></header>
        <div class="status-overview">
            <div class="status-donut"><div class="status-donut-center"><strong><?= e((string)$statusTotal) ?></strong><span>Total loads</span></div></div>
            <div class="status-legend">
                <span><i></i>In transit <b><?= e((string)($loadStatusBreakdown['in_transit'] ?? 0)) ?></b></span>
                <span><i></i>Picked up <b><?= e((string)($loadStatusBreakdown['picked_up'] ?? 0)) ?></b></span>
                <span><i></i>Delivered <b><?= e((string)($loadStatusBreakdown['delivered'] ?? 0)) ?></b></span>
                <span><i></i>Assigned <b><?= e((string)($loadStatusBreakdown['assigned'] ?? 0)) ?></b></span>
                <span><i></i>Pending <b><?= e((string)($loadStatusBreakdown['pending'] ?? 0)) ?></b></span>
            </div>
        </div>
    </article>
</section>

<section class="panel mobile-quick-actions" aria-label="Quick actions">
    <header class="dashboard-card-header"><div><h2>Quick Actions</h2><p>Common daily tasks</p></div></header>
    <div class="quick-action-grid">
        <a href="<?= url('/loads/create') ?>"><span class="blue"><?= $dashboardIcon('plus') ?></span><strong>Book a Load</strong></a>
        <a href="<?= url('/carriers/create') ?>"><span class="purple"><?= $dashboardIcon('carrier') ?></span><strong>Onboard Carrier</strong></a>
        <a href="<?= url('/drivers/create') ?>"><span class="green"><?= $dashboardIcon('driver') ?></span><strong>Add Driver</strong></a>
        <a href="<?= url('/invoices/create') ?>"><span class="orange"><?= $dashboardIcon('invoice') ?></span><strong>Create Invoice</strong></a>
    </div>
</section>
