<!DOCTYPE html>
<html lang="<?= esc(service('request')->getLocale()) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= esc(lang('Backoffice.consoleTitle')) ?></title>
    <link rel="icon" type="image/png" href="<?= base_url('assets/icon.png') ?>">
    <link rel="shortcut icon" type="image/png" href="<?= base_url('assets/icon.png') ?>">
    <link rel="apple-touch-icon" href="<?= base_url('assets/icon.png') ?>">
    <script>
        (() => {
            const savedTheme = window.localStorage.getItem('quantum_backoffice_theme') || 'dark';
            document.documentElement.dataset.theme = savedTheme;
        })();
    </script>
    <script src="https://cdn.tailwindcss.com?plugins=forms,typography"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        quantum: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            200: '#bfdbfe',
                            300: '#93c5fd',
                            400: '#60a5fa',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8',
                            800: '#1e40af',
                            900: '#172554'
                        },
                        graphite: '#111827'
                    },
                    fontFamily: {
                        sans: ['IBM Plex Sans', 'ui-sans-serif', 'system-ui', 'sans-serif'],
                        display: ['Sora', 'IBM Plex Sans', 'sans-serif']
                    }
                }
            }
        };
    </script>
    <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=IBM+Plex+Mono:wght@400;500;700&family=IBM+Plex+Sans:wght@400;500;600;700&family=Sora:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?= base_url('assets/quantum-backoffice.css') ?>">
</head>
<?php
$menuSections = [
    [
        'heading' => lang('Backoffice.menuWorkspaceSection'),
        'items' => [
            'dashboard' => ['label' => lang('Backoffice.menuDashboard'), 'href' => site_url('dashboard')],
            'analytics' => ['label' => lang('Backoffice.menuAnalytics'), 'href' => site_url('analytics')],
            'organizations' => ['label' => lang('Backoffice.menuCompanies'), 'href' => site_url('organizations')],
            'privacy_settings' => ['label' => lang('Backoffice.menuPrivacySettings'), 'href' => site_url('privacy-settings')],
            'team' => ['label' => lang('Backoffice.menuTeam'), 'href' => site_url('team')],
            'sites' => ['label' => 'Parques eólicos', 'href' => site_url('sites')],
            'turbines' => ['label' => 'Turbinas', 'href' => site_url('turbines')],
            'maintenance' => ['label' => 'Manutencoes', 'href' => site_url('maintenance')],
            'blockchain' => ['label' => 'Blockchain', 'href' => site_url('blockchain')],
        ],
    ],
    [
        'heading' => lang('Backoffice.menuApiSection'),
        'items' => [
            'api_keys' => ['label' => lang('Backoffice.menuApiKeys'), 'href' => site_url('api-keys')],
            'api_docs' => ['label' => lang('Backoffice.menuApiDocs'), 'href' => site_url('api-docs')],
            'api_playground' => ['label' => lang('Backoffice.menuApiPlayground'), 'href' => site_url('api-playground')],
        ],
    ],
];

$navIcons = [
    'dashboard' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M4 13h7V4H4zM13 20h7v-9h-7zM13 11h7V4h-7zM4 20h7v-5H4z"/></svg>',
    'analytics' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M4 19h16"/><path d="M7 16V9"/><path d="M12 16V5"/><path d="M17 16v-4"/></svg>',
    'organizations' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M3 21h18"/><path d="M5 21V7l7-4 7 4v14"/><path d="M9 11h.01M15 11h.01M9 15h.01M15 15h.01"/></svg>',
    'privacy_settings' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M12 3l7 4v5c0 5-3.5 7.8-7 9-3.5-1.2-7-4-7-9V7z"/><path d="M9.5 12.5l1.7 1.7 3.3-3.7"/></svg>',
    'team' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M16 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2"/><circle cx="9.5" cy="7" r="3"/><path d="M20 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 4.13a3 3 0 0 1 0 5.74"/></svg>',
    'sites' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M12 2l7 4v5c0 5-3.5 7.8-7 9-3.5-1.2-7-4-7-9V6z"/><path d="M9 14l3-6 3 6"/><path d="M10 12h4"/></svg>',
    'turbines' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><circle cx="12" cy="12" r="1.5"/><path d="M12 13.5V21"/><path d="M13 10l6-2-2-3z"/><path d="M11 10L5 8l2-3z"/><path d="M12 10l1-6h-2z"/></svg>',
    'maintenance' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M14.7 6.3a4 4 0 0 0-5.4 5.4L3 18l3 3 6.3-6.3a4 4 0 0 0 5.4-5.4l-2.2 2.2-3.2-1 1-3.2z"/></svg>',
    'blockchain' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M7.5 7.5L12 5l4.5 2.5v5L12 15l-4.5-2.5z"/><path d="M12 15v4"/><path d="M7.5 12.5L3 15v4l4.5 2.5L12 19"/><path d="M16.5 12.5L21 15v4l-4.5 2.5L12 19"/></svg>',
    'api_keys' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><circle cx="8" cy="15" r="4"/><path d="M12 15h9"/><path d="M18 12v6"/><path d="M21 13v4"/></svg>',
    'api_docs' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M6 3h9l3 3v15H6z"/><path d="M15 3v3h3"/><path d="M9 13h6M9 17h4M9 9h6"/></svg>',
    'api_playground' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M8 8l-4 4 4 4"/><path d="M16 8l4 4-4 4"/><path d="M14 4l-4 16"/></svg>',
];
?>
<body class="theme-shell min-h-screen transition-colors duration-300">
    <div class="pointer-events-none fixed inset-0 overflow-hidden">
        <div class="qb-orb qb-orb--one"></div>
        <div class="qb-orb qb-orb--two"></div>
        <div class="qb-orb qb-orb--three"></div>
    </div>

    <div class="relative min-h-screen lg:grid lg:grid-cols-[310px_minmax(0,1fr)]">
        <aside class="theme-sidebar qb-sidebar px-5 py-5 lg:min-h-screen">
            <div class="flex flex-col gap-6">
                <div>
                    <img src="<?= base_url('assets/quantum-wordmark.svg') ?>" alt="Quantum" class="qb-brand-mark h-12 w-auto object-contain">
                    <div class="mt-4">
                        <span class="qb-label">Quantum Console</span>
                        <h1 class="mt-4 text-2xl font-semibold text-white"><?= esc(lang('Backoffice.console')) ?></h1>
                        <p class="mt-2 max-w-xs text-sm leading-6 text-slate-400"><?= esc(lang('Backoffice.consoleDescription')) ?></p>
                    </div>
                </div>

                <?php if (! empty($authUser)): ?>
                    <section class="qb-context-card rounded-[30px] p-4">
                        <div class="flex items-start justify-between gap-3">
                            <div>
                                <p class="text-[11px] font-semibold uppercase tracking-[0.26em] text-slate-500"><?= esc(lang('Backoffice.workspaceActive')) ?></p>
                                <p class="mt-2 text-lg font-semibold text-white"><?= esc($currentMembership['organization_name'] ?? lang('Backoffice.platformAdmin')) ?></p>
                                <p class="mt-1 text-xs font-semibold uppercase tracking-[0.2em] text-slate-400"><?= esc($isPlatformAdmin ? lang('Backoffice.platformAdmin') : strtoupper((string) ($currentMembership['role'] ?? 'member'))) ?></p>
                            </div>
                            <span class="qb-chip"><?= count($availableMemberships ?? []) ?: 1 ?> tenant</span>
                        </div>

                        <?php if (! empty($availableMemberships)): ?>
                            <div class="mt-4 space-y-2">
                                <?php foreach ($availableMemberships as $membership): ?>
                                    <?php $isCurrent = (int) ($currentMembership['organization_id'] ?? 0) === (int) $membership['organization_id']; ?>
                                    <a href="<?= site_url('organizations/switch/' . $membership['organization_id']) ?>" class="qb-nav-link px-3 py-3 <?= $isCurrent ? 'qb-nav-link--active' : '' ?>">
                                        <span class="min-w-0 truncate"><?= esc($membership['organization_name']) ?></span>
                                        <span class="text-[11px] uppercase tracking-[0.18em] text-slate-500"><?= esc($membership['role']) ?></span>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </section>
                <?php endif; ?>

                <nav class="space-y-5">
                    <?php foreach ($menuSections as $section): ?>
                        <div>
                            <div class="qb-nav-group-title mb-2 px-1 text-[11px] font-semibold uppercase tracking-[0.24em]"><?= esc($section['heading']) ?></div>
                            <div class="space-y-2">
                                <?php foreach ($section['items'] as $key => $item): ?>
                                    <?php $isActive = ($active ?? '') === $key; ?>
                                    <a href="<?= $item['href'] ?>" class="qb-nav-link px-3 py-3 <?= $isActive ? 'qb-nav-link--active' : '' ?>">
                                        <span class="flex items-center gap-3">
                                            <span class="qb-nav-icon"><?= $navIcons[$key] ?? $navIcons['dashboard'] ?></span>
                                            <span class="text-sm font-medium"><?= esc($item['label']) ?></span>
                                        </span>
                                        <span class="text-slate-500">/</span>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </nav>

                <div class="grid gap-2">
                    <a href="<?= site_url('blockchain') ?>" class="qb-button-secondary text-sm">Explorar rastreabilidade blockchain</a>
                    <a href="<?= site_url('audit') ?>" target="_blank" class="qb-button-secondary text-sm">Portal de auditoria</a>
                    <a href="<?= site_url('/') ?>" target="_blank" class="qb-button-secondary text-sm"><?= esc(lang('Backoffice.landing')) ?></a>
                </div>

                <?php if (! empty($authUser)): ?>
                    <div class="qb-side-card">
                        <div class="flex items-center gap-3">
                            <div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-quantum-500 to-cyan-400 text-sm font-bold text-slate-950">
                                <?= esc(strtoupper(substr((string) $authUser['name'], 0, 2))) ?>
                            </div>
                            <div class="min-w-0">
                                <p class="truncate font-semibold text-white"><?= esc($authUser['name']) ?></p>
                                <p class="truncate text-sm text-slate-400"><?= esc($authUser['email']) ?></p>
                            </div>
                        </div>
                        <div class="mt-4 grid gap-2">
                            <a href="<?= site_url('account') ?>" class="qb-button-secondary w-full text-sm"><?= esc(lang('Backoffice.myAccount')) ?></a>
                            <a href="<?= site_url('logout') ?>" class="qb-button-danger w-full text-sm"><?= esc(lang('Backoffice.signOut')) ?></a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </aside>

        <main class="px-4 py-4 sm:px-6 lg:px-8">
            <div class="mx-auto max-w-7xl">
                <header class="qb-topbar mb-6 rounded-[30px] px-5 py-5">
                    <div class="flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between">
                        <div>
                            <span class="qb-chip">Workspace Quantum</span>
                            <h2 class="mt-3 font-semibold text-white"><?= esc($title ?? lang('Backoffice.menuDashboard')) ?></h2>
                            <p class="mt-2 max-w-2xl text-sm leading-7 text-slate-400">Cockpit operacional para manutenção, auditoria, equipa e rastreabilidade técnica.</p>
                        </div>
                        <div class="flex flex-wrap items-center gap-3 text-sm">
                            <div class="qb-topbar-meta rounded-full px-4 py-2">
                                <?= esc($currentMembership['organization_name'] ?? lang('Backoffice.noActiveTenant')) ?>
                            </div>
                            <div class="qb-chip qb-chip--soft"><?= esc(date('d/m/Y')) ?></div>
                            <div class="qb-topbar-meta inline-flex items-center gap-2 rounded-full px-2 py-2">
                                <span class="px-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500"><?= esc(lang('Backoffice.language')) ?></span>
                                <?php foreach (($supportedLocales ?? ['pt', 'en', 'es']) as $locale): ?>
                                    <?php $isCurrentLocale = ($currentLocale ?? 'pt') === $locale; ?>
                                    <a href="<?= site_url('lang/' . $locale) ?>" class="<?= $isCurrentLocale ? 'qb-chip' : 'qb-chip qb-chip--soft' ?>">
                                        <?= esc($localeNames[$locale] ?? strtoupper($locale)) ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                            <button id="themeToggle" type="button" class="qb-button-secondary">
                                <span class="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500"><?= esc(lang('Backoffice.theme')) ?></span>
                                <span id="themeToggleLabel" class="ml-2"><?= esc(lang('Backoffice.themeLight')) ?></span>
                            </button>
                        </div>
                    </div>
                </header>

                <?php if (session()->getFlashdata('success')): ?>
                    <div class="qb-alert qb-alert--success mb-4"><?= esc(session()->getFlashdata('success')) ?></div>
                <?php endif; ?>

                <?php if (session()->getFlashdata('error')): ?>
                    <div class="qb-alert qb-alert--error mb-4"><?= esc(session()->getFlashdata('error')) ?></div>
                <?php endif; ?>

                <div class="space-y-6">
                    <?= $this->renderSection('content') ?>
                </div>
            </div>
        </main>
    </div>

    <script>
        (() => {
            const key = 'quantum_backoffice_theme';
            const root = document.documentElement;
            const button = document.getElementById('themeToggle');
            const label = document.getElementById('themeToggleLabel');
            if (!button || !label) {
                return;
            }

            const labels = {
                dark: '<?= esc(lang('Backoffice.themeDark'), 'js') ?>',
                light: '<?= esc(lang('Backoffice.themeLight'), 'js') ?>'
            };

            const applyTheme = (theme) => {
                root.dataset.theme = theme;
                label.textContent = labels[theme] || labels.dark;
                window.localStorage.setItem(key, theme);
            };

            applyTheme(root.dataset.theme || 'dark');

            button.addEventListener('click', () => {
                const nextTheme = root.dataset.theme === 'light' ? 'dark' : 'light';
                applyTheme(nextTheme);
            });
        })();
    </script>
</body>
</html>
