<?php
declare(strict_types=1);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// ✅ SESSION UNIFIÉE (source unique)
require_once __DIR__ . '/includes/session_init.php';

// --- 1. SÉCURITÉ & ERREURS ---
ini_set('display_errors', '0');
error_reporting(E_ALL);

// --- 2. AUTOLOAD + ENV ---
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
} else {
    die("Erreur critique : Vendor introuvable.");
}

try {
    $dotenv = Dotenv\Dotenv::createImmutable('/etc/teth-ws/');
    $dotenv->load();
} catch (Exception $e) {
    error_log("Erreur .env : " . $e->getMessage());
}

define('RECAPTCHA_SITE_KEY', $_ENV['RECAPTCHA_SITE_KEY'] ?? '');
define('RECAPTCHA_SECRET_KEY', $_ENV['RECAPTCHA_SECRET_KEY'] ?? '');

// --- 3. DB ---
try {
    require_once __DIR__ . '/includes/db.php';
} catch (Exception $e) {
    die("Erreur critique : db.php introuvable");
}

// --- 4. RATE LIMITER (OPTIONNEL) ---
$rateLimiterAvailable = false;
$rateLimiter = null;
if (file_exists(__DIR__ . '/includes/RateLimiterRedis.php')) {
    try {
        require_once __DIR__ . '/includes/RateLimiterRedis.php';
        $rateLimiter = new RateLimiterRedis();
        $rateLimiterAvailable = true;
    } catch (Exception $e) {
        error_log("Connexion: RateLimiter indisponible - " . $e->getMessage());
    }
}

// --- 5. VARIABLES ---
$user_ip = $_SERVER['REMOTE_ADDR'] ?? '';
$message = '';
$action = (string)($_POST['action'] ?? '');
$show_success = (string)($_GET['activated'] ?? '');
$displayed_country = 'République démocratique du Congo';
$show_captcha = false;

// --- 6. RECAPTCHA ---
function verify_recaptcha(string $token): bool
{
    $secret = RECAPTCHA_SECRET_KEY;
    if ($secret === '' || $token === '') return false;

    $url = "https://www.google.com/recaptcha/api/siteverify?secret=" . urlencode($secret) . "&response=" . urlencode($token);
    $response = @file_get_contents($url);
    if ($response === false) return false;

    $data = json_decode($response, true);
    return isset($data['success']) && $data['success'] === true;
}

// --- 7. TRAITEMENT ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!teth_verify_csrf()) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        die("Erreur de sécurité : Session expirée. Veuillez <a href='connexion.php'>rafraîchir la page</a> et réessayer.");
    }

    // ----------------------------
    // LOGIN
    // ----------------------------
    if ($action === 'login') {
        $email = trim((string)($_POST['email'] ?? ''));
        $password = (string)($_POST['password'] ?? '');

        if ($email === '' || $password === '') {
            $message = "Email et mot de passe requis";
        } else {
            $db = get_db();
            $stmt = $db->prepare("SELECT id, email, motdepasse, surnom_de_jeux, pieces, portefeuille, pays, ville, actif, tentatives_echouees, derniere_tentative, compte_verrouille_jusque FROM utilisateurs WHERE email = ? LIMIT 1");
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if (!$user) {
                $message = "Email ou mot de passe incorrect";
            } elseif ((int)$user['actif'] !== 1) {
                $message = "Compte non activé. Vérifiez votre email.";
            } else {
                $now = time();
                $tentatives = (int)($user['tentatives_echouees'] ?? 0);
                $verrouille_jusque = (int)($user['compte_verrouille_jusque'] ?? 0);

                if ($verrouille_jusque > $now) {
                    $minutes_restantes = (int)ceil(($verrouille_jusque - $now) / 60);
                    $message = "Compte temporairement verrouillé. Réessayez dans {$minutes_restantes} minutes.";
                    $show_captcha = true;
                } else {

                    $need_captcha = ($tentatives >= 3);
                    if ($need_captcha) {
                        $recaptcha_response = (string)($_POST['g-recaptcha-response'] ?? '');
                        if ($recaptcha_response === '' || !verify_recaptcha($recaptcha_response)) {
                            $message = "Veuillez compléter le captcha de sécurité.";
                            $show_captcha = true;
                            goto end_login;
                        }
                    }

                    if (!empty($user['motdepasse']) && password_verify($password, (string)$user['motdepasse'])) {

                        $st = $db->prepare("UPDATE utilisateurs SET tentatives_echouees = 0, compte_verrouille_jusque = 0 WHERE id = ?");
                        $uid = (int)$user['id'];
                        $st->bind_param('i', $uid);
                        $st->execute();
                        $st->close();

                        session_regenerate_id(true);

                        $_SESSION['user_id'] = (int)$user['id'];
                        $_SESSION['email'] = (string)$user['email'];
                        $_SESSION['surnom_de_jeux'] = (string)($user['surnom_de_jeux'] ?? '');
                        $_SESSION['pieces'] = (int)($user['pieces'] ?? 0);
                        $_SESSION['portefeuille'] = (float)($user['portefeuille'] ?? 0);
                        $_SESSION['pays'] = (string)($user['pays'] ?? 'Non détecté');
                        $_SESSION['ville'] = (string)($user['ville'] ?? '');
                        $_SESSION['last_activity'] = $now;

                        header("Location: espace_client.php");
                        exit;
                    }

                    $tentatives++;
                    $show_captcha = ($tentatives >= 3);

                    if ($tentatives >= 3) {
                        $verrouille = $now + 3600;
                        $st = $db->prepare("UPDATE utilisateurs SET tentatives_echouees = ?, derniere_tentative = ?, compte_verrouille_jusque = ? WHERE id = ?");
                        $uid = (int)$user['id'];
                        $st->bind_param('iiii', $tentatives, $now, $verrouille, $uid);
                        $st->execute();
                        $st->close();
                        $message = "Trop de tentatives échouées. Compte verrouillé pendant 1 heure.";
                    } else {
                        $st = $db->prepare("UPDATE utilisateurs SET tentatives_echouees = ?, derniere_tentative = ? WHERE id = ?");
                        $uid = (int)$user['id'];
                        $st->bind_param('iii', $tentatives, $now, $uid);
                        $st->execute();
                        $st->close();
                        $restantes = 3 - $tentatives;
                        $message = "Email ou mot de passe incorrect. ({$restantes} tentative(s) restante(s))";
                    }
                }
            }
        }
        end_login:
    }

    // ----------------------------
    // REGISTER
    // ----------------------------
    if ($action === 'register') {
        $email = trim((string)($_POST['email'] ?? ''));
        $telephone = trim((string)($_POST['telephone'] ?? ''));

        $register_key_ip = "register:ip:" . $user_ip;
        $register_key_phone = "register:phone:" . $telephone;

        $ip_blocked = $rateLimiterAvailable && $rateLimiter && !$rateLimiter->check($register_key_ip, 5, 3600);
        $phone_blocked = $rateLimiterAvailable && $rateLimiter && $telephone !== '' && !$rateLimiter->check($register_key_phone, 1, 3600);

        if ($ip_blocked) {
            http_response_code(429);
            $message = "Trop d'inscriptions depuis cette connexion. Réessayez dans 1 heure.";
        } elseif ($phone_blocked) {
            http_response_code(429);
            $message = "Ce numéro a déjà tenté une inscription. Réessayez dans 1 heure.";
        } else {
            if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $message = "Email invalide";
            } elseif ($telephone === '' || !preg_match('/^[0-9]{9,15}$/', $telephone)) {
                $message = "Numéro de téléphone invalide (9-15 chiffres)";
            } else {
                $db = get_db();

                $stmt = $db->prepare("SELECT id FROM utilisateurs WHERE email = ? LIMIT 1");
                $stmt->bind_param('s', $email);
                $stmt->execute();
                $exists_email = $stmt->get_result()->fetch_assoc();
                $stmt->close();

                if ($exists_email) {
                    $message = "Cet email est déjà utilisé";
                } else {
                    $stmt = $db->prepare("SELECT id FROM utilisateurs WHERE telephone = ? LIMIT 1");
                    $stmt->bind_param('s', $telephone);
                    $stmt->execute();
                    $exists_tel = $stmt->get_result()->fetch_assoc();
                    $stmt->close();

                    if ($exists_tel) {
                        $message = "Ce numéro de téléphone est déjà utilisé";
                    } else {
                        $token = bin2hex(random_bytes(32));
                        $expiration = time() + 86400;
                        $code_parrain = strtoupper(substr(md5($email . time()), 0, 8));

                        $stmt = $db->prepare("INSERT INTO utilisateurs (email, telephone, code_parrain, token_activation, token_expiration, actif, pieces, portefeuille, tentatives_echouees, compte_verrouille_jusque) VALUES (?, ?, ?, ?, ?, 0, 0, 0, 0, 0)");
                        $stmt->bind_param('ssssi', $email, $telephone, $code_parrain, $token, $expiration);

                        if ($stmt->execute()) {
                            $app_url = $_ENV['APP_URL'] ?? 'https://php.parisintellectuel.com';
                            $activation_url = $app_url . "/activation.php?token=" . urlencode($token);

                            $body = "<!DOCTYPE html><html lang='fr'><head><meta charset='UTF-8'><style>body{margin:0;padding:20px 0;background:#f5f5f5;font-family:Arial,sans-serif;}.container{max-width:420px;margin:0 auto;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 4px 16px rgba(0,0,0,.1);}.header{padding:24px 20px 18px;text-align:center;background:#fff;border-bottom:2px solid #00bfa6;}.title{color:#008080;font-size:24px;font-weight:bold;margin:0 0 6px;}.subtitle{color:#666;font-size:14px;font-style:italic;}.body{padding:20px 24px 24px;}.body p{margin:0 0 14px;font-size:14px;color:#333;line-height:1.6;}.highlight{color:#ff6b00;font-weight:bold;}.btn-wrap{text-align:center;margin:20px 0 14px;}.btn{display:inline-block;padding:12px 28px;border-radius:999px;background:linear-gradient(135deg,#008080,#00bfa6);color:#fff;text-decoration:none;font-weight:600;font-size:14px;box-shadow:0 4px 12px rgba(0,128,128,.3);}.info{font-size:12px;color:#6b7280;margin:12px 0 0;text-align:center;line-height:1.4;}.footer{padding:12px 20px;background:#f0f9f9;text-align:center;color:#6b7280;font-size:11px;}

/* =========================================================
   AJUSTEMENT FINAL VALIDATION — MOBILE SANS VIDE + PLUS DE TROUS
========================================================= */
.container{
  height:auto!important;
  min-height:0!important;
  max-height:calc(100svh - 8px)!important;
  padding:10px!important;
  background:
    radial-gradient(circle at 6% 6%,rgba(2,8,23,.88) 0 .95px,transparent 1.65px),
    radial-gradient(circle at 14% 12%,rgba(255,183,3,.48) 0 .75px,transparent 1.45px),
    radial-gradient(circle at 25% 7%,rgba(2,8,23,.78) 0 1.15px,transparent 1.85px),
    radial-gradient(circle at 35% 15%,rgba(0,89,96,.66) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 48% 8%,rgba(2,8,23,.86) 0 1px,transparent 1.75px),
    radial-gradient(circle at 59% 15%,rgba(255,183,3,.42) 0 .75px,transparent 1.45px),
    radial-gradient(circle at 72% 7%,rgba(2,8,23,.86) 0 1.1px,transparent 1.85px),
    radial-gradient(circle at 86% 13%,rgba(0,89,96,.68) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 95% 7%,rgba(2,8,23,.84) 0 1px,transparent 1.8px),
    radial-gradient(circle at 9% 24%,rgba(0,89,96,.66) 0 .9px,transparent 1.55px),
    radial-gradient(circle at 20% 29%,rgba(2,8,23,.86) 0 1.25px,transparent 2px),
    radial-gradient(circle at 31% 23%,rgba(255,183,3,.42) 0 .75px,transparent 1.5px),
    radial-gradient(circle at 44% 31%,rgba(2,8,23,.76) 0 1px,transparent 1.7px),
    radial-gradient(circle at 57% 25%,rgba(0,89,96,.66) 0 .85px,transparent 1.55px),
    radial-gradient(circle at 68% 33%,rgba(2,8,23,.84) 0 1.15px,transparent 1.9px),
    radial-gradient(circle at 82% 25%,rgba(255,183,3,.48) 0 .75px,transparent 1.45px),
    radial-gradient(circle at 93% 36%,rgba(2,8,23,.86) 0 1.05px,transparent 1.8px),
    radial-gradient(circle at 7% 43%,rgba(2,8,23,.80) 0 1px,transparent 1.7px),
    radial-gradient(circle at 17% 51%,rgba(255,183,3,.40) 0 .72px,transparent 1.45px),
    radial-gradient(circle at 29% 47%,rgba(0,89,96,.62) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 39% 55%,rgba(2,8,23,.82) 0 1.12px,transparent 1.9px),
    radial-gradient(circle at 54% 46%,rgba(255,183,3,.44) 0 .75px,transparent 1.45px),
    radial-gradient(circle at 63% 57%,rgba(0,89,96,.66) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 76% 49%,rgba(2,8,23,.84) 0 1.2px,transparent 1.95px),
    radial-gradient(circle at 89% 55%,rgba(0,89,96,.66) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 12% 66%,rgba(2,8,23,.80) 0 1px,transparent 1.75px),
    radial-gradient(circle at 24% 75%,rgba(0,89,96,.64) 0 .85px,transparent 1.55px),
    radial-gradient(circle at 36% 68%,rgba(255,183,3,.44) 0 .7px,transparent 1.45px),
    radial-gradient(circle at 49% 78%,rgba(2,8,23,.82) 0 1.05px,transparent 1.85px),
    radial-gradient(circle at 61% 69%,rgba(0,89,96,.64) 0 .85px,transparent 1.55px),
    radial-gradient(circle at 73% 80%,rgba(2,8,23,.82) 0 1.15px,transparent 1.9px),
    radial-gradient(circle at 86% 70%,rgba(255,183,3,.42) 0 .72px,transparent 1.45px),
    radial-gradient(circle at 94% 84%,rgba(2,8,23,.86) 0 1.05px,transparent 1.8px),
    radial-gradient(circle at 9% 91%,rgba(255,183,3,.40) 0 .72px,transparent 1.45px),
    radial-gradient(circle at 21% 88%,rgba(2,8,23,.82) 0 1.05px,transparent 1.85px),
    radial-gradient(circle at 34% 95%,rgba(0,89,96,.62) 0 .85px,transparent 1.55px),
    radial-gradient(circle at 53% 91%,rgba(2,8,23,.82) 0 1px,transparent 1.8px),
    radial-gradient(circle at 69% 94%,rgba(255,183,3,.42) 0 .72px,transparent 1.45px),
    radial-gradient(circle at 84% 91%,rgba(0,89,96,.62) 0 .85px,transparent 1.55px),
    rgba(255,255,255,.945)!important;
}
.main-content{flex:0 1 auto!important;min-height:0!important;overflow-y:auto!important;gap:7px!important;padding-right:2px!important}
.country-detect{margin-top:6px!important}
.switch-btn{display:flex!important;align-items:center!important;justify-content:center!important;gap:6px!important}
@media(max-width:480px){
  body{align-items:center!important;padding:4px!important}
  .container{width:min(94vw,320px)!important;height:auto!important;max-height:calc(100svh - 8px)!important;padding:8px!important}
  .logo-section{padding:5px 0 5px!important}
  .slogan{margin-top:5px!important;font-size:.74rem!important}
  .main-content{gap:6px!important}
  .panel{padding:8px!important}
  .country-detect{padding:7px!important;margin-top:5px!important}
}

</style></head><body><div class='container'><div class='header'><div class='title'>Bienvenue sur Teth</div><div class='subtitle'>« Chaque jour est une vie »</div></div><div class='body'><p>Bonjour,</p><p>Vous venez de créer un compte sur <strong style='color:#008080;'>Teth</strong>.<br>Pour terminer l'inscription, choisissez votre <span class='highlight'>surnom de jeu</span> et votre <span class='highlight'>mot de passe sécurisé</span>.</p><div class='btn-wrap'><a href='{$activation_url}' class='btn'>Configurer mon compte</a></div><p class='info'>Ce lien est valable pendant 24 heures et ne peut être utilisé qu'une seule fois.</p><p style='font-size:11px;color:#9ca3af;margin:12px 0 0;'>Si vous n'êtes pas à l'origine de cette inscription, vous pouvez ignorer cet email.</p></div><div class='footer'>© " . date('Y') . " Teth · Ne répondez pas à cet email (envoi automatique)</div></div></body></html>";

                            try {
                                $mail = new PHPMailer(true);
                                $mail->isSMTP();
                                $mail->Host       = $_ENV['SMTP_HOST'] ?? '';
                                $mail->SMTPAuth   = true;
                                $mail->Username   = $_ENV['SMTP_USER'] ?? '';
                                $mail->Password   = $_ENV['SMTP_PASS'] ?? '';
                                $mail->SMTPSecure = $_ENV['SMTP_ENCRYPTION'] ?? 'tls';
                                $mail->Port       = (int)($_ENV['SMTP_PORT'] ?? 587);
                                $mail->CharSet    = 'UTF-8';
                                $mail->Timeout    = 10;
                                $mail->setFrom($_ENV['SMTP_FROM_EMAIL'] ?? 'serviceclient@parisintellectuel.com', $_ENV['SMTP_FROM_NAME'] ?? 'Teth');
                                $mail->addAddress($email);
                                $mail->Subject = "🎉 Activez votre compte Teth !";
                                $mail->isHTML(true);
                                $mail->Body = $body;
                                $mail->send();
                                $message = "Email d'activation envoyé à $email";
                            } catch (Exception $e) {
                                error_log("ERREUR EMAIL REGISTER: " . $e->getMessage());
                                $message = "Compte créé. Vérifiez vos spams ou contactez le support.";
                            }
                        } else {
                            $message = "Erreur lors de la création du compte";
                        }
                        $stmt->close();
                    }
                }
            }
        }
    }

    // ----------------------------
    // FORGOT
    // ----------------------------
    if ($action === 'forgot') {
        $forgot_key = "forgot:" . $user_ip;

        if ($rateLimiterAvailable && $rateLimiter && !$rateLimiter->check($forgot_key, 5, 3600)) {
            http_response_code(429);
            $message = "Trop de demandes. Réessayez dans 1 heure.";
        } else {
            $email = trim((string)($_POST['email'] ?? ''));
            if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $message = "Email invalide";
            } else {
                $db = get_db();
                $stmt = $db->prepare("SELECT id, motdepasse FROM utilisateurs WHERE email = ? AND actif = 1 LIMIT 1");
                $stmt->bind_param('s', $email);
                $stmt->execute();
                $user = $stmt->get_result()->fetch_assoc();
                $stmt->close();

                $message = "Si cet email existe, un lien de réinitialisation a été envoyé";

                if ($user && !empty($user['motdepasse'])) {
                    $token = bin2hex(random_bytes(32));
                    $expiration = time() + 3600;

                    $stmt2 = $db->prepare("UPDATE utilisateurs SET token_reset = ?, token_expiration = ? WHERE id = ?");
                    $uid = (int)$user['id'];
                    $stmt2->bind_param('sii', $token, $expiration, $uid);
                    $stmt2->execute();
                    $stmt2->close();

                    $app_url = $_ENV['APP_URL'] ?? 'https://php.parisintellectuel.com';
                    $reset_url = $app_url . "/reset_password.php?token=" . urlencode($token);

                    $body = "<div style='font-family:Arial,sans-serif;max-width:400px;margin:0 auto;padding:20px;background:#f0fafa;border-radius:10px;'><h2 style='color:#008080;margin:0 0 15px;'>🔐 Réinitialisation</h2><p style='margin:0 0 20px;'>Cliquez sur le bouton ci-dessous pour réinitialiser votre mot de passe :</p><a href='{$reset_url}' style='display:inline-block;background:#008080;color:#fff;padding:12px 24px;text-decoration:none;border-radius:8px;font-weight:bold;'>Réinitialiser mon mot de passe</a><p style='margin-top:15px;font-size:12px;color:#666;'>Lien valide 1h</p></div>";

                    try {
                        $mail = new PHPMailer(true);
                        $mail->isSMTP();
                        $mail->Host       = $_ENV['SMTP_HOST'] ?? '';
                        $mail->SMTPAuth   = true;
                        $mail->Username   = $_ENV['SMTP_USER'] ?? '';
                        $mail->Password   = $_ENV['SMTP_PASS'] ?? '';
                        $mail->SMTPSecure = $_ENV['SMTP_ENCRYPTION'] ?? 'tls';
                        $mail->Port       = (int)($_ENV['SMTP_PORT'] ?? 587);
                        $mail->CharSet    = 'UTF-8';
                        $mail->Timeout    = 10;
                        $mail->setFrom($_ENV['SMTP_FROM_EMAIL'] ?? 'serviceclient@parisintellectuel.com', $_ENV['SMTP_FROM_NAME'] ?? 'Teth');
                        $mail->addAddress($email);
                        $mail->Subject = "🔐 Réinitialisation mot de passe - Teth";
                        $mail->isHTML(true);
                        $mail->Body = $body;
                        $mail->send();
                    } catch (Exception $e) {
                        error_log("ERREUR EMAIL FORGOT: " . $e->getMessage());
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no,viewport-fit=cover">
<meta http-equiv="Cache-Control" content="no-store">
<title>Connexion – Teth</title>
<link rel="icon" href="<?= ($_ENV['APP_URL'] ?? 'https://php.parisintellectuel.com') ?>/assets/images/logo-teth.webp">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<style>
*{margin:0;padding:0;box-sizing:border-box}
html,body{width:100%;height:100dvh;overflow:hidden;background:#d8f4f4;font-family:'Segoe UI',system-ui,sans-serif}
body{display:flex;align-items:center;justify-content:center;padding:5px}
.container{width:100%;max-width:320px;height:96dvh;background:#fff;border-radius:15px;box-shadow:0 10px 30px rgba(0,0,0,.2);display:flex;flex-direction:column;padding:10px;overflow:hidden;position:relative}
.logo-section{flex-shrink:0;text-align:center;padding:10px 0}
.logo-fire-ring{position:relative;width:85px;height:85px;margin:0 auto;border-radius:50%;display:flex;align-items:center;justify-content:center;background:conic-gradient(from 0deg,#ff6b00,#ffd700,#ff4500,#ff6b00);animation:rotateRing 3s linear infinite}
@keyframes rotateRing{100%{transform:rotate(360deg)}}
.logo-wrapper{width:78px;height:78px;background:#fff;border-radius:50%;overflow:hidden;z-index:2;animation:counterRotate 3s linear infinite}
@keyframes counterRotate{100%{transform:rotate(-360deg)}}
.logo{width:100%;height:100%;object-fit:cover;transform:scale(1.3)}
.slogan{font-size:.8rem;color:#007070;font-style:italic;font-weight:bold;margin-top:8px;display:inline-block;position:relative}
.slogan::after{content:"";display:block;width:70%;height:2px;background:#00bfa6;margin:3px auto 0;border-radius:2px}
.main-content{flex:1 1 0;min-height:0;overflow-y:auto;display:flex;flex-direction:column;gap:7px;padding-right:2px}
.main-content::-webkit-scrollbar{width:3px}.main-content::-webkit-scrollbar-thumb{background:#c0e8e8;border-radius:2px}
.hero-card{background:linear-gradient(135deg,#00bfa6,#007a7c);color:#fff;border-radius:12px;padding:10px 11px;box-shadow:0 6px 16px rgba(0,128,128,.16);flex-shrink:0}
.hero-title{font-size:.85rem;font-weight:900;letter-spacing:.3px;text-transform:uppercase}
.hero-sub{font-size:.64rem;opacity:.92;margin-top:3px;line-height:1.25}
.panel{background:#f0f8f8;border-radius:10px;padding:9px;flex-shrink:0;border:1px solid #d9eeee}
.panel.hidden{display:none}
.form-label{display:block;font-size:.62rem;color:#004d4d;margin:7px 0 4px;font-weight:900;letter-spacing:.5px;text-transform:uppercase;text-align:left}
input[type="email"],input[type="tel"],input[type="password"],input[type="text"]{width:100%;padding:9px 10px;border:2px solid #c0e8e8;border-radius:8px;background:#fff;font-size:.82rem;margin-bottom:6px;transition:.2s;color:#004d4d;font-weight:700}
input::placeholder{color:#93a8a8;font-weight:600}input:focus{outline:none;border-color:#00bfa6;box-shadow:0 0 0 3px rgba(0,191,166,.14);background:#fff}
.checkbox-row{display:flex;align-items:center;justify-content:space-between;margin:2px 0 8px;font-size:.72rem;color:#004d4d;gap:8px}.checkbox-row label{display:flex;align-items:center;cursor:pointer;font-weight:700}.checkbox-row input{margin-right:5px}.forgot-link,.text-link{color:#007070;text-decoration:none;font-weight:900;cursor:pointer}.forgot-link:hover,.text-link:hover{text-decoration:underline}
button,.btn-primary{width:100%;border:0;border-radius:10px;padding:10px;cursor:pointer;font-weight:900;font-size:.78rem;color:#fff;background:linear-gradient(135deg,#00bfa6,#007a7c);box-shadow:0 4px 12px rgba(0,128,128,.18);text-transform:uppercase;letter-spacing:.4px}button:active,.btn-primary:active{transform:translateY(1px)}
.divider{display:flex;align-items:center;margin:8px 0 7px;color:#7c9999;font-size:.66rem;font-weight:900;text-transform:uppercase}.divider::before,.divider::after{content:"";flex:1;height:1px;background:#cceaea}.divider span{margin:0 8px}.switch-btn{display:block;width:100%;border:0;border-radius:8px;padding:8px;background:linear-gradient(135deg,#e8f5f5,#c8f1ed);color:#004d4d;text-decoration:none;font-size:.75rem;font-weight:900;text-align:center;cursor:pointer}
.phone-wrapper{display:flex;align-items:center;border:2px solid #c0e8e8;border-radius:8px;overflow:hidden;background:#fff;margin-bottom:6px}.phone-prefix{background:#e8f5f5;padding:9px 10px;color:#004d4d;font-weight:900;border-right:1px solid #c0e8e8;font-size:.8rem}.phone-wrapper input{border:0!important;margin:0!important;box-shadow:none!important;background:#fff!important;flex:1}
.forgot-card{background:#fff;border:1px solid #d9eeee;border-radius:10px;padding:9px;margin-bottom:8px}.forgot-title{font-size:.82rem;color:#004d4d;font-weight:900}.forgot-copy{font-size:.68rem;color:#007070;font-weight:700;line-height:1.35;margin-top:4px}.captcha-wrapper{margin:6px 0;display:flex;justify-content:center;transform:scale(.78);transform-origin:center}.country-detect{background:#f0f8f8;border-radius:10px;padding:8px;font-size:.66rem;color:#004d4d;text-align:center;font-weight:800;flex-shrink:0}
.inline-msg{display:none}.modal-backdrop{position:fixed;inset:0;background:rgba(0,35,35,.42);z-index:9999;display:none;align-items:center;justify-content:center;padding:18px;backdrop-filter:blur(3px)}.modal-backdrop.show{display:flex}.teth-modal{width:100%;max-width:310px;background:#fff;border-radius:18px;box-shadow:0 18px 45px rgba(0,0,0,.28);overflow:hidden;animation:popIn .24s ease}.teth-modal.error{border:2px solid #ff7043}.teth-modal.success{border:2px solid #00bfa6}.modal-head{padding:14px 14px 10px;text-align:center;background:linear-gradient(135deg,#fff8f2,#fff)}.modal-icon{width:50px;height:50px;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 7px;font-size:1.55rem;background:#fff3e8}.teth-modal.success .modal-icon{background:#e8fff9}.modal-title{font-weight:1000;color:#004d4d;font-size:.98rem}.modal-body{padding:0 15px 14px;text-align:center;color:#006060;font-size:.78rem;font-weight:700;line-height:1.38}.modal-actions{display:flex;gap:8px;padding:0 14px 14px}.modal-close{width:100%;border-radius:10px;padding:9px;background:linear-gradient(135deg,#00bfa6,#007a7c);color:white;border:0;font-weight:900}.modal-secondary{background:linear-gradient(135deg,#fff3e8,#ffe4c8);color:#9a3412}
@keyframes popIn{from{opacity:0;transform:translateY(12px) scale(.96)}to{opacity:1;transform:translateY(0) scale(1)}}

/* =========================================================
   TETH COSMETIQUE PILOTE — CIEL VIVANT + CARTE BLANCHE TROUEE
   Objectif : conserver le gabarit mobile actuel, sans fatigue visuelle.
========================================================= */
:root{--teth-night-1:#020817;--teth-night-2:#061b36;--teth-night-3:#073f46;--teth-cyan:#00bfa6;--teth-deep:#004d4d;--teth-gold:#ffb703}
#tethSky{position:fixed;inset:0;width:100vw;height:100svh;z-index:0;display:block;background:radial-gradient(circle at 17% 24%,rgba(0,191,166,.16),transparent 25%),radial-gradient(circle at 82% 62%,rgba(37,99,235,.18),transparent 30%),linear-gradient(135deg,var(--teth-night-3) 0%,var(--teth-night-2) 42%,var(--teth-night-1) 100%)}
html,body{min-height:100svh;height:100svh;background:#020817!important;overflow:hidden!important}
body{position:relative;padding:5px!important;isolation:isolate}
.container{z-index:2;max-width:320px!important;height:96svh!important;background:radial-gradient(circle at 9% 7%,rgba(2,8,23,.92) 0 1.2px,transparent 1.9px),radial-gradient(circle at 22% 18%,rgba(0,89,96,.72) 0 1px,transparent 1.7px),radial-gradient(circle at 39% 10%,rgba(2,8,23,.85) 0 1.35px,transparent 2.05px),radial-gradient(circle at 62% 16%,rgba(0,89,96,.62) 0 1px,transparent 1.9px),radial-gradient(circle at 82% 9%,rgba(2,8,23,.9) 0 1.25px,transparent 2px),radial-gradient(circle at 93% 26%,rgba(0,89,96,.7) 0 1px,transparent 1.8px),radial-gradient(circle at 13% 39%,rgba(2,8,23,.86) 0 1.1px,transparent 1.9px),radial-gradient(circle at 32% 46%,rgba(255,183,3,.55) 0 .9px,transparent 1.7px),radial-gradient(circle at 74% 42%,rgba(2,8,23,.78) 0 1.45px,transparent 2.2px),radial-gradient(circle at 87% 55%,rgba(0,89,96,.65) 0 1.05px,transparent 1.85px),radial-gradient(circle at 18% 63%,rgba(2,8,23,.72) 0 1.25px,transparent 2px),radial-gradient(circle at 48% 70%,rgba(0,89,96,.68) 0 1px,transparent 1.7px),radial-gradient(circle at 78% 76%,rgba(2,8,23,.88) 0 1.15px,transparent 2px),radial-gradient(circle at 11% 88%,rgba(255,183,3,.45) 0 .9px,transparent 1.8px),radial-gradient(circle at 55% 91%,rgba(2,8,23,.72) 0 1.05px,transparent 1.85px),rgba(255,255,255,.94)!important;border:1px solid rgba(255,255,255,.9);box-shadow:0 18px 48px rgba(0,0,0,.42),0 0 0 1px rgba(0,191,166,.18),0 0 34px rgba(0,191,166,.16);backdrop-filter:blur(5px);-webkit-backdrop-filter:blur(5px)}
.container::before{content:"";position:absolute;inset:0;border-radius:15px;pointer-events:none;background:linear-gradient(135deg,rgba(255,255,255,.48),rgba(255,255,255,.10) 48%,rgba(0,191,166,.07));z-index:0}.container>*{position:relative;z-index:1}
.logo-section{padding:9px 0 6px!important}.logo-fire-ring{width:72px!important;height:72px!important;box-shadow:0 0 18px rgba(255,183,3,.35)}.logo-wrapper{width:65px!important;height:65px!important}.slogan{color:#007070!important;text-shadow:0 1px 0 rgba(255,255,255,.8)}
.main-content{gap:7px!important}.hero-card.coin-hero{height:47px!important;min-height:47px!important;padding:6px 9px!important;display:flex;align-items:center;justify-content:center;overflow:hidden;background:linear-gradient(135deg,rgba(0,191,166,.95),rgba(0,116,124,.98))!important;border:1px solid rgba(255,255,255,.45);box-shadow:0 8px 18px rgba(0,128,128,.22),inset 0 1px 0 rgba(255,255,255,.35)}
.coin-row{height:34px;width:100%;display:flex;align-items:center;justify-content:center;gap:13px;filter:drop-shadow(0 0 8px rgba(255,183,3,.35))}.coin{width:24px;height:24px;border-radius:50%;display:inline-block;position:relative;background:radial-gradient(circle at 35% 28%,#fff8cc 0 9%,#ffd166 18%,#ff9f1c 52%,#b45309 100%);border:2px solid rgba(255,242,180,.95);box-shadow:inset -4px -3px 7px rgba(92,43,0,.35),inset 3px 2px 5px rgba(255,255,255,.62),0 0 9px rgba(255,183,3,.55);animation:coinBreathe 2.8s ease-in-out infinite}.coin::before{content:"";position:absolute;inset:5px;border-radius:50%;border:1.5px solid rgba(255,255,255,.65);box-shadow:inset 0 0 4px rgba(0,75,105,.22)}.coin::after{content:"";position:absolute;left:6px;top:4px;width:5px;height:9px;border-radius:50%;background:rgba(255,255,255,.70);transform:rotate(28deg)}.coin-b{animation-delay:.35s}.coin-c{animation-delay:.7s}.coin-d{animation-delay:1.05s}.coin-e{animation-delay:1.4s}
@keyframes coinBreathe{0%,100%{opacity:.72;transform:translateY(1px) rotateY(0deg) scale(.92)}45%{opacity:1;transform:translateY(-2px) rotateY(180deg) scale(1.08)}70%{opacity:.88;transform:translateY(0) rotateY(260deg) scale(.98)}}
.panel,.country-detect,.forgot-card{background:rgba(240,248,248,.78)!important;border:1px solid rgba(0,128,128,.18)!important;box-shadow:inset 0 1px 0 rgba(255,255,255,.45)}
input[type="email"],input[type="tel"],input[type="password"],input[type="text"]{background:rgba(255,255,255,.72)!important;border-color:rgba(0,128,128,.25)!important;color:#004d4d!important}.switch-btn{background:linear-gradient(135deg,rgba(232,245,245,.82),rgba(200,241,237,.88))!important}.country-detect{margin-top:6px!important}
@media(max-width:480px){body{padding:4px!important}.container{width:min(94vw,320px)!important;height:calc(100svh - 8px)!important}.coin-row{gap:10px}.coin{width:22px;height:22px}.hero-card.coin-hero{height:44px!important;min-height:44px!important}.logo-fire-ring{width:68px!important;height:68px!important}.logo-wrapper{width:61px!important;height:61px!important}}
@media(prefers-reduced-motion:reduce){.coin{animation:none!important}#tethSky{display:none}}


/* =========================================================
   AJUSTEMENT FINAL VALIDATION — MOBILE SANS VIDE + PLUS DE TROUS
========================================================= */
.container{
  height:auto!important;
  min-height:0!important;
  max-height:calc(100svh - 8px)!important;
  padding:10px!important;
  background:
    radial-gradient(circle at 6% 6%,rgba(2,8,23,.88) 0 .95px,transparent 1.65px),
    radial-gradient(circle at 14% 12%,rgba(255,183,3,.48) 0 .75px,transparent 1.45px),
    radial-gradient(circle at 25% 7%,rgba(2,8,23,.78) 0 1.15px,transparent 1.85px),
    radial-gradient(circle at 35% 15%,rgba(0,89,96,.66) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 48% 8%,rgba(2,8,23,.86) 0 1px,transparent 1.75px),
    radial-gradient(circle at 59% 15%,rgba(255,183,3,.42) 0 .75px,transparent 1.45px),
    radial-gradient(circle at 72% 7%,rgba(2,8,23,.86) 0 1.1px,transparent 1.85px),
    radial-gradient(circle at 86% 13%,rgba(0,89,96,.68) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 95% 7%,rgba(2,8,23,.84) 0 1px,transparent 1.8px),
    radial-gradient(circle at 9% 24%,rgba(0,89,96,.66) 0 .9px,transparent 1.55px),
    radial-gradient(circle at 20% 29%,rgba(2,8,23,.86) 0 1.25px,transparent 2px),
    radial-gradient(circle at 31% 23%,rgba(255,183,3,.42) 0 .75px,transparent 1.5px),
    radial-gradient(circle at 44% 31%,rgba(2,8,23,.76) 0 1px,transparent 1.7px),
    radial-gradient(circle at 57% 25%,rgba(0,89,96,.66) 0 .85px,transparent 1.55px),
    radial-gradient(circle at 68% 33%,rgba(2,8,23,.84) 0 1.15px,transparent 1.9px),
    radial-gradient(circle at 82% 25%,rgba(255,183,3,.48) 0 .75px,transparent 1.45px),
    radial-gradient(circle at 93% 36%,rgba(2,8,23,.86) 0 1.05px,transparent 1.8px),
    radial-gradient(circle at 7% 43%,rgba(2,8,23,.80) 0 1px,transparent 1.7px),
    radial-gradient(circle at 17% 51%,rgba(255,183,3,.40) 0 .72px,transparent 1.45px),
    radial-gradient(circle at 29% 47%,rgba(0,89,96,.62) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 39% 55%,rgba(2,8,23,.82) 0 1.12px,transparent 1.9px),
    radial-gradient(circle at 54% 46%,rgba(255,183,3,.44) 0 .75px,transparent 1.45px),
    radial-gradient(circle at 63% 57%,rgba(0,89,96,.66) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 76% 49%,rgba(2,8,23,.84) 0 1.2px,transparent 1.95px),
    radial-gradient(circle at 89% 55%,rgba(0,89,96,.66) 0 .9px,transparent 1.6px),
    radial-gradient(circle at 12% 66%,rgba(2,8,23,.80) 0 1px,transparent 1.75px),
    radial-gradient(circle at 24% 75%,rgba(0,89,96,.64) 0 .85px,transparent 1.55px),
    radial-gradient(circle at 36% 68%,rgba(255,183,3,.44) 0 .7px,transparent 1.45px),
    radial-gradient(circle at 49% 78%,rgba(2,8,23,.82) 0 1.05px,transparent 1.85px),
    radial-gradient(circle at 61% 69%,rgba(0,89,96,.64) 0 .85px,transparent 1.55px),
    radial-gradient(circle at 73% 80%,rgba(2,8,23,.82) 0 1.15px,transparent 1.9px),
    radial-gradient(circle at 86% 70%,rgba(255,183,3,.42) 0 .72px,transparent 1.45px),
    radial-gradient(circle at 94% 84%,rgba(2,8,23,.86) 0 1.05px,transparent 1.8px),
    radial-gradient(circle at 9% 91%,rgba(255,183,3,.40) 0 .72px,transparent 1.45px),
    radial-gradient(circle at 21% 88%,rgba(2,8,23,.82) 0 1.05px,transparent 1.85px),
    radial-gradient(circle at 34% 95%,rgba(0,89,96,.62) 0 .85px,transparent 1.55px),
    radial-gradient(circle at 53% 91%,rgba(2,8,23,.82) 0 1px,transparent 1.8px),
    radial-gradient(circle at 69% 94%,rgba(255,183,3,.42) 0 .72px,transparent 1.45px),
    radial-gradient(circle at 84% 91%,rgba(0,89,96,.62) 0 .85px,transparent 1.55px),
    rgba(255,255,255,.945)!important;
}
.main-content{flex:0 1 auto!important;min-height:0!important;overflow-y:auto!important;gap:7px!important;padding-right:2px!important}
.country-detect{margin-top:6px!important}
.switch-btn{display:flex!important;align-items:center!important;justify-content:center!important;gap:6px!important}
@media(max-width:480px){
  body{align-items:center!important;padding:4px!important}
  .container{width:min(94vw,320px)!important;height:auto!important;max-height:calc(100svh - 8px)!important;padding:8px!important}
  .logo-section{padding:5px 0 5px!important}
  .slogan{margin-top:5px!important;font-size:.74rem!important}
  .main-content{gap:6px!important}
  .panel{padding:8px!important}
  .country-detect{padding:7px!important;margin-top:5px!important}
}



/* =========================================================
   TETH DESIGN SYSTEM CENTRAL — WRAPPER + CIEL VIVANT
   Source visuelle unique, sans toucher à la logique métier.
========================================================= */
:root{
  --teth-bg-deep:#050713;
  --teth-bg-mid:#101b33;
  --teth-primary:#00bfa6;
  --teth-primary-dark:#007a7c;
  --teth-gold:#ffb703;
  --teth-card:rgba(255,255,255,.955);
}
html{min-height:100%;height:100%;background:var(--teth-bg-deep)!important}
html,body{width:100%;min-height:100svh;height:100svh;overflow:hidden!important}
body{
  display:block!important;
  padding:0!important;
  margin:0!important;
  background:
    radial-gradient(ellipse at 50% 115%,rgba(0,191,166,.22) 0%,rgba(9,10,15,0) 48%),
    radial-gradient(ellipse at top,#1b2735 0%,#090a0f 100%)!important;
}
#tethSky{
  position:fixed;
  inset:0;
  width:100vw;
  height:100vh;
  z-index:0;
  pointer-events:none;
}
.teth-wrapper{
  position:relative;
  z-index:1;
  width:100%;
  min-height:100svh;
  display:flex;
  align-items:center;
  justify-content:center;
  padding:clamp(4px,1.2svh,12px);
  overflow:hidden;
}
.container{
  height:auto!important;
  max-height:calc(100svh - 12px)!important;
  min-height:0!important;
  background:var(--teth-card)!important;
  backdrop-filter:blur(10px);
  -webkit-backdrop-filter:blur(10px);
  border:1px solid rgba(255,255,255,.72);
}
.main-content{
  flex:0 1 auto!important;
  min-height:0!important;
  overflow-y:auto!important;
  overscroll-behavior:contain;
}
@supports(height:100dvh){
  html,body{height:100dvh}
  .teth-wrapper{min-height:100dvh}
  .container{max-height:calc(100dvh - 12px)!important}
}
@media(max-width:480px){
  .teth-wrapper{padding:4px!important}
  .container{width:min(94vw,320px)!important;max-height:calc(100svh - 8px)!important}
  @supports(height:100dvh){.container{max-height:calc(100dvh - 8px)!important}}
}
@media(prefers-reduced-motion:reduce){
  .logo-fire-ring,.logo-wrapper,.coin{animation:none!important}
}
</style>
</head>
<body>
<canvas id="tethSky" aria-hidden="true"></canvas>
<?php
$isError = $message !== '' && (strpos($message,'erreur')!==false || strpos($message,'invalide')!==false || strpos($message,'incorrect')!==false || strpos($message,'utilisé')!==false || strpos($message,'Trop')!==false || strpos($message,'verrouillé')!==false || strpos($message,'requis')!==false || strpos($message,'captcha')!==false);
$modalTitle = 'Information Teth';
$modalIcon = '✨';
if ($message !== '') {
    if (strpos($message, 'incorrect') !== false) { $modalTitle = 'Accès refusé'; $modalIcon = '🛡️'; }
    elseif (strpos($message, 'verrouillé') !== false || strpos($message, 'Trop') !== false) { $modalTitle = 'Sécurité renforcée'; $modalIcon = '⏳'; }
    elseif (strpos($message, 'réinitialisation') !== false || strpos($message, 'lien') !== false) { $modalTitle = 'Lien de secours envoyé'; $modalIcon = '📩'; }
    elseif (!$isError) { $modalTitle = 'Opération réussie'; $modalIcon = '✅'; }
}
?>
<div class="teth-wrapper">
<div class="container">
  <div class="logo-section">
    <div class="logo-fire-ring"><div class="logo-wrapper"><img src="<?= ($_ENV['APP_URL'] ?? 'https://php.parisintellectuel.com') ?>/assets/images/logo-teth.webp" class="logo" alt="Logo Teth" loading="eager"></div></div>
    <div class="slogan">« Chaque jour est une vie »</div>
  </div>
  <div class="main-content">
    <div class="hero-card coin-hero" aria-label="Pièces Teth animées">
      <div class="coin-row">
        <span class="coin coin-a"></span>
        <span class="coin coin-b"></span>
        <span class="coin coin-c"></span>
        <span class="coin coin-d"></span>
        <span class="coin coin-e"></span>
      </div>
    </div>
    <?php if($show_success): ?><div class="inline-msg" id="messageBox">✅ Compte activé ! Connectez-vous.</div><?php endif; ?>
    <?php if($message): ?><div class="inline-msg" id="messageBox"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>

    <div id="login" class="panel">
      <form method="POST" id="loginForm" autocomplete="on">
        <input type="hidden" name="action" value="login">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
        <label class="form-label">✉️ Email</label>
        <input type="email" name="email" placeholder="ton@email.com" required autocomplete="email">
        <label class="form-label">🔐 Mot de passe</label>
        <input type="password" name="password" id="loginPassword" placeholder="••••••••" required autocomplete="current-password">
        <div class="checkbox-row"><label><input type="checkbox" onclick="const i=document.getElementById('loginPassword');i.type=i.type==='password'?'text':'password'">Afficher</label><a class="forgot-link" onclick="showPanel('forgot')">Mot de passe oublié ?</a></div>
        <?php if($show_captcha): ?><div class="captcha-wrapper"><div class="g-recaptcha" data-sitekey="<?= htmlspecialchars(RECAPTCHA_SITE_KEY, ENT_QUOTES, 'UTF-8') ?>"></div></div><?php endif; ?>
        <button type="submit">▶️ Connexion</button>
      </form>
      <div class="divider"><span>Nouveau joueur</span></div><a class="switch-btn" onclick="showPanel('register')">📝 Créer mon compte</a>
    </div>

    <div id="register" class="panel hidden">
      <form method="POST" autocomplete="on">
        <input type="hidden" name="action" value="register">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
        <label class="form-label">✉️ Email</label><input type="email" name="email" placeholder="ton@email.com" required autocomplete="email">
        <label class="form-label">📱 Téléphone</label><div class="phone-wrapper"><span class="phone-prefix">+243</span><input type="tel" name="telephone" maxlength="15" placeholder="812345678" required oninput="this.value=this.value.replace(/[^0-9]/g,'')" autocomplete="tel"></div>
        <button type="submit">📝 S'inscrire</button>
      </form>
      <div class="divider"><span>Déjà inscrit</span></div><a class="switch-btn" onclick="showPanel('login')">🔓 Retour connexion</a>
    </div>

    <div id="forgot" class="panel hidden">
      <div class="forgot-card"><div class="forgot-title">🛟 Assistance mot de passe</div><div class="forgot-copy">Entrez l’email du compte. Si le compte existe, Teth envoie un lien privé valable 1 heure. Aucun mot de passe n’est affiché ni communiqué.</div></div>
      <form method="POST" autocomplete="on">
        <input type="hidden" name="action" value="forgot">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
        <label class="form-label">✉️ Email du compte</label><input type="email" name="email" placeholder="ton@email.com" required autocomplete="email">
        <button type="submit">📩 Recevoir le lien sécurisé</button>
      </form>
      <div class="divider"><span>Retour</span></div><a class="switch-btn" onclick="showPanel('login')">🔓 Connexion</a>
    </div>
  </div>
  <div class="country-detect">📍 Depuis : <strong><?= htmlspecialchars($displayed_country, ENT_QUOTES, 'UTF-8') ?></strong></div>
</div>
</div>

<div class="modal-backdrop" id="tethModal">
  <div class="teth-modal <?= $isError ? 'error' : 'success' ?>">
    <div class="modal-head"><div class="modal-icon"><?= $modalIcon ?></div><div class="modal-title"><?= htmlspecialchars($modalTitle, ENT_QUOTES, 'UTF-8') ?></div></div>
    <div class="modal-body" id="modalText"><?= htmlspecialchars($message ?: ($show_success ? 'Compte activé ! Connectez-vous.' : ''), ENT_QUOTES, 'UTF-8') ?></div>
    <div class="modal-actions">
      <?php if($message && strpos($message,'incorrect')!==false): ?><button type="button" class="modal-close modal-secondary" onclick="showPanel('forgot');closeModal();">Réinitialiser</button><?php endif; ?>
      <button type="button" class="modal-close" onclick="closeModal();">Compris</button>
    </div>
  </div>
</div>
<script>
'use strict';
function showPanel(id){document.querySelectorAll('.panel').forEach(p=>p.classList.add('hidden'));const p=document.getElementById(id);if(p)p.classList.remove('hidden');}
function closeModal(){const m=document.getElementById('tethModal');if(m)m.classList.remove('show');}
showPanel(<?= json_encode($action === 'register' ? 'register' : ($action === 'forgot' ? 'forgot' : 'login')) ?>);
(function(){const hasMsg=<?= ($message !== '' || $show_success) ? 'true' : 'false' ?>; if(hasMsg){setTimeout(()=>{const m=document.getElementById('tethModal');if(m)m.classList.add('show');},120);}})();
window.addEventListener('pageshow', e=>{if(e.persisted) location.reload();});
document.addEventListener('keydown', e=>{if(e.key==='Escape') closeModal();});
document.getElementById('tethModal')?.addEventListener('click', e=>{if(e.target.id==='tethModal') closeModal();});

/* =========================================================
   Ciel vivant Teth : 80-120 étoiles, allumage non synchronisé.
========================================================= */
(function(){
  const canvas=document.getElementById('tethSky');
  if(!canvas) return;
  const reduced=window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const ctx=canvas.getContext('2d',{alpha:true});
  if(!ctx || reduced) return;
  let w=0,h=0,dpr=1,stars=[],meteors=[];
  function rnd(a,b){return a+Math.random()*(b-a);}
  function resize(){
    dpr=Math.min(window.devicePixelRatio||1,2);
    w=window.innerWidth; h=window.innerHeight;
    canvas.width=Math.floor(w*dpr); canvas.height=Math.floor(h*dpr);
    canvas.style.width=w+'px'; canvas.style.height=h+'px';
    ctx.setTransform(dpr,0,0,dpr,0,0);
    const count=Math.max(80,Math.min(120,Math.round((w*h)/9000)));
    stars=Array.from({length:count},()=>({x:Math.random()*w,y:Math.random()*h,r:rnd(.45,1.55),phase:rnd(0,Math.PI*2),speed:rnd(.0008,.0028),hue:Math.random()<.72?'255,255,255':(Math.random()<.55?'0,191,166':'255,183,3'),base:rnd(.18,.62),amp:rnd(.18,.55)}));
  }
  function maybeMeteor(){if(meteors.length<2 && Math.random()<0.006)meteors.push({x:rnd(w*.05,w*.95),y:rnd(10,h*.48),vx:rnd(-2.8,-1.4),vy:rnd(1.1,2.2),life:0,max:rnd(36,62)});}
  function draw(t){
    ctx.clearRect(0,0,w,h);
    const g=ctx.createRadialGradient(w*.52,h*.45,10,w*.52,h*.45,Math.max(w,h)*.75);
    g.addColorStop(0,'rgba(0,191,166,.045)');g.addColorStop(.5,'rgba(37,99,235,.035)');g.addColorStop(1,'rgba(0,0,0,0)');ctx.fillStyle=g;ctx.fillRect(0,0,w,h);
    for(const s of stars){const pulse=s.base+(Math.sin(t*s.speed+s.phase)*.5+.5)*s.amp;ctx.beginPath();ctx.arc(s.x,s.y,s.r*(.85+pulse*.22),0,Math.PI*2);ctx.fillStyle='rgba('+s.hue+','+Math.min(.95,pulse)+')';ctx.fill();if(pulse>.82){ctx.beginPath();ctx.arc(s.x,s.y,s.r*3.2,0,Math.PI*2);ctx.fillStyle='rgba('+s.hue+',.08)';ctx.fill();}}
    maybeMeteor();meteors=meteors.filter(m=>m.life++<m.max);for(const m of meteors){const a=1-m.life/m.max;ctx.strokeStyle='rgba(255,255,255,'+(a*.45)+')';ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(m.x,m.y);ctx.lineTo(m.x-m.vx*12,m.y-m.vy*12);ctx.stroke();m.x+=m.vx;m.y+=m.vy;}
    requestAnimationFrame(draw);
  }
  window.addEventListener('resize',resize,{passive:true});resize();requestAnimationFrame(draw);
})();

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