<?php
session_start();
require 'conexao.php';

// =================================================================================
// 1. SISTEMA ORIGINAL INTACTO (LÓGICA, VARIÁVEIS E CONSULTAS)
// =================================================================================

// 1. Verificação de Acesso
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// 2. Inicialização de Variáveis
$msgsis2 = $_SESSION['msg2'] ?? '';
$user_id = $_SESSION['user_name'];

// Preços e Variáveis Globais
$precomadeira = 27; $_SESSION['precomadeira'] = $precomadeira;
$precocarne = 36; $_SESSION['precocarne'] = $precocarne;

$total_notificacoes = 0;
$personagemAtivo = null; 
$messages = [];
$situacao = 'Nenhum'; 
$local = '';
$paralisado = date('Y-m-d H:i:s'); 
$tipolocal = 'city'; 

// Variáveis de Localização (Inicialização para evitar erros)
$dominio_local = 'Nenhum';
$governante_local = 'Ninguém';
$nomelocal = 'Desconhecido';

// Controle de Direções e Litoral
$norte_id = ''; $leste_id = ''; $sul_id = ''; $oeste_id = ''; 
$show_n = false; $show_l = false; $show_s = false; $show_o = false;
$is_litoral = false;

$horarioAtual = date('Y-m-d H:i:s');

// 3. Notificações
$sqlCountNotificacoes = "SELECT COUNT(*) AS total_notificacoes FROM notificacoes_jogo WHERE user2 = :user_name AND vz2 = 0";
$stmtCountNotificacoes = $pdo->prepare($sqlCountNotificacoes);
$stmtCountNotificacoes->bindParam(':user_name', $user_id, PDO::PARAM_STR);
$stmtCountNotificacoes->execute();
$total_notificacoes = $stmtCountNotificacoes->fetch(PDO::FETCH_ASSOC)['total_notificacoes'];

// 4. Modal Local (Ajax) - Mantido para compatibilidade
if (isset($_GET['location'])) {
    $location = $_GET['location'];
    $sqlLocation = "SELECT descricao FROM mapasmed WHERE nome = :location";
    $stmtLocation = $pdo->prepare($sqlLocation);
    $stmtLocation->bindParam(':location', $location, PDO::PARAM_STR);
    $stmtLocation->execute();
    $locationInfo = $stmtLocation->fetch(PDO::FETCH_ASSOC);
    if ($locationInfo) { echo $locationInfo['descricao']; exit(); }
}

// 5. Consulta Personagem
$sql = "SELECT * FROM personagens WHERE jogador = :user_id AND ativo = 1 LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
$stmt->execute();

if ($stmt->rowCount() > 0) {
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $personagemAtivo = $row; 
    
    $personagem_id = $row['id'];
    $nomePersonagem = $row['personagem'];
    $personagem = $row['personagem'];
    $situacao = $row['situacao'] ?? 'livre'; 
    $local = $row['local'];
    $paralisado = $row['paralisado'];
    
    // Recursos
    $prata = $row['prata'];
    $ouro = $row['ouro']; // Adicionado Ouro que faltava em algumas views
    $soldados = $row['soldados'];
    $carne = $row['carne'];
    $madeira = $row['madeira'];
    $atk = $row['atk'];
    $def = $row['def'];
    $cla = $row['cla'];
    $cargo_id = $row['cargo'] ?? 1;
    
    // Status
    $hp_atual = $row['hp_atual'] ?? 100; 
    $hp_max = $row['hp_max'] ?? 100;
    
    // Colunas de Fome/Sede
    $fome = $row['fome'] ?? 100;
    $sede = $row['sede'] ?? 100;
    
    // Sessão
    $_SESSION['personagem'] = $personagem_id;
    $_SESSION['personagem_nome'] = $nomePersonagem;
    $_SESSION['local'] = $local;
    $_SESSION['situacao'] = $situacao;
    $_SESSION['carne'] = $carne;
    $_SESSION['madeira'] = $madeira;
    $_SESSION['soldados'] = $soldados;
    $_SESSION['prata'] = $prata;
    $_SESSION['sede'] = $sede;
    $_SESSION['fome'] = $fome;
    $_SESSION['cla'] = $cla;
    $_SESSION['cargo_id'] = $cargo_id;

    // --- LÓGICA DE VIZINHOS E LITORAL ---
    $sqlLocal = "SELECT tipo, regiao, nome, dominio, governante, n, l, s, o FROM mapasmed WHERE nome = :local";
    $stmtLocal = $pdo->prepare($sqlLocal);
    $stmtLocal->bindParam(':local', $local, PDO::PARAM_STR);
    $stmtLocal->execute();
    $local_info = $stmtLocal->fetch(PDO::FETCH_ASSOC);
    
    if ($local_info) {
        $tipolocal = $local_info['tipo'];
        $regiao_atual = $local_info['regiao'];
        
        $nomelocal = $local_info['nome'];
        $dominio_local = $local_info['dominio'];
        $governante_local = $local_info['governante'];
        
        $norte_id = $local_info['n'];
        $leste_id = $local_info['l'];
        $sul_id = $local_info['s'];
        $oeste_id = $local_info['o'];

        $ids_vizinhos = array_filter([$norte_id, $leste_id, $sul_id, $oeste_id]);
        $tipos_vizinhos = [];

        if (!empty($ids_vizinhos)) {
            $inQuery = implode(',', array_map('intval', $ids_vizinhos));
            $sqlViz = "SELECT id2, tipo FROM mapasmed WHERE id2 IN ($inQuery) AND regiao = :regiao";
            $stmtViz = $pdo->prepare($sqlViz);
            $stmtViz->execute([':regiao' => $regiao_atual]);
            $tipos_vizinhos = $stmtViz->fetchAll(PDO::FETCH_KEY_PAIR); 
        }

        function analisarDirecao($id, $lista_tipos) {
            if (empty($id) || !isset($lista_tipos[$id])) return ['show' => false, 'is_mar' => false];
            $tipo = strtolower($lista_tipos[$id]);
            $is_mar = ($tipo === 'mar');
            return ['show' => !$is_mar, 'is_mar' => $is_mar];
        }

        $res = analisarDirecao($norte_id, $tipos_vizinhos); $show_n = $res['show']; if($res['is_mar']) $is_litoral=true;
        $res = analisarDirecao($leste_id, $tipos_vizinhos); $show_l = $res['show']; if($res['is_mar']) $is_litoral=true;
        $res = analisarDirecao($sul_id, $tipos_vizinhos); $show_s = $res['show']; if($res['is_mar']) $is_litoral=true;
        $res = analisarDirecao($oeste_id, $tipos_vizinhos); $show_o = $res['show']; if($res['is_mar']) $is_litoral=true;
    }
    
    // 6. Histórico
    $sqlMessages = "SELECT id, acao, dataehora, vz FROM acoespersonagens WHERE personagem = :personagem ORDER BY dataehora DESC LIMIT 30";
    $stmtMessages = $pdo->prepare($sqlMessages);
    $stmtMessages->bindParam(':personagem', $nomePersonagem, PDO::PARAM_STR);
    $stmtMessages->execute();
    $messages = $stmtMessages->fetchAll(PDO::FETCH_ASSOC);
    
    // Update VZ (Visualizado)
    $idsParaAtualizar = array_column(array_filter($messages, function($m) { return $m['vz'] == 0; }), 'id');
    if (!empty($idsParaAtualizar)) {
        $placeholders = implode(',', array_fill(0, count($idsParaAtualizar), '?'));
        $pdo->prepare("UPDATE acoespersonagens SET vz = 1 WHERE id IN ($placeholders)")->execute($idsParaAtualizar);
    }

    // --- LOGICA DE CLÃS E ORDENS ---
    $texto_og = "Nenhuma ordem geral ativa.";
    $info_og_display = ""; 
    $texto_om = "Nenhuma instrução momentânea.";
    $info_om_display = "";
    
    $mapa_cargos = [
        1 => 'Guardião da Vanguarda', 2 => 'Capitão do Mato', 3 => 'Capitão da Vanguarda',
        4 => 'Comandante da Guarda Real', 5 => 'Subcomandante', 6 => 'Comandante Oficial', 7 => '1º Ministro'
    ];
    $cargo_nome = $mapa_cargos[$cargo_id] ?? 'Recruta';

    if (!empty($cla) && $cla !== 'Nenhum') {
        try {
            $stmtId = $pdo->prepare("SELECT id FROM cla WHERE nome = :nome LIMIT 1");
            $stmtId->execute([':nome' => $cla]);
            $claData = $stmtId->fetch(PDO::FETCH_ASSOC);

            if ($claData) {
                $cid = $claData['id'];
                
                // Ordem Geral
                $stmtOG = $pdo->prepare("SELECT ordem, data, cargo, redator FROM cla_ordens WHERE cla_id = :cid AND tipo = 'G' ORDER BY data DESC LIMIT 1");
                $stmtOG->execute([':cid' => $cid]);
                $resOG = $stmtOG->fetch(PDO::FETCH_ASSOC);
                if ($resOG) {
                    $texto_og = $resOG['ordem'];
                    $c_og = $resOG['cargo'] ?? 1;
                    $n_og = $mapa_cargos[$c_og] ?? 'Membro';
                    $r_og = $resOG['redator'] ?? 'Anônimo';
                    $info_og_display = "<strong>Por: $r_og <span style='font-size:0.7rem'>($n_og)</span></strong><br><span style='font-size:0.7rem'>Em: " . date('d/m H:i', strtotime($resOG['data'])) . "</span>";
                }

                // Ordem Momentânea
                $stmtOM = $pdo->prepare("SELECT ordem, data, cargo, redator FROM cla_ordens WHERE cla_id = :cid AND tipo = 'M' ORDER BY data DESC LIMIT 1");
                $stmtOM->execute([':cid' => $cid]);
                $resOM = $stmtOM->fetch(PDO::FETCH_ASSOC);
                if ($resOM) {
                    $texto_om = $resOM['ordem'];
                    $c_om = $resOM['cargo'] ?? 1;
                    $n_om = $mapa_cargos[$c_om] ?? 'Membro';
                    $r_om = $resOM['redator'] ?? 'Anônimo';
                    $info_om_display = "<strong>Por: $r_om <span style='font-size:0.7rem'>($n_om)</span></strong><br><span style='font-size:0.7rem'>Em: " . date('d/m H:i', strtotime($resOM['data'])) . "</span>";
                }
            }
        } catch (Exception $e) { /* Silêncio */ }
    }
} else {
    // Se não tiver personagem ativo, redireciona
    header("Location:admpersonagens/ativarpersonagens.php"); exit();
}

// --- FUNÇÃO PARA COR DA BARRA ---
function getBarColor($val) {
    if ($val > 70) return '#00ffaa'; 
    if ($val > 30) return '#ffaa00'; 
    return '#ff3333';
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>RPG ERA MEDIEVAL: Dervian</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@400;700&family=Roboto:wght@400;700&display=swap" rel="stylesheet">
    
    <style>
        /* === TEMA MÁGICO / DARK (ARCANE UI) === */
        :root {
            --bg-dark: #0a0510;
            --bg-panel: rgba(20, 10, 30, 0.95);
            --bg-glass: rgba(30, 15, 45, 0.7);
            --primary: #9d4edd; /* Roxo Mágico */
            --accent: #ff9e00;  /* Dourado Fogo */
            --success: #00ff66;
            --danger: #ff3333;
            --font-title: 'Cinzel', serif;
            --font-body: 'Roboto', sans-serif;
            --nav-height: 60px;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; outline: none; }
        
        body {
            background: var(--bg-dark) url('../rpg-login-background.jpg') center/cover fixed;
            color: #fff;
            font-family: var(--font-body);
            overflow: hidden; /* App style */
            height: 100vh;
            width: 100vw;
            display: flex; flex-direction: column;
        }

        .backdrop { position: absolute; top:0; left:0; width:100%; height:100%; background: rgba(5, 2, 10, 0.85); z-index: -1; }

        /* === 1. TOP HUD (STATUS BAR) === */
        .top-hud {
            height: 75px; flex-shrink: 0;
            display: flex; align-items: center; justify-content: space-between;
            padding: 0 15px;
            background: linear-gradient(180deg, rgba(0,0,0,1) 0%, rgba(0,0,0,0) 100%);
            z-index: 100;
        }

        .char-wrapper { position: relative; width: 55px; height: 55px; }
        .char-aura {
            position: absolute; top:-5px; left:-5px; width:120%; height:120%; border-radius: 50%;
            background: radial-gradient(circle, var(--primary) 0%, transparent 70%);
            animation: pulseAura 3s infinite;
        }
        .char-img {
            width: 100%; height: 100%; border-radius: 50%; border: 2px solid var(--accent);
            position: relative; z-index: 2; object-fit: cover; background: #000;
            animation: breathe 4s ease-in-out infinite;
        }
        
        @keyframes breathe { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } }
        @keyframes pulseAura { 0% { opacity: 0.3; transform: scale(1); } 50% { opacity: 0.6; transform: scale(1.2); } 100% { opacity: 0.3; transform: scale(1); } }

        .char-info-col { flex-grow: 1; margin-left: 15px; display: flex; flex-direction: column; justify-content: center; }
        .char-name { font-family: var(--font-title); font-size: 0.9rem; color: var(--primary); text-transform: uppercase; margin-bottom: 5px; }
        
        .stat-bar-box { display: flex; align-items: center; gap: 8px; width: 100%; max-width: 150px; height: 6px; background: rgba(255,255,255,0.1); border-radius: 3px; overflow: hidden; margin-bottom: 4px; }
        .progress-fill { height: 100%; border-radius: 3px; transition: width 0.5s; }

        .top-actions { display: flex; gap: 15px; }
        .icon-btn { background: none; border: none; color: #fff; font-size: 1.2rem; cursor: pointer; position: relative; }
        .notif-badge { position: absolute; top: -5px; right: -5px; background: var(--danger); font-size: 0.6rem; padding: 2px 5px; border-radius: 10px; }

        /* === 2. MAIN CONTENT AREA (SCROLLABLE) === */
        .main-stage {
            flex-grow: 1; overflow-y: auto; padding: 15px; padding-bottom: 80px; /* Space for nav */
            position: relative;
        }

        /* Generic Card Style */
        .arcane-card {
            background: var(--bg-glass); border: 1px solid rgba(157, 78, 221, 0.3);
            border-radius: 12px; padding: 15px; margin-bottom: 15px;
            backdrop-filter: blur(5px); box-shadow: 0 4px 15px rgba(0,0,0,0.5);
            animation: slideUp 0.4s ease-out;
        }
        @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }

        .card-header {
            border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 8px; margin-bottom: 10px;
            font-family: var(--font-title); color: var(--accent); font-size: 1rem;
            display: flex; justify-content: space-between;
        }

        /* === MAPA GRID STYLE === */
        .map-grid {
            display: grid; grid-template-columns: repeat(6, 1fr); gap: 2px;
            border: 2px solid var(--primary); background: #000; padding: 2px;
            box-shadow: 0 0 15px rgba(157, 78, 221, 0.2); max-width: 400px; margin: 0 auto;
        }
        .map-tile { position: relative; aspect-ratio: 1/1; cursor: pointer; overflow: hidden; }
        .map-tile-img { width: 100%; height: 100%; object-fit: cover; filter: brightness(0.8); transition: 0.3s; }
        .map-tile:hover .map-tile-img { filter: brightness(1.2); transform: scale(1.1); }
        
        .tile-overlay {
            position: absolute; bottom: 0; left: 0; width: 100%;
            background: linear-gradient(0deg, rgba(0,0,0,0.9) 0%, transparent 100%);
            color: #fff; font-size: 0.55rem; text-align: center; pointer-events: none;
            padding-top: 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
        }
        .tile-marker {
            position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
            width: 70%; z-index: 5; filter: drop-shadow(0 0 5px var(--accent));
            animation: bounceMarker 2s infinite;
        }
        @keyframes bounceMarker { 0%, 100% { transform: translate(-50%, -50%); } 50% { transform: translate(-50%, -60%); } }

        /* === CONTROLS (D-PAD) === */
        .d-pad {
            display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
            width: 150px; margin: 15px auto;
        }
        .move-btn {
            background: rgba(255,255,255,0.05); border: 1px solid var(--primary); color: var(--primary);
            height: 45px; border-radius: 8px; cursor: pointer; font-size: 1.2rem;
            display: flex; align-items: center; justify-content: center;
        }
        .move-btn:active { background: var(--primary); color: #fff; box-shadow: 0 0 15px var(--primary); }
        .move-disabled { opacity: 0.3; pointer-events: none; border-color: #555; }

        /* === ACTION BUTTONS === */
        .action-btn {
            width: 100%; padding: 12px; margin-bottom: 8px;
            background: linear-gradient(45deg, #1a0b2e, #2e1a47);
            border: 1px solid var(--primary); border-radius: 6px;
            color: #fff; font-weight: bold; text-transform: uppercase; cursor: pointer;
            display: flex; align-items: center; justify-content: center; gap: 8px;
            transition: 0.2s; font-size: 0.9rem;
        }
        .action-btn:hover { border-color: var(--accent); color: var(--accent); box-shadow: 0 0 10px var(--accent); }
        .btn-danger { border-color: var(--danger); background: rgba(50, 0, 0, 0.6); }

        /* === BOTTOM NAV === */
        .bottom-nav {
            position: fixed; bottom: 0; left: 0; width: 100%; height: var(--nav-height);
            background: rgba(10, 5, 20, 0.98); border-top: 1px solid rgba(255,255,255,0.1);
            display: flex; justify-content: space-around; align-items: center; z-index: 200;
        }
        .nav-item {
            background: none; border: none; color: #666; font-size: 0.7rem;
            display: flex; flex-direction: column; align-items: center; gap: 4px;
            width: 20%; padding: 5px; cursor: pointer; transition: 0.3s;
        }
        .nav-item i { font-size: 1.4rem; transition: 0.3s; }
        .nav-item.active { color: var(--primary); text-shadow: 0 0 8px var(--primary); }
        .nav-item.active i { transform: translateY(-3px); color: var(--accent); }

        /* === VIEWS VISIBILITY === */
        .view-section { display: none; }
        .view-section.active { display: block; }

        /* === MODAL === */
        .modal-overlay {
            display: none; position: fixed; top:0; left:0; width:100%; height:100%;
            background: rgba(0,0,0,0.9); z-index: 1000; align-items: center; justify-content: center;
        }
        .modal-box {
            background: #111; border: 1px solid var(--accent); width: 90%; max-width: 350px;
            padding: 20px; border-radius: 10px; position: relative; text-align: center;
            box-shadow: 0 0 30px rgba(255, 158, 0, 0.2);
        }

        /* === TOASTS === */
        #toast-container { position: fixed; top: 80px; right: 10px; z-index: 3000; display: flex; flex-direction: column; gap: 8px; pointer-events: none; }
        .toast {
            background: rgba(0,0,0,0.9); border-left: 4px solid var(--primary); padding: 12px;
            color: #fff; box-shadow: 0 5px 15px rgba(0,0,0,0.5); border-radius: 4px;
            animation: slideIn 0.3s ease; pointer-events: auto; min-width: 250px;
        }
        @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }

        /* === TIMER BOX === */
        .timer-box {
            border: 2px solid var(--success); background: rgba(0, 20, 0, 0.6);
            padding: 15px; border-radius: 10px; text-align: center; margin-bottom: 20px;
        }
        .timer-nums { font-family: monospace; font-size: 1.8rem; color: var(--success); text-shadow: 0 0 10px var(--success); }
    </style>
</head>
<body>

<div class="backdrop"></div>

<header class="top-hud">
    <div class="char-wrapper">
        <div class="char-aura"></div>
        <img src="personagem.png" class="char-img" onerror="this.src='https://cdn-icons-png.flaticon.com/512/4825/4825038.png'">
    </div>
    
    <div class="char-info-col">
        <div class="char-name"><?= $nomePersonagem ?></div>
        
        <div class="stat-bar-box">
            <i class="fas fa-heart" style="color:#ff3333; font-size:0.7rem;"></i>
            <div class="progress-fill" style="width: <?= $hp_atual ?>%; background:#ff3333;"></div>
        </div>
        <div class="stat-bar-box">
            <i class="fas fa-utensils" style="color:#ffaa00; font-size:0.7rem;"></i>
            <div class="progress-fill" style="width: <?= $fome ?>%; background:#ffaa00;"></div>
        </div>
    </div>

    <div class="top-actions">
        <a href="pagina_notificacoesjogo.php">
            <button class="icon-btn"><i class="fas fa-bell"></i>
            <?php if($total_notificacoes > 0): ?><span class="notif-badge"><?= $total_notificacoes ?></span><?php endif; ?>
            </button>
        </a>
        <button class="icon-btn" onclick="if(confirm('Sair?')) location.href='logout.php'"><i class="fas fa-sign-out-alt"></i></button>
    </div>
</header>

<main class="main-stage">
    
    <?php if (!empty($_SESSION['msg'])): ?>
        <div class="arcane-card" style="border-color: var(--accent); color: var(--accent); text-align: center;">
            <i class="fas fa-scroll"></i> <?= htmlspecialchars($_SESSION['msg']) ?>
        </div>
        <?php $_SESSION['msg'] = ''; ?>
    <?php endif; ?>

    <div id="tab-map" class="view-section active">
        <div class="arcane-card" style="text-align: center;">
            <div class="card-header" style="justify-content: center;">
                <?= $nomelocal ?> <span style="font-size:0.8rem; color:#888; margin-left:10px;">(<?= $tipolocal ?>)</span>
            </div>
            
            <div class="map-grid">
                <?php
                // RECARREGA LOCAIS EM GUERRA
                $locais_invadidos = [];
                try {
                    $stmtInv = $pdo->query("SELECT local FROM guerra_dominio WHERE dominou = 0 AND (defensor IS NULL OR defensor = '') AND iniciou > DATE_SUB(NOW(), INTERVAL 7 MINUTE)");
                    $locais_invadidos = $stmtInv->fetchAll(PDO::FETCH_COLUMN);
                } catch (Exception $e) {}

                // QUERY DO MAPA (IMPORTANTE: INCLUI GOVERNANTE)
                $stmtMap = $pdo->query("SELECT nome, tipo, dominio, governante FROM mapasmed LIMIT 36");

                while ($m = $stmtMap->fetch(PDO::FETCH_ASSOC)) {
                    $nm = $m['nome'];
                    $tp = $m['tipo'];
                    $dm = $m['dominio'];
                    $gv = $m['governante'];
                    
                    $img = "fts/mapa/terreno/" . $tp . ".png";
                    $isYou = ($nm == $local);
                    $isWar = in_array($nm, $locais_invadidos);
                    
                    // ATRIBUTOS PARA O MODAL JS
                    $dataAttrs = "data-nome='$nm' data-cla='$dm' data-gov='$gv'";
                    
                    echo "<div class='map-tile' onclick='openCityModal(this)' $dataAttrs>";
                    echo "<img src='$img' class='map-tile-img'>";
                    
                    // Bandeira Clã
                    if ($dm && $dm !== 'Nenhum') {
                        echo "<img src='cla/fts/bandeiras/$dm.png' style='position:absolute; top:2px; left:2px; width:40%; filter:drop-shadow(1px 1px 1px #000);' onerror='this.style.display=\"none\"'>";
                    }
                    // Fogo (Guerra)
                    if ($isWar) {
                        echo "<img src='fts/mapa/icones/fire.png' style='position:absolute; top:2px; right:2px; width:15px; animation:pulseAura 0.5s infinite;'>";
                    }
                    // Marcador Personagem
                    if ($isYou) {
                        echo "<img src='personagem.png' class='tile-marker'>";
                    }
                    
                    // Nome Overlay
                    echo "<div class='tile-overlay'>$nm</div>";
                    echo "</div>";
                }
                ?>
            </div>

            <?php if ($situacao == "livre" || $situacao == ''): ?>
                <form action="personagem/acoes/moverperson.php" method="post" class="d-pad">
                    <input type="hidden" name="mover" value="1">
                    
                    <div></div>
                    <?php if($show_n): ?><button name="direcao" value="<?= $norte_id ?>" class="move-btn"><i class="fas fa-caret-up"></i></button><?php else: ?><div class="move-btn move-disabled"><i class="fas fa-ban"></i></div><?php endif; ?>
                    <div></div>
                    
                    <?php if($show_o): ?><button name="direcao" value="<?= $oeste_id ?>" class="move-btn"><i class="fas fa-caret-left"></i></button><?php else: ?><div class="move-btn move-disabled"><i class="fas fa-ban"></i></div><?php endif; ?>
                    <div style="display:flex; align-items:center; justify-content:center; opacity:0.5;"><i class="fas fa-walking"></i></div>
                    <?php if($show_l): ?><button name="direcao" value="<?= $leste_id ?>" class="move-btn"><i class="fas fa-caret-right"></i></button><?php else: ?><div class="move-btn move-disabled"><i class="fas fa-ban"></i></div><?php endif; ?>
                    
                    <div></div>
                    <?php if($show_s): ?><button name="direcao" value="<?= $sul_id ?>" class="move-btn"><i class="fas fa-caret-down"></i></button><?php else: ?><div class="move-btn move-disabled"><i class="fas fa-ban"></i></div><?php endif; ?>
                    <div></div>
                </form>
            <?php else: ?>
                <div style="margin-top:15px; color:#aaa; font-style:italic;">Movimento bloqueado.</div>
            <?php endif; ?>
        </div>
    </div>

    <div id="tab-char" class="view-section">
        <div class="arcane-card">
            <div class="card-header">Recursos & Estatísticas</div>
            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:10px;">
                <div style="background:rgba(255,255,255,0.05); padding:8px; border-radius:5px;">
                    <span style="font-size:0.7rem; color:#aaa;">ATK / DEF</span><br>
                    <span style="font-size:1.1rem; color:#fff;"><?= $atk ?> / <?= $def ?></span>
                </div>
                <div style="background:rgba(255,255,255,0.05); padding:8px; border-radius:5px;">
                    <span style="font-size:0.7rem; color:#aaa;">SOLDADOS</span><br>
                    <span style="font-size:1.1rem; color:#fff;"><?= $soldados ?></span>
                </div>
                <div style="background:rgba(255,255,255,0.05); padding:8px; border-radius:5px;">
                    <span style="font-size:0.7rem; color:#aaa;">CARNE</span><br>
                    <span style="font-size:1.1rem; color:var(--accent);"><?= $carne ?></span>
                </div>
                <div style="background:rgba(255,255,255,0.05); padding:8px; border-radius:5px;">
                    <span style="font-size:0.7rem; color:#aaa;">MADEIRA</span><br>
                    <span style="font-size:1.1rem; color:var(--accent);"><?= $madeira ?></span>
                </div>
            </div>
        </div>

        <div class="arcane-card">
            <div class="card-header">Sobrevivência</div>
            <?php if ($carne > 0): ?>
                <form action="personagem/acoes/alimentar.php" method="POST">
                    <button type="submit" class="action-btn"><i class="fas fa-drumstick-bite"></i> Alimentar-se</button>
                </form>
            <?php endif; ?>
            
            <?php if ($is_litoral): ?>
                <form action="personagem/acoes/beberagua.php" method="POST">
                    <button type="submit" class="action-btn" style="border-color:#00d2ff; color:#00d2ff;"><i class="fas fa-tint"></i> Beber Água</button>
                </form>
            <?php endif; ?>
            
            <div style="margin-top:10px; font-size:0.8rem; color:#aaa;">
                Fome: <?= $fome ?>% | Sede: <?= $sede ?>%
            </div>
        </div>
    </div>

    <div id="tab-actions" class="view-section">
        
        <?php
        $agora = time();
        $fim = strtotime($paralisado);
        $segundos = $fim - $agora;

        // LÓGICA DE FINALIZAR AÇÃO (MANTIDA 100%)
        $action = ''; $btnTxt = '';
        if ($situacao == "trabalhando") { $action = "personagem/acoes/pegarpg.php"; $btnTxt = "Receber Salário ($)"; }
        elseif ($situacao == "caçando") { $action = "personagem/acoes/finalisarcaca.php"; $btnTxt = "Recolher Caça"; }
        elseif ($situacao == "pegando madeira") { $action = "personagem/acoes/finalisarlenha.php"; $btnTxt = "Recolher Madeira"; }
        elseif ($situacao == "treinandoATK") { $action = "personagem/acoes/finalisartreinoatk.php"; $btnTxt = "Finalizar Treino ATK"; }
        elseif ($situacao == "treinandoDEF") { $action = "personagem/acoes/finalisartreinodef.php"; $btnTxt = "Finalizar Treino DEF"; }
        elseif ($situacao == "Invadindo cidade") { $action = "admcity/finalizar_dominio.php"; $btnTxt = "Concluir Invasão"; }
        elseif ($situacao == "pescando") { $action = "personagem/acoes/finalisarpesca.php"; $btnTxt = "Recolher Rede"; }
        elseif ($situacao == "bebendoagua") { $action = "personagem/acoes/finalisarbeberagua.php"; $btnTxt = "Voltar à Ativa"; }
        elseif ($situacao == "alimentando") { $action = "personagem/acoes/alimentar_finalizar.php"; $btnTxt = "Voltar à Ativa"; }
        elseif (in_array($situacao, ["fugindo e reagrupando soldados", "reagrupando soldados", "escondido"])) { $action = "personagem/acoes/aparecer.php"; $btnTxt = "Aparecer"; }
        ?>

        <?php if ($segundos > 0): ?>
            <div class="timer-box" id="timer-wrapper">
                <div style="text-transform:uppercase; font-size:0.8rem; margin-bottom:5px; color:#fff;"><?= $situacao ?></div>
                <div id="timer-display" class="timer-nums">--:--:--</div>
            </div>
        <?php elseif (!empty($action) && $situacao != "livre" && $situacao != ''): ?>
            <form action="<?= $action ?>" method="POST">
                <input type="hidden" name="local" value="treino">
                <button type="submit" class="action-btn" style="background:#003300; border-color:var(--success); color:var(--success); font-size:1.1rem; padding:15px; animation: pulseAura 1.5s infinite;">
                    <i class="fas fa-check"></i> <?= $btnTxt ?>
                </button>
            </form>
        <?php endif; ?>

        <div class="arcane-card">
            <div class="card-header">Interagir no Local</div>
            
            <button class="action-btn" onclick="openPeopleModal()" style="border-color:#fff;"><i class="fas fa-eye"></i> Observar Pessoas</button>
            
            <?php if ($situacao == "livre" || $situacao == ''): ?>
                
                <?php if ($tipolocal == "city"): ?>
                    <form action="trabalhar.php" method="POST">
                        <button type="submit" name="trabalhar" class="action-btn" onclick="return confirm('Trabalhar?')"><i class="fas fa-hammer"></i> Trabalhar</button>
                    </form>
                    
                    <div style="display:flex; gap:5px;">
                        <form action="personagem/acoes/contratar.php" method="POST" style="flex:1">
                            <input type="number" name="quantidade" min="1" placeholder="Qtd" style="width:100%; margin-bottom:5px; padding:5px; border-radius:4px; border:1px solid #555; background:#000; color:#fff;">
                            <button type="submit" name="contratar" class="action-btn" style="font-size:0.7rem;">Contratar</button>
                        </form>
                        <form action="personagem/acoes/vendercarne.php" method="POST" style="flex:1">
                            <input type="number" name="quantidade" min="1" max="<?= $carne ?>" placeholder="Carne" style="width:100%; margin-bottom:5px; padding:5px; border-radius:4px; border:1px solid #555; background:#000; color:#fff;">
                            <button type="submit" name="vendercarne" class="action-btn btn-danger" style="font-size:0.7rem;">Vender</button>
                        </form>
                    </div>

                    <?php if (isset($cla) && ($cla != $dominio_local)): ?>
                        <form action="admcity/dominar.php" method="POST" onsubmit="return confirm('Iniciar invasão? Alto Risco!')">
                            <input type="hidden" name="local_alvo" value="<?= htmlspecialchars($local); ?>">
                            <button type="submit" class="action-btn btn-danger" style="margin-top:10px;"><i class="fas fa-skull"></i> INVADIR CIDADE</button>
                        </form>
                    <?php endif; ?>

                    <?php if (isset($cla) && ($governante_local == $personagem)): ?>
                        <button type="button" class="action-btn"><i class="fas fa-coins"></i> Cobrar Impostos</button>
                    <?php endif; ?>

                <?php endif; ?>

                <?php if ($tipolocal == "campo"): ?>
                    <form action="treinaratk.php" method="POST"><button type="submit" name="treinar" class="action-btn"><i class="fas fa-fist-raised"></i> Treinar Ataque</button></form>
                    <form action="treinardef.php" method="POST"><button type="submit" name="treinar" class="action-btn"><i class="fas fa-shield-alt"></i> Treinar Defesa</button></form>
                <?php endif; ?>

                <?php if ($tipolocal == "mata"): ?>
                    <form action="personagem/acoes/caca.php" method="POST"><button type="submit" name="caca" class="action-btn"><i class="fas fa-paw"></i> Caçar</button></form>
                    <form action="personagem/acoes/lenhar.php" method="POST"><button type="submit" name="lenhar" class="action-btn"><i class="fas fa-tree"></i> Lenhar</button></form>
                <?php endif; ?>

            <?php endif; ?>
        </div>
    </div>

    <div id="tab-social" class="view-section">
        <div class="arcane-card" style="padding:0; overflow:hidden; display:flex; flex-direction:column; height:350px;">
            <div style="padding:10px; background:rgba(0,0,0,0.5); border-bottom:1px solid #333;">Chat Local</div>
            <iframe src="chat_firebase.php" style="border:none; width:100%; flex-grow:1;"></iframe>
        </div>

        <div class="arcane-card">
            <div class="card-header">Clã: <?= $cla ?></div>
            <?php if ($cla && $cla != 'Nenhum'): ?>
                <div style="margin-bottom:10px; font-style:italic; color:#ccc;">"<?= $texto_og ?>"</div>
                <div style="display:flex; gap:5px;">
                    <a href="cla/acoes/lista_membros_cla.php" style="flex:1"><button class="action-btn">Membros</button></a>
                    <?php if ($cargo_id >= 3): ?>
                        <a href="cla/acoes/ordens_cla.php" style="flex:1"><button class="action-btn">Ordens</button></a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <p>Você não possui clã.</p>
                <a href="clas.php"><button class="action-btn">Procurar Clã</button></a>
            <?php endif; ?>
        </div>
    </div>

    <div id="tab-logs" class="view-section">
        <div class="arcane-card">
            <div class="card-header">Histórico Pessoal</div>
            <div style="height:300px; overflow-y:auto; font-size:0.8rem;">
                <?php foreach ($messages as $msg): ?>
                    <div style="border-bottom:1px solid rgba(255,255,255,0.1); padding:5px;">
                        <span style="color:#888;"><?= date('H:i', strtotime($msg['dataehora'])) ?></span>
                        <?= $msg['acao'] ?>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <div class="arcane-card">
            <div class="card-header">Notificações Globais/Clã</div>
            <div id="log-content-ajax" style="color:#aaa;">Carregando...</div>
        </div>
    </div>

</main>

<nav class="bottom-nav">
    <button class="nav-item active" onclick="goTab('tab-map', this)"><i class="fas fa-map"></i>Map</button>
    <button class="nav-item" onclick="goTab('tab-char', this)"><i class="fas fa-user"></i>Eu</button>
    <button class="nav-item" onclick="goTab('tab-actions', this)"><i class="fas fa-hand-sparkles"></i>Ações</button>
    <button class="nav-item" onclick="goTab('tab-social', this)"><i class="fas fa-users"></i>Social</button>
    <button class="nav-item" onclick="goTab('tab-logs', this)"><i class="fas fa-scroll"></i>Logs</button>
</nav>

<div id="cityModal" class="modal-overlay" onclick="if(event.target==this) closeCityModal()">
    <div class="modal-box">
        <h2 id="modal-city-name" style="color:var(--accent); margin-bottom:5px;">Cidade</h2>
        <div style="width:100%; height:1px; background:var(--accent); margin-bottom:15px;"></div>
        
        <div style="display:flex; justify-content:center; margin-bottom:15px;">
            <img id="modal-clan-img" src="" style="width:80px; height:80px; border-radius:50%; border:2px solid #fff; display:none;">
            <div id="modal-clan-none" style="width:80px; height:80px; border-radius:50%; border:2px dashed #555; display:flex; align-items:center; justify-content:center; color:#555;">Sem Clã</div>
        </div>

        <p><strong>Dominado por:</strong> <br> <span id="modal-clan-name" style="font-size:1.2rem; color:var(--primary);">--</span></p>
        <p style="margin-top:10px;"><strong>Governante:</strong> <br> <span id="modal-gov-name" style="color:#ccc;">--</span></p>

        <button class="action-btn" style="margin-top:20px;" onclick="closeCityModal()">Fechar</button>
    </div>
</div>

<div id="peopleModal" class="modal-overlay" onclick="if(event.target==this) document.getElementById('peopleModal').style.display='none'">
    <div class="modal-box">
        <h3 style="color:var(--primary);">Pessoas no Local</h3>
        <div id="people-content" style="max-height:200px; overflow-y:auto; margin-top:10px; text-align:left;"></div>
        <button class="action-btn" style="margin-top:10px;" onclick="document.getElementById('peopleModal').style.display='none'">Fechar</button>
    </div>
</div>

<div id="toast-container"></div>

<script>
    // --- NAVEGAÇÃO SPA ---
    function goTab(id, btn) {
        document.querySelectorAll('.view-section').forEach(e => e.classList.remove('active'));
        document.querySelectorAll('.nav-item').forEach(e => e.classList.remove('active'));
        document.getElementById(id).classList.add('active');
        btn.classList.add('active');
    }

    // --- LÓGICA DO MODAL CIDADE ---
    function openCityModal(el) {
        let nome = el.getAttribute('data-nome');
        let cla = el.getAttribute('data-cla');
        let gov = el.getAttribute('data-gov') || "Ninguém";

        document.getElementById('modal-city-name').innerText = nome;
        document.getElementById('modal-clan-name').innerText = cla || "Nenhum";
        document.getElementById('modal-gov-name').innerText = gov;
        
        let img = document.getElementById('modal-clan-img');
        let divNone = document.getElementById('modal-clan-none');
        
        if(cla && cla !== 'Nenhum') {
            img.src = 'cla/fts/bandeiras/' + cla + '.png';
            img.style.display = 'block';
            divNone.style.display = 'none';
        } else {
            img.style.display = 'none';
            divNone.style.display = 'flex';
        }
        document.getElementById('cityModal').style.display = 'flex';
    }

    function closeCityModal() { document.getElementById('cityModal').style.display = 'none'; }

    function openPeopleModal() {
        let c = document.getElementById('people-content');
        document.getElementById('peopleModal').style.display = 'flex';
        c.innerHTML = 'Carregando...';
        fetch('jogo/quemestanolocal.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:'local=<?= urlencode($local) ?>' })
        .then(r=>r.text()).then(t=>{ c.innerHTML = t; });
    }

    // --- LOGS & NOTIFICAÇÕES (Lógica Corrigida para não spammar no inicio) ---
    let firstLoad = true; 
    let lastLogId = 0;

    function updateLogs() {
        let fd = new FormData();
        fd.append('cla', '<?= $cla ?>');
        fd.append('local', '<?= $local ?>');
        
        fetch('jogo/api_ocorrencias.php', { method:'POST', body:fd })
        .then(r=>r.json())
        .then(data => {
            // Renderiza na aba Logs
            let lista = data.geral || [];
            let html = '';
            lista.forEach(i => {
                html += `<div><span style="color:#888; font-size:0.7rem;">${i.data.substring(11,16)}</span> ${i.situacao}</div>`;
            });
            document.getElementById('log-content-ajax').innerHTML = html || "Nada recente.";

            // Alerta Toast (Somente se for novo e não for firstLoad)
            if (lista.length > 0) {
                let newestId = parseInt(lista[0].id);
                if (!firstLoad && newestId > lastLogId) {
                    showToast("Nova Ocorrência", lista[0].situacao);
                }
                lastLogId = newestId;
            }
            firstLoad = false;
        }).catch(e=>{});
    }

    function showToast(tit, txt) {
        let c = document.getElementById('toast-container');
        let t = document.createElement('div');
        t.className = 'toast';
        t.innerHTML = `<strong>${tit}</strong><br>${txt}`;
        c.prepend(t);
        // new Audio('beep.mp3').play().catch(e=>{}); // Opcional: Som
        setTimeout(() => t.remove(), 5000);
    }

    // Timer JS (Sincronizado com PHP)
    <?php if ($segundos > 0): ?>
    let timeLeft = <?= $segundos ?>;
    let timerInt = setInterval(() => {
        if(timeLeft <= 0) { clearInterval(timerInt); location.reload(); return; }
        let h = Math.floor(timeLeft/3600);
        let m = Math.floor((timeLeft%3600)/60);
        let s = timeLeft%60;
        document.getElementById('timer-display').innerText = 
            (h<10?'0':'')+h + ":" + (m<10?'0':'')+m + ":" + (s<10?'0':'')+s;
        timeLeft--;
    }, 1000);
    <?php endif; ?>

    // Loops do Sistema
    setInterval(updateLogs, 10000); // Logs a cada 10s
    updateLogs(); // Primeira execução imediata
    
    // Check de Mudança de Status (Reload automático se acabar timer no backend)
    let currentStatus = "<?= $situacao ?>";
    setInterval(() => {
        fetch('sistema/scripts/verificar_status_situacao_personagem.php').then(r=>r.text()).then(s=>{
            if(s.trim() && s.trim() !== currentStatus) location.reload();
        });
    }, 4000);
    
    // Verificação de Ataque ao Governo (Lógica Original Resgatada)
    <?php if ($nomePersonagem !== 'Ninguém' && $nomePersonagem !== ''): ?>
    let govAttackInterval = setInterval(() => {
        let fd = new FormData(); fd.append('cla', '<?= $cla ?>'); fd.append('local', '<?= $local ?>');
        fetch('personagem/acoes/check_ataque_governo.php', { method:'POST', body:fd })
        .then(r=>r.json()).then(d => {
            if(d.atacado && d.locais.length > 0) showToast("ALERTA DE GUERRA!", "Cidades atacadas: "+d.locais.join(', '));
        }).catch(e=>{});
    }, 60000);
    <?php endif; ?>

</script>
</body>
</html>