<?php
/**
 * Configurações do SaaS - Super Admin
 */
require_once __DIR__ . '/../../../includes/config.php';

if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

$superAdmin = getSuperAdmin();
$pdo = getDB();

function getSetting($pdo, $key, $default = '') {
    $stmt = $pdo->prepare("SELECT setting_value FROM saas_settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    $result = $stmt->fetchColumn();
    return $result !== false ? $result : $default;
}

function saveSetting($pdo, $key, $value) {
    $stmt = $pdo->prepare("UPDATE saas_settings SET setting_value = ? WHERE setting_key = ?");
    return $stmt->execute([$value, $key]);
}

$settings = [];
$settingsResult = $pdo->query("SELECT setting_key, setting_value FROM saas_settings");
while ($row = $settingsResult->fetch()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_profile') {
        $name = trim($_POST['name'] ?? '');
        if (empty($name)) {
            $message = 'O nome é obrigatório.';
            $messageType = 'error';
        } else {
            $stmt = $pdo->prepare("UPDATE super_admins SET name = ? WHERE id = ?");
            if ($stmt->execute([$name, $superAdmin['id']])) {
                $superAdmin['name'] = $name;
                $message = 'Perfil atualizado com sucesso!';
                $messageType = 'success';
            } else {
                $message = 'Erro ao atualizar perfil.';
                $messageType = 'error';
            }
        }
    } elseif ($action === 'update_password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        if (empty($currentPassword) or empty($newPassword) or empty($confirmPassword)) {
            $message = 'Todos os campos de senha são obrigatórios.';
            $messageType = 'error';
        } elseif (strlen($newPassword) < 6) {
            $message = 'A nova senha deve ter pelo menos 6 caracteres.';
            $messageType = 'error';
        } elseif ($newPassword !== $confirmPassword) {
            $message = 'As senhas não conferem.';
            $messageType = 'error';
        } elseif (!password_verify($currentPassword, $superAdmin['password_hash'])) {
            $message = 'Senha atual incorreta.';
            $messageType = 'error';
        } else {
            $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE super_admins SET password_hash = ? WHERE id = ?");
            if ($stmt->execute([$newHash, $superAdmin['id']])) {
                $message = 'Senha alterada com sucesso!';
                $messageType = 'success';
            } else {
                $message = 'Erro ao alterar senha.';
                $messageType = 'error';
            }
        }
    } elseif ($action === 'update_settings') {
        $saasName = trim($_POST['saas_name'] ?? '');
        $trialDays = intval($_POST['trial_days'] ?? 14);
        $supportEmail = trim($_POST['support_email'] ?? '');
        $supportPhone = trim($_POST['support_phone'] ?? '');
        $maxProductsTrial = intval($_POST['max_products_trial'] ?? 50);
        $maxProductsBasic = intval($_POST['max_products_basic'] ?? 500);
        $currency = trim($_POST['currency'] ?? 'BRL');
        $timezone = trim($_POST['timezone'] ?? 'America/Sao_Paulo');

        if (empty($saasName)) {
            $message = 'O nome do SaaS é obrigatório.';
            $messageType = 'error';
        } elseif ($trialDays < 0 or $trialDays > 90) {
            $message = 'Os dias de trial devem estar entre 0 e 90.';
            $messageType = 'error';
        } elseif (!empty($supportEmail) and !filter_var($supportEmail, FILTER_VALIDATE_EMAIL)) {
            $message = 'Email de suporte inválido.';
            $messageType = 'error';
        } else {
            saveSetting($pdo, 'saas_name', $saasName);
            saveSetting($pdo, 'trial_days', $trialDays);
            saveSetting($pdo, 'support_email', $supportEmail);
            saveSetting($pdo, 'support_phone', $supportPhone);
            saveSetting($pdo, 'max_products_trial', $maxProductsTrial);
            saveSetting($pdo, 'max_products_basic', $maxProductsBasic);
            saveSetting($pdo, 'currency', $currency);
            saveSetting($pdo, 'timezone', $timezone);

            $settings['saas_name'] = $saasName;
            $settings['trial_days'] = $trialDays;
            $settings['support_email'] = $supportEmail;
            $settings['support_phone'] = $supportPhone;
            $settings['max_products_trial'] = $maxProductsTrial;
            $settings['max_products_basic'] = $maxProductsBasic;
            $settings['currency'] = $currency;
            $settings['timezone'] = $timezone;

            $message = 'Configurações do SaaS atualizadas com sucesso!';
            $messageType = 'success';
        }
    } elseif ($action === 'update_system') {
        $maintenanceMode = isset($_POST['maintenance_mode']) ? '1' : '0';
        $registrationEnabled = isset($_POST['registration_enabled']) ? '1' : '0';

        saveSetting($pdo, 'maintenance_mode', $maintenanceMode);
        saveSetting($pdo, 'registration_enabled', $registrationEnabled);

        $settings['maintenance_mode'] = $maintenanceMode;
        $settings['registration_enabled'] = $registrationEnabled;

        $message = 'Configurações do sistema atualizadas com sucesso!';
        $messageType = 'success';
    }
}

$pageTitle = 'Configurações';
$currentPage = 'settings';

$totalStores = $pdo->query("SELECT COUNT(*) FROM stores WHERE deleted_at IS NULL")->fetchColumn();
$activeStores = $pdo->query("SELECT COUNT(*) FROM stores WHERE status = 'active' AND deleted_at IS NULL")->fetchColumn();
$totalOrders = $pdo->query("SELECT COUNT(*) FROM orders")->fetchColumn();
$totalProducts = $pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();

include __DIR__ . '/../includes/header.php';
?>
<div class="app-container">
    <?php include __DIR__ . '/../includes/sidebar.php'; ?>
    <main class="main-content">
        <?php include __DIR__ . '/../includes/topbar.php'; ?>
        <div class="content-area">
            <div class="page-header">
                <div>
                    <h2><iconify-icon icon="solar:settings-bold" class="text-gold"></iconify-icon> Configurações</h2>
                    <p>Gerencie as configurações do sistema</p>
                </div>
            </div>

            <?php if ($message): ?>
            <div class="alert <?= $messageType === 'success' ? 'alert-success' : 'alert-error' ?>" id="alertMsg">
                <iconify-icon icon="<?= $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:close-circle-bold' ?>"></iconify-icon>
                <span><?= htmlspecialchars($message) ?></span>
                <button type="button" class="alert-close" onclick="this.parentElement.remove()"><iconify-icon icon="solar:close-circle-bold"></iconify-icon></button>
            </div>
            <?php endif; ?>

            <div class="settings-tabs">
                <button class="tab-btn active" data-tab="profile"><iconify-icon icon="solar:user-bold"></iconify-icon><span>Perfil</span></button>
                <button class="tab-btn" data-tab="security"><iconify-icon icon="solar:lock-bold"></iconify-icon><span>Segurança</span></button>
                <button class="tab-btn" data-tab="saas"><iconify-icon icon="solar:shop-2-bold"></iconify-icon><span>SaaS</span></button>
                <button class="tab-btn" data-tab="system"><iconify-icon icon="solar:server-bold"></iconify-icon><span>Sistema</span></button>
            </div>

            <div class="settings-grid">
                <!-- Perfil -->
                <div class="panel" data-section="profile">
                    <div class="panel-header">
                        <div class="panel-icon"><iconify-icon icon="solar:user-bold"></iconify-icon></div>
                        <div><h3>Meu Perfil</h3><span class="panel-subtitle">Suas informações pessoais</span></div>
                    </div>
                    <form method="POST" class="settings-form">
                        <input type="hidden" name="action" value="update_profile">
                        <div class="form-group">
                            <label class="form-label"><iconify-icon icon="solar:user-outline"></iconify-icon> Nome</label>
                            <input type="text" name="name" value="<?= htmlspecialchars($superAdmin['name'] ?? '') ?>" class="form-input" required placeholder="Seu nome">
                        </div>
                        <div class="form-group">
                            <label class="form-label"><iconify-icon icon="solar:letter-outline"></iconify-icon> Email</label>
                            <input type="email" value="<?= htmlspecialchars($superAdmin['email'] ?? '') ?>" class="form-input disabled" readonly disabled>
                            <small class="form-hint"><iconify-icon icon="solar:info-circle-outline"></iconify-icon> O email não pode ser alterado</small>
                        </div>
                        <div class="form-group">
                            <label class="form-label"><iconify-icon icon="solar:clock-circle-outline"></iconify-icon> Último acesso</label>
                            <input type="text" value="<?= $superAdmin['last_login_at'] ? date('d/m/Y H:i', strtotime($superAdmin['last_login_at'])) : 'Nunca' ?>" class="form-input disabled" readonly disabled>
                        </div>
                        <button type="submit" class="btn btn-primary btn-block"><iconify-icon icon="solar:disk-bold"></iconify-icon> Salvar Perfil</button>
                    </form>
                </div>

                <!-- Senha -->
                <div class="panel" data-section="security">
                    <div class="panel-header">
                        <div class="panel-icon"><iconify-icon icon="solar:lock-bold"></iconify-icon></div>
                        <div><h3>Alterar Senha</h3><span class="panel-subtitle">Mantenha sua conta segura</span></div>
                    </div>
                    <form method="POST" class="settings-form">
                        <input type="hidden" name="action" value="update_password">
                        <div class="form-group">
                            <label class="form-label"><iconify-icon icon="solar:key-outline"></iconify-icon> Senha Atual</label>
                            <div class="input-password">
                                <input type="password" name="current_password" class="form-input" required placeholder="Digite sua senha atual">
                                <button type="button" class="toggle-password"><iconify-icon icon="solar:eye-outline"></iconify-icon></button>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label"><iconify-icon icon="solar:lock-outline"></iconify-icon> Nova Senha</label>
                            <div class="input-password">
                                <input type="password" name="new_password" class="form-input" required minlength="6" placeholder="Digite a nova senha">
                                <button type="button" class="toggle-password"><iconify-icon icon="solar:eye-outline"></iconify-icon></button>
                            </div>
                            <div class="password-strength" id="pwStr"></div>
                            <small class="form-hint"><iconify-icon icon="solar:shield-check-outline"></iconify-icon> Mínimo de 6 caracteres</small>
                        </div>
                        <div class="form-group">
                            <label class="form-label"><iconify-icon icon="solar:lock-password-outline"></iconify-icon> Confirmar Senha</label>
                            <div class="input-password">
                                <input type="password" name="confirm_password" class="form-input" required minlength="6" placeholder="Confirme a nova senha">
                                <button type="button" class="toggle-password"><iconify-icon icon="solar:eye-outline"></iconify-icon></button>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary btn-block"><iconify-icon icon="solar:lock-password-bold"></iconify-icon> Alterar Senha</button>
                    </form>
                </div>

                <!-- SaaS Config -->
                <div class="panel panel-large" data-section="saas">
                    <div class="panel-header">
                        <div class="panel-icon"><iconify-icon icon="solar:shop-2-bold"></iconify-icon></div>
                        <div><h3>Configurações do SaaS</h3><span class="panel-subtitle">Ajustes gerais da plataforma</span></div>
                    </div>
                    <form method="POST" class="settings-form">
                        <input type="hidden" name="action" value="update_settings">
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label"><iconify-icon icon="solar:text-outline"></iconify-icon> Nome do SaaS</label>
                                <input type="text" name="saas_name" value="<?= htmlspecialchars($settings['saas_name'] ?? 'MontaLoja') ?>" class="form-input" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label"><iconify-icon icon="solar:calendar-outline"></iconify-icon> Dias de Trial</label>
                                <input type="number" name="trial_days" value="<?= htmlspecialchars($settings['trial_days'] ?? '14') ?>" class="form-input" min="0" max="90" required>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label"><iconify-icon icon="solar:letter-outline"></iconify-icon> Email de Suporte</label>
                                <input type="email" name="support_email" value="<?= htmlspecialchars($settings['support_email'] ?? '') ?>" class="form-input" placeholder="suporte@exemplo.com">
                            </div>
                            <div class="form-group">
                                <label class="form-label"><iconify-icon icon="solar:phone-outline"></iconify-icon> Telefone</label>
                                <input type="text" name="support_phone" value="<?= htmlspecialchars($settings['support_phone'] ?? '') ?>" class="form-input" placeholder="(00) 00000-0000">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label"><iconify-icon icon="solar:box-outline"></iconify-icon> Máx. Produtos (Trial)</label>
                                <input type="number" name="max_products_trial" value="<?= htmlspecialchars($settings['max_products_trial'] ?? '50') ?>" class="form-input" min="1">
                            </div>
                            <div class="form-group">
                                <label class="form-label"><iconify-icon icon="solar:box-outline"></iconify-icon> Máx. Produtos (Básico)</label>
                                <input type="number" name="max_products_basic" value="<?= htmlspecialchars($settings['max_products_basic'] ?? '500') ?>" class="form-input" min="1">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label"><iconify-icon icon="solar:dollar-outline"></iconify-icon> Moeda</label>
                                <select name="currency" class="form-select">
                                    <option value="BRL" <?= ($settings['currency'] ?? 'BRL') === 'BRL' ? 'selected' : '' ?>>🇧🇷 BRL - Real</option>
                                    <option value="USD" <?= ($settings['currency'] ?? '') === 'USD' ? 'selected' : '' ?>>🇺🇸 USD - Dólar</option>
                                    <option value="EUR" <?= ($settings['currency'] ?? '') === 'EUR' ? 'selected' : '' ?>>🇪🇺 EUR - Euro</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label"><iconify-icon icon="solar:clock-circle-outline"></iconify-icon> Fuso Horário</label>
                                <select name="timezone" class="form-select">
                                    <option value="America/Sao_Paulo" <?= ($settings['timezone'] ?? 'America/Sao_Paulo') === 'America/Sao_Paulo' ? 'selected' : '' ?>>São Paulo (GMT-3)</option>
                                    <option value="America/Manaus" <?= ($settings['timezone'] ?? '') === 'America/Manaus' ? 'selected' : '' ?>>Manaus (GMT-4)</option>
                                    <option value="America/Cuiaba" <?= ($settings['timezone'] ?? '') === 'America/Cuiaba' ? 'selected' : '' ?>>Cuiabá (GMT-4)</option>
                                    <option value="America/Fortaleza" <?= ($settings['timezone'] ?? '') === 'America/Fortaleza' ? 'selected' : '' ?>>Fortaleza (GMT-3)</option>
                                </select>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary"><iconify-icon icon="solar:disk-bold"></iconify-icon> Salvar Configurações</button>
                    </form>
                </div>

                <!-- Controles -->
                <div class="panel" data-section="system">
                    <div class="panel-header">
                        <div class="panel-icon warning"><iconify-icon icon="solar:server-bold"></iconify-icon></div>
                        <div><h3>Controles do Sistema</h3><span class="panel-subtitle">Configurações avançadas</span></div>
                    </div>
                    <form method="POST" class="settings-form">
                        <input type="hidden" name="action" value="update_system">
                        <div class="toggle-group">
                            <div class="toggle-item <?= ($settings['maintenance_mode'] ?? '0') === '1' ? 'active-warning' : '' ?>">
                                <div class="toggle-info">
                                    <div class="toggle-icon"><iconify-icon icon="solar:shield-warning-bold"></iconify-icon></div>
                                    <div><span class="toggle-label">Modo de Manutenção</span><span class="toggle-hint">Apenas admins podem acessar</span></div>
                                </div>
                                <label class="toggle-switch"><input type="checkbox" name="maintenance_mode" <?= ($settings['maintenance_mode'] ?? '0') === '1' ? 'checked' : '' ?>><span class="toggle-slider"></span></label>
                            </div>
                            <div class="toggle-item">
                                <div class="toggle-info">
                                    <div class="toggle-icon success"><iconify-icon icon="solar:user-plus-bold"></iconify-icon></div>
                                    <div><span class="toggle-label">Registro de Novas Lojas</span><span class="toggle-hint">Permitir novos cadastros</span></div>
                                </div>
                                <label class="toggle-switch"><input type="checkbox" name="registration_enabled" <?= ($settings['registration_enabled'] ?? '1') === '1' ? 'checked' : '' ?>><span class="toggle-slider"></span></label>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary btn-block" style="margin-top:1.5rem"><iconify-icon icon="solar:disk-bold"></iconify-icon> Salvar Controles</button>
                    </form>
                </div>

                <!-- Info Sistema -->
                <div class="panel" data-section="system">
                    <div class="panel-header">
                        <div class="panel-icon info"><iconify-icon icon="solar:info-circle-bold"></iconify-icon></div>
                        <div><h3>Informações do Sistema</h3><span class="panel-subtitle">Detalhes técnicos</span></div>
                    </div>
                    <div class="info-grid">
                        <div class="info-item"><div class="info-icon"><iconify-icon icon="solar:tag-outline"></iconify-icon></div><div class="info-content"><span class="info-label">Versão</span><span class="info-value">1.0.0</span></div></div>
                        <div class="info-item"><div class="info-icon"><iconify-icon icon="solar:code-outline"></iconify-icon></div><div class="info-content"><span class="info-label">PHP</span><span class="info-value"><?= phpversion() ?></span></div></div>
                        <div class="info-item"><div class="info-icon"><iconify-icon icon="solar:database-outline"></iconify-icon></div><div class="info-content"><span class="info-label">MySQL</span><span class="info-value"><?= $pdo->query('SELECT VERSION()')->fetchColumn() ?></span></div></div>
                        <div class="info-item"><div class="info-icon"><iconify-icon icon="solar:server-outline"></iconify-icon></div><div class="info-content"><span class="info-label">Servidor</span><span class="info-value"><?= php_uname('s') ?></span></div></div>
                        <div class="info-item"><div class="info-icon"><iconify-icon icon="solar:cpu-outline"></iconify-icon></div><div class="info-content"><span class="info-label">Memória</span><span class="info-value"><?= ini_get('memory_limit') ?></span></div></div>
                        <div class="info-item"><div class="info-icon"><iconify-icon icon="solar:upload-outline"></iconify-icon></div><div class="info-content"><span class="info-label">Upload</span><span class="info-value"><?= ini_get('upload_max_filesize') ?></span></div></div>
                    </div>
                </div>

                <!-- Estatísticas -->
                <div class="panel" data-section="system">
                    <div class="panel-header">
                        <div class="panel-icon"><iconify-icon icon="solar:chart-bold"></iconify-icon></div>
                        <div><h3>Estatísticas Rápidas</h3><span class="panel-subtitle">Visão geral</span></div>
                    </div>
                    <div class="stats-grid">
                        <div class="stat-card"><div class="stat-icon blue"><iconify-icon icon="solar:shop-bold"></iconify-icon></div><div class="stat-info"><span class="stat-value"><?= number_format($totalStores) ?></span><span class="stat-label">Lojas</span></div></div>
                        <div class="stat-card"><div class="stat-icon green"><iconify-icon icon="solar:check-circle-bold"></iconify-icon></div><div class="stat-info"><span class="stat-value"><?= number_format($activeStores) ?></span><span class="stat-label">Ativas</span></div></div>
                        <div class="stat-card"><div class="stat-icon purple"><iconify-icon icon="solar:bag-3-bold"></iconify-icon></div><div class="stat-info"><span class="stat-value"><?= number_format($totalOrders) ?></span><span class="stat-label">Pedidos</span></div></div>
                        <div class="stat-card"><div class="stat-icon orange"><iconify-icon icon="solar:box-bold"></iconify-icon></div><div class="stat-info"><span class="stat-value"><?= number_format($totalProducts) ?></span><span class="stat-label">Produtos</span></div></div>
                    </div>
                </div>
            </div>
        </div>
        <?php include __DIR__ . '/../includes/footer.php'; ?>
    </main>
</div>

<style>
.settings-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:1.5rem}
.panel-large{grid-column:span 2}
.settings-tabs{display:flex;gap:.5rem;margin-bottom:1.5rem;background:var(--bg-panel);border-radius:var(--radius-lg);padding:.5rem;overflow-x:auto;-webkit-overflow-scrolling:touch}
.tab-btn{display:flex;align-items:center;gap:.5rem;padding:.75rem 1rem;background:transparent;border:0;border-radius:var(--radius-md);color:var(--text-muted);font-size:.85rem;font-weight:500;cursor:pointer;white-space:nowrap;transition:all .2s}
.tab-btn:hover{background:rgba(255,255,255,.05);color:var(--text-primary)}
.tab-btn.active{background:var(--gold);border-color:var(--gold);color:#000}
.tab-btn iconify-icon{font-size:1.1rem}
.panel-header{display:flex;align-items:flex-start;gap:1rem;margin-bottom:1.5rem;padding-bottom:1rem;border-bottom:1px solid var(--border-light)}
.panel-icon{width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:rgba(204,164,59,.15);border-radius:12px;flex-shrink:0}
.panel-icon iconify-icon{font-size:1.4rem;color:var(--gold)}
.panel-icon.warning{background:rgba(245,158,11,.15)}
.panel-icon.warning iconify-icon{color:#F59E0B}
.panel-icon.info{background:rgba(59,130,246,.15)}
.panel-icon.info iconify-icon{color:#3B82F6}
.panel-header h3{margin:0;font-size:1.1rem;font-weight:600;color:var(--text-primary)}
.panel-subtitle{font-size:.8rem;color:var(--text-muted);margin-top:.2rem;display:block}
.settings-form{display:flex;flex-direction:column;gap:1.25rem}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:1rem}
.form-label{display:flex;align-items:center;gap:.5rem;margin-bottom:.5rem;font-size:.9rem;font-weight:500;color:var(--text-primary)}
.form-label iconify-icon{font-size:1rem;color:var(--text-muted)}
.form-input.disabled{opacity:.6;cursor:not-allowed}
.form-hint{display:flex;align-items:center;gap:.35rem;margin-top:.5rem;font-size:.8rem;color:var(--text-muted)}
.form-hint iconify-icon{font-size:.9rem}
.input-password{position:relative}
.input-password .form-input{padding-right:2.75rem}
.toggle-password{position:absolute;right:.75rem;top:50%;transform:translateY(-50%);background:none;border:none;color:var(--text-muted);cursor:pointer;padding:.25rem;display:flex;align-items:center;justify-content:center}
.toggle-password:hover{color:var(--text-primary)}
.password-strength{height:4px;border-radius:2px;margin-top:.5rem;background:var(--border-light);overflow:hidden;display:none}
.password-strength.visible{display:block}
.password-strength::after{content:'';display:block;height:100%;width:var(--strength,0%);background:var(--strength-color,var(--border-light));transition:all .3s}
.btn-block{width:100%;justify-content:center}
.alert{display:flex;align-items:center;gap:.75rem;padding:1rem 1.25rem;border-radius:var(--radius-md);margin-bottom:1.5rem;font-weight:500;animation:slideDown .3s ease-out}
@keyframes slideDown{from{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}
.alert iconify-icon{font-size:1.25rem;flex-shrink:0}
.alert span{flex:1}
.alert-close{background:none;border:none;color:inherit;opacity:.6;cursor:pointer;padding:.25rem;display:flex;align-items:center;justify-content:center;transition:opacity .2s}
.alert-close:hover{opacity:1}
.alert-success{background:rgba(34,197,94,.1);border:1px solid rgba(34,197,94,.3);color:#22C55E}
.alert-error{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);color:#EF4444}
.toggle-group{display:flex;flex-direction:column;gap:1rem}
.toggle-item{display:flex;justify-content:space-between;align-items:center;padding:1rem;background:var(--bg-input);border-radius:var(--radius-md);border:1px solid transparent;transition:all .2s}
.toggle-item:hover{border-color:var(--border-light)}
.toggle-item.active-warning{background:rgba(245,158,11,.1);border-color:rgba(245,158,11,.3)}
.toggle-info{display:flex;align-items:center;gap:.75rem}
.toggle-icon{width:36px;height:36px;display:flex;align-items:center;justify-content:center;background:rgba(245,158,11,.15);border-radius:8px;flex-shrink:0}
.toggle-icon iconify-icon{font-size:1.1rem;color:#F59E0B}
.toggle-icon.success{background:rgba(34,197,94,.15)}
.toggle-icon.success iconify-icon{color:#22C55E}
.toggle-label{font-weight:500;color:var(--text-primary);display:block}
.toggle-hint{font-size:.8rem;color:var(--text-muted);display:block;margin-top:.15rem}
.toggle-switch{position:relative;width:50px;height:26px;flex-shrink:0}
.toggle-switch input{opacity:0;width:0;height:0}
.toggle-slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:var(--border-light);transition:.3s;border-radius:26px}
.toggle-slider:before{position:absolute;content:"";height:20px;width:20px;left:3px;bottom:3px;background-color:white;transition:.3s;border-radius:50%;box-shadow:0 2px 4px rgba(0,0,0,.2)}
.toggle-switch input:checked+.toggle-slider{background-color:var(--gold)}
.toggle-switch input:checked+.toggle-slider:before{transform:translateX(24px)}
.info-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:.75rem}
.info-item{display:flex;align-items:center;gap:.75rem;padding:.75rem;background:var(--bg-input);border-radius:var(--radius-md)}
.info-icon{width:32px;height:32px;display:flex;align-items:center;justify-content:center;background:var(--bg-dark);border-radius:8px;flex-shrink:0}
.info-icon iconify-icon{font-size:1rem;color:var(--text-muted)}
.info-content{display:flex;flex-direction:column;min-width:0}
.info-label{font-size:.75rem;color:var(--text-muted)}
.info-value{font-weight:600;color:var(--text-primary);font-size:.9rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.stats-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:1rem}
.stat-card{display:flex;align-items:center;gap:1rem;padding:1rem;background:var(--bg-input);border-radius:var(--radius-md);transition:transform .2s,box-shadow .2s}
.stat-card:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,.15)}
.stat-icon{width:48px;height:48px;display:flex;align-items:center;justify-content:center;border-radius:12px;flex-shrink:0}
.stat-icon iconify-icon{font-size:1.5rem}
.stat-icon.blue{background:rgba(59,130,246,.15)}.stat-icon.blue iconify-icon{color:#3B82F6}
.stat-icon.green{background:rgba(34,197,94,.15)}.stat-icon.green iconify-icon{color:#22C55E}
.stat-icon.purple{background:rgba(168,85,247,.15)}.stat-icon.purple iconify-icon{color:#A855F7}
.stat-icon.orange{background:rgba(249,115,22,.15)}.stat-icon.orange iconify-icon{color:#F97316}
.stat-info{display:flex;flex-direction:column}
.stat-value{font-size:1.5rem;font-weight:700;color:var(--text-primary);line-height:1.2}
.stat-label{font-size:.8rem;color:var(--text-muted)}
@media(max-width:1200px){.settings-grid{grid-template-columns:1fr}.panel-large{grid-column:span 1}}
@media(max-width:768px){.settings-tabs{display:flex}.settings-grid{gap:1rem}.form-row{grid-template-columns:1fr}.info-grid{grid-template-columns:1fr}.stats-grid{grid-template-columns:1fr 1fr}.toggle-info{flex-direction:column;align-items:flex-start;gap:.5rem}}
@media(max-width:480px){.content-area{padding:1rem}.panel{padding:1.25rem}.panel-header{flex-direction:column;align-items:flex-start;gap:.75rem}.stats-grid{grid-template-columns:1fr}.stat-card{justify-content:flex-start}.tab-btn span{display:none}.tab-btn{padding:.75rem}}
.panel{animation:fadeIn .4s ease-out}
@keyframes fadeIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}
.panel:nth-child(1){animation-delay:0s}.panel:nth-child(2){animation-delay:.05s}.panel:nth-child(3){animation-delay:.1s}.panel:nth-child(4){animation-delay:.15s}.panel:nth-child(5){animation-delay:.2s}.panel:nth-child(6){animation-delay:.25s}
</style>

<script>
document.addEventListener('DOMContentLoaded',function(){
document.querySelectorAll('.toggle-password').forEach(btn=>{btn.addEventListener('click',function(){const i=this.previousElementSibling;i.type=i.type==='password'?'text':'password';this.querySelector('iconify-icon').setAttribute('icon',i.type==='password'?'solar:eye-outline':'solar:eye-closed-outline')})});
const pwInput=document.querySelector('input[name="new_password"]'),pwStr=document.getElementById('pwStr');
if(pwInput&&pwStr){pwInput.addEventListener('input',function(){const p=this.value;let s=0;if(p.length>=6)s+=25;if(p.length>=8)s+=25;if(/[A-Z]/.test(p))s+=25;if(/[0-9]/.test(p))s+=15;if(/[^A-Za-z0-9]/.test(p))s+=10;s=Math.min(100,s);let c='#EF4444';if(s>25)c='#F59E0B';if(s>50)c='#EAB308';if(s>75)c='#22C55E';pwStr.classList.toggle('visible',p.length>0);pwStr.style.setProperty('--strength',s+'%');pwStr.style.setProperty('--strength-color',c)})}
const tabs=document.querySelectorAll('.tab-btn'),panels=document.querySelectorAll('.panel[data-section]');
tabs.forEach(tab=>{tab.addEventListener('click',function(){const t=this.dataset.tab;tabs.forEach(x=>x.classList.remove('active'));this.classList.add('active');panels.forEach(p=>{p.style.display=(p.dataset.section===t)?'block':'none'})})});
panels.forEach(p=>{p.style.display=(p.dataset.section==='profile')?'block':'none'});
if(window.innerWidth<=768){panels.forEach(p=>{p.classList.toggle('visible',p.dataset.section==='profile')})}
const alert=document.getElementById('alertMsg');if(alert){setTimeout(()=>{alert.style.opacity='0';alert.style.transform='translateY(-10px)';setTimeout(()=>alert.remove(),300)},5000)}
const maint=document.querySelector('input[name="maintenance_mode"]');if(maint){maint.addEventListener('change',function(){this.closest('.toggle-item').classList.toggle('active-warning',this.checked)})}
});
</script>
