<?php

declare(strict_types=1);

function render_header(string $titleKey, array $options = []): void
{
    $layout = $options['layout'] ?? 'public';
    $showNav = $options['nav'] ?? true;
    $currentPage = $options['page'] ?? '';
    $pageTitle = __($titleKey);
    $locale = current_locale();
    $bodyClass = trim(($options['body_class'] ?? '') . ' ' . (!empty($options['hide_lang_switcher']) ? 'hide-global-lang' : ''));
    ?>
<!DOCTYPE html>
<html lang="<?= e($locale) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow, noarchive, nosnippet">
    <meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet">
    <title><?= e($pageTitle) ?> | <?= e(__('app_name')) ?></title>
    <base href="<?= e(app_base_url() . '/') ?>">
    <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=Inter:wght@400;500;600;700;800&family=Plus+Jakarta+Sans:wght@600;700;800&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/flowbite@2.5.2/dist/flowbite.min.css" rel="stylesheet">
    <link rel="stylesheet" href="<?= e(app_asset('css/style.css')) ?>">
    <link rel="stylesheet" href="assets/css/style.css">
    <script>window.KARVI_BASE=<?= json_encode(app_base_path(), JSON_UNESCAPED_SLASHES) ?>;</script>
    <script>
        window.karviPath=function(p){p=(p||'/').charAt(0)==='/'?p:'/'+p;var b=window.KARVI_BASE||'';return b+(p==='/'?'':p);};
        window.karviAsset=function(p){return window.karviPath('/assets/'+(p||'').replace(/^\//,''));};
    </script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        karvi: {
                            50: '#fafafa', 100: '#f4f4f5', 200: '#e4e4e7', 300: '#d4d4d8',
                            400: '#a1a1aa', 500: '#71717a', 600: '#52525b', 700: '#3f3f46',
                            800: '#27272a', 900: '#18181b', 950: '#0a0a0a',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        display: ['Plus Jakarta Sans', 'Inter', 'sans-serif'],
                    }
                }
            }
        };
    </script>
</head>
<body class="bg-karvi-50 text-karvi-950 font-sans antialiased min-h-screen flex flex-col<?= $bodyClass !== '' ? ' ' . e($bodyClass) : '' ?>">

<?php if (empty($options['hide_lang_switcher'])): ?>
<?php render_lang_switcher(); ?>
<?php endif; ?>

<?php if ($layout === 'admin' && $showNav && auth_check()): ?>
<div class="flex min-h-screen">
    <aside id="sidebar" class="fixed inset-y-0 left-0 z-40 w-72 -translate-x-full lg:translate-x-0 transition-transform bg-karvi-950 text-white border-r border-karvi-800">
        <div class="flex flex-col h-full">
            <div class="p-6 border-b border-karvi-800">
                <div class="flex items-center gap-3">
                    <div class="w-11 h-11 rounded-2xl bg-white text-karvi-950 flex items-center justify-center shrink-0">
                        <span class="material-symbols-rounded text-2xl">handshake</span>
                    </div>
                    <div class="min-w-0">
                        <p class="font-display font-bold text-sm leading-tight truncate"><?= e(__('app_short')) ?></p>
                        <p class="text-[11px] text-karvi-400 truncate"><?= e(__('app_tagline')) ?></p>
                    </div>
                </div>
            </div>
            <nav class="flex-1 p-4 space-y-1">
                <a href="<?= e(app_path('/admin/dashboard')) ?>" class="sidebar-link <?= $currentPage === 'dashboard' ? 'active' : '' ?>">
                    <span class="material-symbols-rounded">dashboard</span>
                    <?= e(__('nav_dashboard')) ?>
                </a>
                <a href="<?= e(app_path('/admin/create')) ?>" class="sidebar-link <?= $currentPage === 'create' ? 'active' : '' ?>">
                    <span class="material-symbols-rounded">note_add</span>
                    <?= e(__('nav_new_contract')) ?>
                </a>
                <a href="<?= e(app_path('/admin/database')) ?>" class="sidebar-link <?= $currentPage === 'database' ? 'active' : '' ?>">
                    <span class="material-symbols-rounded">database</span>
                    <?= e(__('nav_database')) ?>
                </a>
                <a href="<?= e(app_path('/admin/website')) ?>" class="sidebar-link <?= in_array($currentPage, ['website', 'website_create'], true) ? 'active' : '' ?>">
                    <span class="material-symbols-rounded">language</span>
                    <?= e(__('nav_karvi_website')) ?>
                </a>
                <a href="<?= e(app_path('/admin/pos')) ?>" class="sidebar-link <?= in_array($currentPage, ['pos', 'pos_create'], true) ? 'active' : '' ?>">
                    <span class="material-symbols-rounded">point_of_sale</span>
                    <?= e(__('nav_karvi_pos')) ?>
                </a>
            </nav>
            <div class="p-4 border-t border-karvi-800">
                <div class="flex items-center gap-3 px-3 py-2 mb-3">
                    <div class="w-9 h-9 rounded-full bg-karvi-800 flex items-center justify-center">
                        <span class="material-symbols-rounded text-lg">person</span>
                    </div>
                    <div>
                        <p class="text-sm font-medium">Admin</p>
                        <p class="text-xs text-karvi-400"><?= e(__('role_admin')) ?></p>
                    </div>
                </div>
                <a href="<?= e(app_path('/admin/logout')) ?>" class="sidebar-link text-red-300 hover:!bg-red-950 hover:!text-red-200">
                    <span class="material-symbols-rounded">logout</span>
                    <?= e(__('nav_sign_out')) ?>
                </a>
            </div>
        </div>
    </aside>
    <div id="sidebar-backdrop" class="fixed inset-0 z-30 bg-karvi-950/60 backdrop-blur-sm hidden lg:hidden"></div>

    <button id="sidebarToggle" type="button" class="mobile-nav-fab lg:hidden" aria-label="Menu">
        <span class="material-symbols-rounded">menu</span>
    </button>

    <div class="flex-1 lg:ml-72 flex flex-col min-h-screen">
        <main class="flex-1 px-4 sm:px-8 py-8 pt-20 lg:pt-8">

<?php elseif ($layout === 'auth'): ?>
<div class="min-h-screen grid lg:grid-cols-2">
    <div class="hidden lg:flex flex-col justify-between bg-karvi-950 text-white p-12 relative overflow-hidden">
        <div class="absolute inset-0 opacity-[0.03]" style="background-image: radial-gradient(circle at 1px 1px, white 1px, transparent 0); background-size: 32px 32px;"></div>
        <div class="relative">
            <div class="w-14 h-14 rounded-2xl bg-white text-karvi-950 flex items-center justify-center mb-8">
                <span class="material-symbols-rounded text-3xl">handshake</span>
            </div>
            <h1 class="font-display font-extrabold text-4xl xl:text-5xl leading-tight mb-4"><?= e(__('app_name')) ?></h1>
            <p class="text-karvi-400 text-lg max-w-md leading-relaxed"><?= e(__('auth_hero_desc')) ?></p>
        </div>
        <div class="relative space-y-6">
            <div class="flex items-start gap-4">
                <div class="w-10 h-10 rounded-xl bg-karvi-800 flex items-center justify-center shrink-0">
                    <span class="material-symbols-rounded">description</span>
                </div>
                <div>
                    <p class="font-semibold"><?= e(__('auth_feature_contracts')) ?></p>
                    <p class="text-sm text-karvi-400"><?= e(__('auth_feature_contracts_desc')) ?></p>
                </div>
            </div>
            <div class="flex items-start gap-4">
                <div class="w-10 h-10 rounded-xl bg-karvi-800 flex items-center justify-center shrink-0">
                    <span class="material-symbols-rounded">draw</span>
                </div>
                <div>
                    <p class="font-semibold"><?= e(__('auth_feature_signing')) ?></p>
                    <p class="text-sm text-karvi-400"><?= e(__('auth_feature_signing_desc')) ?></p>
                </div>
            </div>
        </div>
    </div>
    <div class="flex flex-col min-h-screen">
        <main class="flex-1 flex items-center justify-center p-6 sm:p-12 pt-24 sm:pt-12">

<?php else: ?>
<main class="flex-1 max-w-5xl w-full mx-auto px-4 sm:px-6 py-8 sm:py-12 pt-24">

<?php endif;
}

function render_footer(array $options = []): void
{
    $layout = $options['layout'] ?? 'public';
    $year = date('Y');
    $extraScripts = $options['scripts'] ?? [];

    if ($layout === 'admin'): ?>
        </main>
        <footer class="px-4 sm:px-8 py-5 border-t border-karvi-200 text-center text-xs text-karvi-500">
            &copy; <?= $year ?> <?= e(__('app_name')) ?>
        </footer>
    </div>
</div>
    <?php elseif ($layout === 'auth'): ?>
        </main>
        <footer class="py-4 text-center text-xs text-karvi-400">
            &copy; <?= $year ?> <?= e(__('app_name')) ?>
        </footer>
    </div>
</div>
    <?php else: ?>
</main>
<footer class="border-t border-karvi-200 mt-8">
    <div class="max-w-5xl mx-auto px-4 sm:px-6 py-6 text-center text-xs text-karvi-500">
        &copy; <?= $year ?> <?= e(__('app_name')) ?> &mdash; <?= e(__('footer_rights')) ?>
    </div>
</footer>
    <?php endif; ?>

<?php render_i18n_script(); ?>
<script src="https://cdn.jsdelivr.net/npm/flowbite@2.5.2/dist/flowbite.min.js"></script>
<script src="<?= e(app_asset('js/app.js')) ?>"></script>
<script src="assets/js/app.js"></script>
<?php foreach ($extraScripts as $script): ?>
<script src="<?= e(app_public_script($script)) ?>"></script>
<?php endforeach; ?>
</body>
</html>
    <?php
}

function render_flash(): void
{
    auth_start();
    if (empty($_SESSION['flash'])) {
        return;
    }
    $flash = $_SESSION['flash'];
    unset($_SESSION['flash']);
    $isError = ($flash['type'] ?? '') === 'error';
    $message = $flash['message'] ?? '';
    if (!empty($flash['message_key'])) {
        $message = __($flash['message_key'], $flash['replace'] ?? []);
    }
    ?>
<div class="mb-6 flex items-start gap-3 p-4 rounded-2xl border <?= $isError ? 'bg-karvi-950 text-white border-karvi-950' : 'bg-white border-karvi-200 shadow-soft' ?> animate-fade-in">
    <span class="material-symbols-rounded shrink-0 mt-0.5"><?= $isError ? 'error' : 'check_circle' ?></span>
    <p class="text-sm font-medium"><?= e($message) ?></p>
</div>
    <?php
}

function set_flash(string $messageOrKey, string $type = 'success', bool $isKey = false, array $replace = []): void
{
    auth_start();
    if ($isKey) {
        $_SESSION['flash'] = ['message_key' => $messageOrKey, 'type' => $type, 'replace' => $replace];
    } else {
        $_SESSION['flash'] = ['message' => $messageOrKey, 'type' => $type];
    }
}

function stat_card(string $labelKey, string $value, string $icon, ?string $valueId = null): void
{
    ?>
<div class="stat-card group">
    <div class="flex items-start justify-between">
        <div>
            <p class="text-xs font-medium text-karvi-500 uppercase tracking-wider mb-1"><?= e(__($labelKey)) ?></p>
            <p class="font-display font-bold text-3xl text-karvi-950"<?= $valueId ? ' id="' . e($valueId) . '"' : '' ?>><?= e($value) ?></p>
        </div>
        <div class="w-12 h-12 rounded-2xl bg-karvi-950 text-white flex items-center justify-center group-hover:scale-105 transition-transform">
            <span class="material-symbols-rounded"><?= e($icon) ?></span>
        </div>
    </div>
</div>
    <?php
}

function page_heading(string $titleKey, string $subtitleKey = '', ?string $actionUrl = null, string $actionLabelKey = '', bool $compact = false): void
{
    $titleClass = $compact
        ? 'font-display font-bold text-xl sm:text-2xl text-karvi-950 tracking-tight'
        : 'font-display font-bold text-2xl sm:text-3xl text-karvi-950 tracking-tight';
    $subtitleClass = $compact
        ? 'text-karvi-500 mt-1 text-xs sm:text-sm'
        : 'text-karvi-500 mt-1.5 text-sm sm:text-base';
    $wrapClass = $compact ? 'mb-6' : 'mb-8';
    ?>
<div class="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 <?= e($wrapClass) ?>">
    <div>
        <h2 class="<?= e($titleClass) ?>"><?= e(__($titleKey)) ?></h2>
        <?php if ($subtitleKey): ?>
        <p class="<?= e($subtitleClass) ?>"><?= e(__($subtitleKey)) ?></p>
        <?php endif; ?>
    </div>
    <?php if ($actionUrl && $actionLabelKey): ?>
    <a href="<?= e(app_path($actionUrl)) ?>" class="btn-primary shrink-0">
        <span class="material-symbols-rounded">add</span>
        <?= e(__($actionLabelKey)) ?>
    </a>
    <?php endif; ?>
</div>
    <?php
}
