<?php

require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/session.php';

if (function_exists('current_user')) {
    $user = current_user();
}

$page_title = isset($page_title) ? $page_title : 'Dashboard';
$theme = isset($_SESSION['theme']) && in_array($_SESSION['theme'], ['dark', 'light'], true)
    ? $_SESSION['theme']
    : 'dark';

$is_spa = isset($_SERVER['HTTP_X_SPA_REQUEST']) && $_SERVER['HTTP_X_SPA_REQUEST'] === 'true';

if ($is_spa) {
    header('X-Page-Title: ' . rawurlencode($page_title . ' | ICYLAB OS'));
    return;
}

// 🔥 DESTRUCTOR DE CACHÉ: Obliga al celular a bajar los nuevos estilos
$v = '9.0.7';
?>
<!DOCTYPE html>
<html lang="es" data-theme="<?php echo htmlspecialchars($theme, ENT_QUOTES, 'UTF-8'); ?>">

<head>
    <script>
    // Aplica la preferencia local antes de cargar el CSS para evitar un destello del tema incorrecto.
    (function () {
        try {
            var savedTheme = localStorage.getItem('icylab-theme');
            if (savedTheme === 'dark' || savedTheme === 'light') {
                document.documentElement.setAttribute('data-theme', savedTheme);
            }
        } catch (error) {
            // El tema entregado por el servidor sigue siendo un valor seguro.
        }
    })();
    </script>
    <?php if (function_exists('csrf_token')): ?><meta name="csrf-token" content="<?php echo htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8'); ?>"><?php endif; ?>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title><?php echo htmlspecialchars($page_title, ENT_QUOTES, 'UTF-8'); ?> | ICYLAB OS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="<?php echo $theme === 'light' ? '#F2F3F5' : '#090909'; ?>">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="/assets/css/app.css?v=<?php echo $v; ?>">
    
    <link rel="icon" type="image/webp" href="/assets/img/favicon_dark.webp" media="(prefers-color-scheme: light)">
    <link rel="icon" type="image/webp" href="/assets/img/favicon_light.webp" media="(prefers-color-scheme: dark)">
    <link rel="shortcut icon" href="/assets/img/favicon_dark.webp">
    <link rel="manifest" href="/manifest.webmanifest">
</head>

<body>
<div class="app-shell">
