<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/progression_functions.php';
require_once __DIR__ . '/../includes/stats_functions.php';
if (file_exists(__DIR__ . '/../includes/diamond_functions.php')) {
    require_once __DIR__ . '/../includes/diamond_functions.php';
}

requireLogin();
recarregarSessaoUsuario($pdo, (int) $_SESSION['usuario_id']);
$pre = usuarioAtual();
$userId = (int) ($pre['id'] ?? 0);

if (function_exists('afGarantirProgressao')) {
    afGarantirProgressao($pdo, $userId);
}
if (function_exists('afSincronizarRecompensas')) {
    afSincronizarRecompensas($pdo, $userId, calcularNivel((int) ($pre['xp_total'] ?? 0)));
}

recarregarSessaoUsuario($pdo, $userId);
$u = usuarioAtual();
$userId = (int) $u['id'];

$nivel = calcularNivel((int) ($u['xp_total'] ?? 0));
$xpMax = max(1, xpParaProximoNivel($nivel));
$xpAtual = max(0, xpNoNivelAtual((int) ($u['xp_total'] ?? 0), $nivel));
$xpPct = min(100, (int) round(($xpAtual / $xpMax) * 100));
$titulo = getTitulo($nivel);
$corTit = getCorTitulo($titulo);

$progressao = function_exists('afResumoProgressao') ? afResumoProgressao($pdo, $userId) : [];
$equip = $progressao['equipamentos'] ?? [];
$missoes = $progressao['missoes']['diaria'] ?? [];
$diamondBalance = function_exists('afDiamondsGetBalance') ? (int) afDiamondsGetBalance($pdo, $userId) : 0;
$notifs = function_exists('contarNotificacoesNaoLidas') ? (int) contarNotificacoesNaoLidas($pdo, $userId) : 0;
$melhorNota = (float) ($u['melhor_pontuacao'] ?? 0);
$ranking = function_exists('afRanking') ? (afRanking($pdo, 'global', 'global', $u, 3, 0)['itens'] ?? []) : [];
$posicao = function_exists('afCalcularPosicaoPeriodo') ? (int) afCalcularPosicaoPeriodo($pdo, $userId, 'global') : 0;

$mainMission = array_values(array_slice($missoes, 0, 1))[0] ?? [
    'nome' => 'Aura Intensa',
    'descricao' => 'Faça pelo menos 700 pontos em uma partida.',
    'progresso' => 210,
    'meta' => 700,
    'xp_recompensa' => 15,
    'concluida_em' => null,
];
$missionProgress = max(0, (int) ($mainMission['progresso'] ?? 0));
$missionGoal = max(1, (int) ($mainMission['meta'] ?? 1));
$missionPct = min(100, (int) round(($missionProgress / $missionGoal) * 100));
$avatarUrl = urlAvatar($u['foto_perfil'] ?? null, $u['foto_externa'] ?? null);

$liveCards = [
    [
        'nome' => 'Lucas Mendes',
        'categoria' => 'Cantando ao vivo',
        'publico' => '1,2K',
        'imagem' => 'live-lucas.webp',
    ],
    [
        'nome' => 'Letícia Gamer',
        'categoria' => 'Ranqueada ao vivo',
        'publico' => '2,8K',
        'imagem' => 'live-leticia.webp',
    ],
    [
        'nome' => 'Rafael Soul',
        'categoria' => 'Voz e violão',
        'publico' => '956',
        'imagem' => 'live-rafael.webp',
    ],
];

$icon = static function (string $name, string $class = ''): string {
    $attrs = 'class="af-icon ' . esc($class) . '" viewBox="0 0 24 24" aria-hidden="true" focusable="false"';
    return match ($name) {
        'bell' => '<svg ' . $attrs . '><path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9"/><path d="M10 21h4"/></svg>',
        'diamond' => '<svg ' . $attrs . '><path d="m3 8 4-5h10l4 5-9 13L3 8Z"/><path d="m7 3 5 18 5-18M3 8h18"/></svg>',
        'plus' => '<svg ' . $attrs . '><path d="M12 5v14M5 12h14"/></svg>',
        'trophy' => '<svg ' . $attrs . '><path d="M8 21h8M12 17v4M7 4h10v4a5 5 0 0 1-10 0V4Z"/><path d="M7 6H4v2a4 4 0 0 0 4 4M17 6h3v2a4 4 0 0 1-4 4"/></svg>',
        'play' => '<svg ' . $attrs . '><path d="m8 5 11 7-11 7V5Z"/></svg>',
        'fire' => '<svg ' . $attrs . '><path d="M12 22c4 0 7-3 7-7 0-3-2-6-5-9 0 3-2 4-3 5 0-4-2-7-4-9 0 5-3 8-3 13 0 4 4 7 8 7Z"/><path d="M9 17c0 2 1 3 3 3s3-1 3-3c0-1-1-3-3-5-1 2-3 3-3 5Z"/></svg>',
        'monitor' => '<svg ' . $attrs . '><rect x="3" y="4" width="18" height="13" rx="2"/><path d="M8 21h8M12 17v4"/><path d="m10 8 5 3-5 3V8Z"/></svg>',
        'arrow' => '<svg ' . $attrs . '><path d="M5 12h14M13 6l6 6-6 6"/></svg>',
        'broadcast' => '<svg ' . $attrs . '><circle cx="12" cy="12" r="2"/><path d="M8.5 8.5a5 5 0 0 0 0 7M15.5 8.5a5 5 0 0 1 0 7M5.5 5.5a9 9 0 0 0 0 13M18.5 5.5a9 9 0 0 1 0 13"/></svg>',
        'eye' => '<svg ' . $attrs . '><path d="M2 12s4-6 10-6 10 6 10 6-4 6-10 6S2 12 2 12Z"/><circle cx="12" cy="12" r="2.5"/></svg>',
        'target' => '<svg ' . $attrs . '><circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="4"/><path d="M12 2v3M22 12h-3"/></svg>',
        'crown' => '<svg ' . $attrs . '><path d="m3 7 4 4 5-7 5 7 4-4-2 11H5L3 7Z"/><path d="M5 21h14"/></svg>',
        'cart' => '<svg ' . $attrs . '><path d="M3 4h2l2 11h10l3-8H6"/><circle cx="9" cy="20" r="1"/><circle cx="17" cy="20" r="1"/></svg>',
        'home' => '<svg ' . $attrs . '><path d="m3 11 9-8 9 8"/><path d="M5 10v11h14V10M9 21v-6h6v6"/></svg>',
        'swords' => '<svg ' . $attrs . '><path d="m14 5 5-2-2 5-8 8-3 1 1-3 7-9ZM10 5 5 3l2 5 3 3M14 14l3 3 3 1-1-3-3-3M5 19l3-3"/></svg>',
        'user' => '<svg ' . $attrs . '><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>',
        default => '<svg ' . $attrs . '><circle cx="12" cy="12" r="9"/></svg>',
    };
};

$pageTitle = 'Início';
$activePage = 'home';
$bodyClass = trim(($bodyClass ?? '') . ' aura-home-v4-body');
$showNav = false;
$hideLegalFooter = true;
$pageStyles = array_merge($pageStyles ?? [], [SITE_URL . '/assets/css/home-fiel.css?v=4.0.0']);
$pageScripts = array_merge($pageScripts ?? [], [SITE_URL . '/assets/js/home-fiel.js?v=4.0.0']);
require_once __DIR__ . '/../includes/header.php';
?>

<header class="af-home-header">
    <div class="af-home-shell af-home-header__inner">
        <a href="<?= SITE_URL ?>/pages/home.php" class="af-brand" aria-label="Aura Farming — Início">
            <span>AURA</span>
            <small>FARMING</small>
        </a>

        <div class="af-header-status" aria-label="Resumo da conta">
            <a href="<?= SITE_URL ?>/pages/notificacoes.php" class="af-status af-status--notification" aria-label="Notificações">
                <?= $icon('bell') ?>
                <?php if ($notifs > 0): ?><b><?= min(99, $notifs) ?></b><?php endif; ?>
            </a>
            <a href="<?= SITE_URL ?>/pages/comprar-diamantes.php" class="af-status af-status--diamonds" aria-label="Comprar diamantes">
                <?= $icon('diamond') ?>
                <strong><?= formatarNumero($diamondBalance) ?></strong>
                <span class="af-status-plus"><?= $icon('plus') ?></span>
            </a>
            <a href="<?= SITE_URL ?>/pages/perfil.php" class="af-status af-status--score" aria-label="Maior nota pessoal">
                <?= $icon('trophy') ?>
                <span><small>MAIOR NOTA</small><strong><?= $melhorNota > 0 ? formatarNumero($melhorNota) : '0' ?></strong></span>
            </a>
        </div>
    </div>
</header>

<main class="af-home-shell af-home-main">
    <?= renderFlash() ?>

    <section class="af-hero" aria-labelledby="af-home-title">
        <div class="af-hero-copy">
            <span class="af-eyebrow">AURA FARMING</span>
            <h1 id="af-home-title">PRONTO PARA<br>FARMAR SUA<br><em>AURA</em> HOJE?</h1>
            <p>Grave, assista, pontue e evolua.<br>Mostre seu talento e conquiste o topo!</p>
            <a href="<?= SITE_URL ?>/pages/farmar.php" class="af-primary-button">
                <span><?= $icon('play') ?></span>
                COMEÇAR FARM <b>AURA</b>
            </a>
        </div>
        <div class="af-hero-art" aria-hidden="true">
            <img src="<?= SITE_URL ?>/assets/imagens/hero-aura.webp" alt="" width="1600" height="900" fetchpriority="high">
        </div>
    </section>

    <section class="af-profile" aria-label="Resumo do jogador">
        <div class="af-profile-user">
            <div class="af-avatar frame-<?= esc($equip['moldura_valor'] ?? 'none') ?>" style="--player-aura-color:<?= esc($equip['cor_aura_valor'] ?? '#00d4ff') ?>">
                <img src="<?= esc($avatarUrl) ?>" alt="Foto de <?= esc($u['nome']) ?>">
                <i></i>
                <span>Nv <?= $nivel ?></span>
            </div>
            <div class="af-profile-meta">
                <h2><?= esc($u['nome']) ?></h2>
                <p><?= esc($u['aura_id']) ?></p>
                <span style="--rank-color:<?= esc($corTit) ?>">★ <?= esc($equip['titulo_valor'] ?? $titulo) ?></span>
            </div>
        </div>

        <div class="af-profile-stats">
            <div>
                <?= $icon('diamond') ?>
                <span><small>DIAMANTES</small><strong><?= formatarNumero($diamondBalance) ?></strong></span>
            </div>
            <div>
                <?= $icon('trophy') ?>
                <span><small>MAIOR NOTA PESSOAL</small><strong><?= $melhorNota > 0 ? formatarNumero($melhorNota) : '0' ?></strong></span>
            </div>
        </div>

        <div class="af-profile-progress">
            <div><span>Nível <?= $nivel ?></span><span>Nível <?= $nivel + 1 ?></span></div>
            <div class="af-progress" role="progressbar" aria-valuenow="<?= $xpPct ?>" aria-valuemin="0" aria-valuemax="100"><i style="width:<?= $xpPct ?>%"></i></div>
            <small><?= formatarNumero($xpAtual) ?> / <?= formatarNumero($xpMax) ?> XP</small>
        </div>
    </section>

    <section class="af-actions" aria-label="Acessos rápidos">
        <a href="<?= SITE_URL ?>/pages/farmar.php" class="af-action-card af-action-card--farm">
            <img src="<?= SITE_URL ?>/assets/imagens/card-farm.webp" alt="" width="1000" height="750" loading="lazy">
            <div class="af-action-content">
                <span class="af-action-icon"><?= $icon('fire') ?></span>
                <h3>FARMAR AURA</h3>
                <p>Entre no jogo, grave<br>e acumule aura!</p>
            </div>
            <span class="af-card-arrow"><?= $icon('arrow') ?></span>
        </a>

        <a href="<?= SITE_URL ?>/pages/assistir.php" class="af-action-card af-action-card--watch">
            <img src="<?= SITE_URL ?>/assets/imagens/card-watch.webp" alt="" width="1000" height="750" loading="lazy">
            <div class="af-action-content">
                <span class="af-action-icon"><?= $icon('monitor') ?></span>
                <h3>ASSISTIR E<br>GANHAR XP</h3>
                <p>Assista vídeos, descubra<br>talentos e ganhe XP!</p>
            </div>
            <span class="af-card-arrow"><?= $icon('arrow') ?></span>
        </a>

        <a href="<?= SITE_URL ?>/pages/ranking.php" class="af-action-card af-action-card--ranking">
            <img src="<?= SITE_URL ?>/assets/imagens/card-ranking.webp" alt="" width="1000" height="750" loading="lazy">
            <div class="af-action-content">
                <span class="af-action-icon"><?= $icon('trophy') ?></span>
                <h3>RANKING</h3>
                <p>Veja os melhores<br>e suba no ranking!</p>
            </div>
            <span class="af-card-arrow"><?= $icon('arrow') ?></span>
        </a>

        <a href="<?= SITE_URL ?>/pages/comprar-diamantes.php" class="af-action-card af-action-card--diamonds">
            <img src="<?= SITE_URL ?>/assets/imagens/card-diamantes.webp" alt="" width="1000" height="750" loading="lazy">
            <div class="af-action-content">
                <span class="af-action-icon"><?= $icon('diamond') ?></span>
                <h3>COMPRAR<br>DIAMANTES</h3>
                <p>Mais recursos para<br>mais conquistas!</p>
            </div>
            <span class="af-card-arrow"><?= $icon('arrow') ?></span>
        </a>
    </section>

    <section class="af-live" data-af-carousel>
        <header class="af-section-heading">
            <div><span class="af-live-pulse"><?= $icon('broadcast') ?></span><h2>AO VIVO <em>AGORA</em></h2></div>
            <a href="<?= SITE_URL ?>/pages/ao_vivo.php">VER TODOS <?= $icon('arrow') ?></a>
        </header>

        <div class="af-live-viewport" data-af-carousel-viewport>
            <div class="af-live-track">
                <?php foreach ($liveCards as $index => $live): ?>
                    <a href="<?= SITE_URL ?>/pages/assistir.php" class="af-live-card" data-af-slide>
                        <img src="<?= SITE_URL ?>/assets/imagens/<?= esc($live['imagem']) ?>" alt="<?= esc($live['nome']) ?> ao vivo" width="1200" height="675" loading="lazy">
                        <span class="af-live-badge">● AO VIVO</span>
                        <span class="af-live-viewers"><?= $icon('eye') ?> <?= esc($live['publico']) ?></span>
                        <div class="af-live-info">
                            <strong><?= esc($live['nome']) ?> <i>✓</i></strong>
                            <small><?= esc($live['categoria']) ?></small>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="af-carousel-controls">
            <button type="button" class="af-carousel-button" data-af-prev aria-label="Voltar transmissão"><?= $icon('arrow') ?></button>
            <div class="af-carousel-dots" data-af-dots aria-label="Paginação das transmissões"></div>
            <button type="button" class="af-carousel-button" data-af-next aria-label="Avançar transmissão"><?= $icon('arrow') ?></button>
        </div>
    </section>

    <section class="af-dashboard-grid">
        <article class="af-dashboard-card af-mission-card">
            <header><?= $icon('target') ?><h2>MISSÃO DO DIA</h2></header>
            <div class="af-mission-body">
                <div>
                    <h3><?= strtoupper(esc($mainMission['nome'] ?? 'Aura Intensa')) ?></h3>
                    <p><?= esc($mainMission['descricao'] ?? 'Faça pelo menos 700 pontos em uma partida.') ?></p>
                </div>
                <strong>+ <?= (int) ($mainMission['xp_recompensa'] ?? 15) ?> XP</strong>
            </div>
            <div class="af-progress" role="progressbar" aria-valuenow="<?= $missionPct ?>" aria-valuemin="0" aria-valuemax="100"><i style="width:<?= $missionPct ?>%"></i></div>
            <footer><span><?= min($missionProgress, $missionGoal) ?> / <?= $missionGoal ?></span><?php if (!empty($mainMission['concluida_em'])): ?><b>✓ Concluída</b><?php endif; ?></footer>
        </article>

        <article class="af-dashboard-card af-ranking-card">
            <header>
                <div><?= $icon('crown') ?><h2>TOP RANKING</h2></div>
                <a href="<?= SITE_URL ?>/pages/ranking.php">VER TODOS <?= $icon('arrow') ?></a>
            </header>
            <ol class="af-ranking-list">
                <?php if ($ranking): ?>
                    <?php foreach ($ranking as $index => $player): ?>
                        <li>
                            <span class="af-rank-number af-rank-number--<?= $index + 1 ?>"><?= $index + 1 ?></span>
                            <img src="<?= esc(urlAvatar($player['foto_perfil'] ?? null, $player['foto_externa'] ?? null)) ?>" alt="<?= esc($player['nome']) ?>">
                            <span class="af-rank-name"><strong><?= esc($player['nome']) ?></strong><small><?= $index === 0 ? 'Líder global' : 'Aura em destaque' ?></small></span>
                            <b><?= $icon('trophy') ?> <?= formatarNumero((float) ($player['melhor_pontuacao'] ?? 0)) ?></b>
                        </li>
                    <?php endforeach; ?>
                <?php else: ?>
                    <li class="af-ranking-empty">Seja o primeiro no ranking!</li>
                <?php endif; ?>
            </ol>
            <?php if ($posicao > 0): ?><footer>Você está em <strong><?= $posicao ?>º lugar</strong></footer><?php endif; ?>
        </article>

        <a href="<?= SITE_URL ?>/pages/comprar-diamantes.php" class="af-dashboard-card af-diamond-promo">
            <img src="<?= SITE_URL ?>/assets/imagens/card-diamantes.webp" alt="Baú com diamantes" width="1000" height="750" loading="lazy">
            <div>
                <h2>COMPRAR<br>DIAMANTES</h2>
                <p>Mais diamantes,<br>mais conquistas!</p>
                <span><?= $icon('cart') ?> COMPRAR</span>
            </div>
        </a>
    </section>
</main>

<nav class="af-home-nav" aria-label="Navegação principal">
    <div class="af-home-nav__inner">
        <a href="<?= SITE_URL ?>/pages/home.php" class="is-active"><?= $icon('home') ?><span>INÍCIO</span></a>
        <a href="<?= SITE_URL ?>/pages/ao_vivo.php"><?= $icon('broadcast') ?><span>AO VIVO</span></a>
        <a href="<?= SITE_URL ?>/pages/arena.php"><?= $icon('swords') ?><span>ARENA</span></a>
        <a href="<?= SITE_URL ?>/pages/ranking.php"><?= $icon('trophy') ?><span>RANKING</span></a>
        <a href="<?= SITE_URL ?>/pages/perfil.php"><?= $icon('user') ?><span>PERFIL</span></a>
    </div>
</nav>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
