<?php
session_start([
    'cookie_lifetime' => 172800,
    'gc_maxlifetime' => 172800,
]);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

$usersFile = 'users.json';
$ipBansFile = 'ip_bans.json';
$baseDir = 'data/';
$announcementsDir = $baseDir . 'announcements/';
define('LOGIN_ATTEMPT_LIMIT', 5);
define('LOGIN_ATTEMPT_WINDOW', 15 * 60);

function read_locked_json($file) {
    if (!file_exists($file) || filesize($file) === 0) return [];
    $handle = @fopen($file, 'r');
    if (!$handle) return [];
    $data = [];
    if (@flock($handle, LOCK_SH)) {
        $content = @fread($handle, filesize($file));
        @flock($handle, LOCK_UN);
        if ($content) {
            try {
                $decoded = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
                if (is_array($decoded)) $data = $decoded;
            } catch (JsonException $e) {
                 error_log('JSON Decode Error in read_locked_json (' . $file . '): ' . $e->getMessage());
                 return [];
            }
        }
    }
    @fclose($handle);
    return $data;
}

function write_locked_json($file, $data) {
    $dir = dirname($file);
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    
    try {
        $json_data = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        error_log('JSON Encode Error in write_locked_json (' . $file . '): ' . $e->getMessage());
        return false;
    }

    $temp_file = $file . '.' . bin2hex(random_bytes(6)) . '.tmp';
    if (@file_put_contents($temp_file, $json_data, LOCK_EX) === false) {
        @unlink($temp_file);
        error_log('Failed to write to temp file: ' . $temp_file);
        return false;
    }
    
    if (!@rename($temp_file, $file)) {
        @unlink($temp_file);
        error_log('Failed to rename temp file: ' . $temp_file . ' to ' . $file);
        return false;
    }
    
    @chmod($file, 0644); 
    
    return true;
}

function get_ip_address() {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $forwarded_ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip_candidate = trim($forwarded_ips[0]);
        if (filter_var($ip_candidate, FILTER_VALIDATE_IP)) {
            $ip = $ip_candidate;
        }
    }
    return $ip;
}

function check_ip_ban() {
    global $ipBansFile;
    $ip = get_ip_address();
    if (!file_exists($ipBansFile)) return;
    $bans = read_locked_json($ipBansFile);
    if (isset($bans[$ip]) && time() < $bans[$ip]['expires']) {
        http_response_code(403);
        die('شما به دلیل تخلف به طور موقت مسدود شده اید. دلیل: ' . htmlspecialchars($bans[$ip]['reason']));
    }
}

function format_persian_date($timestamp) {
    if (class_exists('IntlDateFormatter')) {
        $formatter = new IntlDateFormatter('fa_IR@calendar=persian', IntlDateFormatter::NONE, IntlDateFormatter::NONE, 'Asia/Tehran', IntlDateFormatter::TRADITIONAL);
        $formatter->setPattern('d MMMM y');
        return $formatter->format($timestamp);
    }
    return date('Y-m-d', $timestamp);
}

function add_announcement($username, $message_text) {
    global $announcementsDir;
    if (!is_dir($announcementsDir)) @mkdir($announcementsDir, 0755, true);
    $file = $announcementsDir . 'announcements_' . $username . '.json';
    $messages = read_locked_json($file);
    $timestamp = microtime(true);
    $newMessage = [
        'id' => uniqid('ann_'),
        'sender' => 'system',
        'content' => $message_text,
        'timestamp' => $timestamp,
        'time' => date('H:i', (int)$timestamp),
        'date_fa' => format_persian_date((int)$timestamp),
        'type' => 'text',
        'seen_by' => []
    ];
    $messages[] = $newMessage;
    write_locked_json($file, $messages);
}

check_ip_ban();

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
    $users = read_locked_json($usersFile);
    $current_username = $_SESSION['username'] ?? null;
    if (!$current_username || !isset($users[$current_username]) || ($users[$current_username]['status']['banned'] ?? false) === true) {
        $ban_reason = $users[$current_username]['status']['ban_reason'] ?? 'دلیل نامشخص.';
        session_unset();
        session_destroy();
        header('Location: ' . $_SERVER['PHP_SELF'] . '?action=login_page&error=' . urlencode('حساب شما مسدود شده است. دلیل: ' . $ban_reason));
        exit;
    }
    
    if (!isset($_SESSION['session_token']) || ($users[$current_username]['session_token'] ?? null) !== $_SESSION['session_token']) {
         session_unset();
         session_destroy();
         header('Location: ' . $_SERVER['PHP_SELF'] . '?action=login_page&error=' . urlencode('نشست شما نامعتبر است. لطفاً دوباره وارد شوید.'));
         exit;
    }
}

function generate_color() {
    $h = rand(0, 360);
    $s = rand(70, 90);
    $l = rand(40, 55);
    return "hsl($h, {$s}%, {$l}%)";
}

$error = $_GET['error'] ?? '';
$success = '';
$action = $_POST['action'] ?? $_GET['action'] ?? 'login_page';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']))) {
    $error = 'درخواست نامعتبر است. لطفاً صفحه را رفرش کنید.';
    $action = 'login_page';
} else {
    if ($action === 'register') {
        if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['name'])) {
            $users = read_locked_json($usersFile);
            $username = strtolower(trim($_POST['username']));
            if (isset($users[$username])) {
                $error = 'این نام کاربری قبلا ثبت شده است.';
            } elseif (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
                $error = 'نام کاربری باید بین ۳ تا ۲۰ کاراکتر و فقط شامل حروف انگلیسی، اعداد و _ باشد.';
            } elseif (strlen($_POST['password']) < 6) {
                $error = 'رمز عبور باید حداقل ۶ کاراکتر باشد.';
            } else {
                $users[$username] = [
                    'password' => password_hash($_POST['password'], PASSWORD_DEFAULT),
                    'name' => htmlspecialchars(trim($_POST['name'])),
                    'bio' => 'سلام! من یک کاربر جدید هستم.',
                    'avatar' => null,
                    'color' => generate_color(),
                    'last_active' => 0,
                    'last_ip' => null,
                    'is_typing' => 0,
                    'session_token' => null,
                    'status' => ['banned' => false, 'ban_reason' => null],
                    'profile_status' => null,
                    'settings' => ['theme' => 'dark', 'primary_color' => '#00DC82'],
                    'privacy' => ['last_seen' => 'everyone'],
                    '2fa_enabled' => false,
                    '2fa_codes' => []
                ];
                write_locked_json($usersFile, $users);
                add_announcement($username, 'به ایرنا  خوش آمدید! حساب کاربری شما با موفقیت ایجاد شد.');
                $success = 'ثبت‌نام با موفقیت انجام شد. اکنون می‌توانید وارد شوید.';
                $action = 'login_page';
            }
        } else {
            $error = 'لطفا تمام فیلدها را پر کنید.';
        }
    }

    if ($action === 'login') {
        if (isset($_SESSION['login_attempts']) && $_SESSION['login_attempts']['time'] > time() - LOGIN_ATTEMPT_WINDOW && $_SESSION['login_attempts']['count'] >= LOGIN_ATTEMPT_LIMIT) {
            $error = 'تعداد تلاش‌های ناموفق بیش از حد مجاز بوده است. لطفاً ۱۵ دقیقه دیگر امتحان کنید.';
        } elseif (!empty($_POST['username']) && !empty($_POST['password'])) {
            $users = read_locked_json($usersFile);
            $username = strtolower(trim($_POST['username']));
            if (isset($users[$username]) && password_verify($_POST['password'], $users[$username]['password'])) {
                if ($users[$username]['status']['banned'] ?? false) {
                     $error = 'حساب شما مسدود شده است. دلیل: ' . htmlspecialchars($users[$username]['status']['ban_reason'] ?? 'نامشخص');
                } else {
                    unset($_SESSION['login_attempts']);
                    
                    if ($users[$username]['2fa_enabled'] ?? false) {
                        $_SESSION['2fa_user'] = $username;
                        header('Location: ' . $_SERVER['PHP_SELF'] . '?action=2fa_page');
                        exit;
                    }
                    
                    session_regenerate_id(true);
                    $session_token = bin2hex(random_bytes(32));
                    $_SESSION['loggedin'] = true;
                    $_SESSION['username'] = $username;
                    $_SESSION['session_token'] = $session_token;
                    
                    $user_info = $users[$username];
                    $_SESSION['user_info'] = [
                        'name' => $user_info['name'],
                        'bio' => $user_info['bio'] ?? '',
                        'avatar' => $user_info['avatar'] ?? null,
                        'color' => $user_info['color'],
                        'username' => $username,
                        'settings' => $user_info['settings'] ?? ['theme' => 'dark', 'primary_color' => '#00DC82']
                    ];
                    
                    $ip = get_ip_address();
                    add_announcement($username, "ورود موفق با IP: $ip");
                    
                    $users[$username]['last_ip'] = $ip;
                    $users[$username]['session_token'] = $session_token;
                    write_locked_json($usersFile, $users);

                    header('Location: ' . $_SERVER['PHP_SELF']);
                    exit;
                }
            } else {
                if (!isset($_SESSION['login_attempts']) || $_SESSION['login_attempts']['time'] < time() - LOGIN_ATTEMPT_WINDOW) {
                    $_SESSION['login_attempts'] = ['count' => 1, 'time' => time()];
                } else {
                    $_SESSION['login_attempts']['count']++;
                }
                $error = 'نام کاربری یا رمز عبور اشتباه است.';
            }
        } else {
            $error = 'لطفا نام کاربری و رمز عبور را وارد کنید.';
        }
    }
    
    if ($action === 'verify_2fa') {
        if (!isset($_SESSION['2fa_user'])) {
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        }
        
        $username = $_SESSION['2fa_user'];
        $code = trim($_POST['2fa_code'] ?? '');
        $code = str_replace('-', '', $code);
        
        if (empty($code)) {
            $error = 'لطفا کد پشتیبان را وارد کنید.';
            $action = '2fa_page';
        } else {
            $users = read_locked_json($usersFile);
            if (!isset($users[$username]) || !($users[$username]['2fa_enabled'] ?? false)) {
                unset($_SESSION['2fa_user']);
                header('Location: ' . $_SERVER['PHP_SELF']);
                exit;
            }
            
            $hashed_code_to_check = hash('sha256', $code);
            $codes = $users[$username]['2fa_codes'] ?? [];
            $found_key = array_search($hashed_code_to_check, $codes);
            
            if ($found_key !== false) {
                unset($users[$username]['2fa_codes'][$found_key]);
                
                session_regenerate_id(true);
                $session_token = bin2hex(random_bytes(32));
                $_SESSION['loggedin'] = true;
                $_SESSION['username'] = $username;
                $_SESSION['session_token'] = $session_token;
                unset($_SESSION['2fa_user']);
                
                $user_info = $users[$username];
                $_SESSION['user_info'] = [
                    'name' => $user_info['name'],
                    'bio' => $user_info['bio'] ?? '',
                    'avatar' => $user_info['avatar'] ?? null,
                    'color' => $user_info['color'],
                    'username' => $username,
                    'settings' => $user_info['settings'] ?? ['theme' => 'dark', 'primary_color' => '#00DC82']
                ];
                
                $ip = get_ip_address();
                add_announcement($username, "ورود موفق (2FA) با IP: $ip");
                
                $users[$username]['last_ip'] = $ip;
                $users[$username]['session_token'] = $session_token;
                write_locked_json($usersFile, $users);

                header('Location: ' . $_SERVER['PHP_SELF']);
                exit;
            } else {
                $error = 'کد پشتیبان نامعتبر است.';
                $action = '2fa_page';
            }
        }
    }
}

if ($action === 'logout') {
    if (isset($_SESSION['username'])) {
        $users = read_locked_json($usersFile);
        if (isset($users[$_SESSION['username']])) {
            $users[$_SESSION['username']]['session_token'] = null;
            write_locked_json($usersFile, $users);
        }
    }
    session_unset();
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>ورود به چت</title>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        :root {
            --font-family: 'Vazirmatn', sans-serif;
            --primary-hue: 165;
            --primary-saturation: 100%;
            --primary-lightness: 45%;
            --primary-color: hsl(var(--primary-hue), var(--primary-saturation), var(--primary-lightness));
            --primary-color-dark: hsl(var(--primary-hue), var(--primary-saturation), calc(var(--primary-lightness) - 10%));
            
            --bg-deep: #f4f7fa;
            --bg-surface: #ffffff;
            --text-primary: #1a202c;
            --text-muted: #718096;
            --border-color: #e2e8f0;
            --input-bg: #edf2f7;
            --error-bg: #fff5f5;
            --error-text: #e53e3e;
            --error-border: #fed7d7;
            --success-bg: #f0fff4;
            --success-text: #38a169;
            --success-border: #c6f6d5;
            --shadow-color: rgba(0, 0, 0, 0.1);
        }
        
        [data-theme="dark"] {
            --bg-deep: #121418;
            --bg-surface: #1B1E20;
            --text-primary: #F0F2F3;
            --text-muted: #8A9199;
            --border-color: #2a2f35;
            --input-bg: #23272C;
            --error-bg: rgba(255, 69, 100, 0.1);
            --error-text: #FF4564;
            --error-border: #50202a;
            --success-bg: rgba(0, 224, 143, 0.1);
            --success-text: #00E08F;
            --success-border: #004d3a;
            --shadow-color: rgba(0, 0, 0, 0.6);
        }
        
        * { 
            box-sizing: border-box; 
            -webkit-tap-highlight-color: transparent; 
        }
        
        body { 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            min-height: 100vh;
            min-height: 100dvh;
            margin: 0; 
            background-color: var(--bg-deep); 
            color: var(--text-primary); 
            font-family: var(--font-family); 
            padding: 20px;
            overflow: hidden;
            position: relative;
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        
        .theme-toggle {
            position: absolute;
            top: 20px;
            left: 20px;
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background-color: var(--bg-surface);
            border: 1px solid var(--border-color);
            color: var(--text-muted);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            cursor: pointer;
            transition: all 0.3s ease;
            z-index: 10;
        }
        .theme-toggle:hover {
            color: var(--text-primary);
            box-shadow: 0 4px 15px var(--shadow-color);
        }
        .theme-toggle .fa-sun { display: none; }
        .theme-toggle .fa-moon { display: block; }
        [data-theme="dark"] .theme-toggle .fa-sun { display: block; }
        [data-theme="dark"] .theme-toggle .fa-moon { display: none; }
        
        .background-blobs {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
            overflow: hidden;
        }
        
        .blob {
            position: absolute;
            border-radius: 50%;
            filter: blur(120px);
            opacity: 0.15;
            transition: background 0.3s ease;
        }
        
        [data-theme="dark"] .blob {
            opacity: 0.2;
        }
        
        .blob1 {
            width: 450px;
            height: 450px;
            background: var(--primary-color);
            top: -150px;
            left: -150px;
            animation: moveBlob1 25s ease-in-out infinite alternate;
        }
        
        .blob2 {
            width: 350px;
            height: 350px;
            background: #3498db;
            bottom: -100px;
            right: -100px;
            animation: moveBlob2 30s ease-in-out infinite alternate;
        }
        
        @keyframes moveBlob1 {
            from { transform: translate(0, 0) scale(1); }
            to { transform: translate(200px, 300px) scale(1.2); }
        }
        
        @keyframes moveBlob2 {
            from { transform: translate(0, 0) scale(1); }
            to { transform: translate(-300px, -200px) scale(0.8); }
        }
        
        .auth-container { 
            padding: 40px 35px; 
            background-color: var(--bg-surface);
            border-radius: 24px; 
            box-shadow: 0 16px 48px var(--shadow-color); 
            text-align: center; 
            width: 100%; 
            max-width: 420px; 
            border: 1px solid var(--border-color);
            animation: popIn 0.7s cubic-bezier(0.18, 0.89, 0.32, 1.28); 
            position: relative;
            z-index: 1;
            overflow: hidden;
            transition: all 0.3s ease;
        }
        
        [data-theme="dark"] .auth-container {
             background-color: rgba(28, 30, 31, 0.6);
             backdrop-filter: blur(25px) saturate(180%);
             border-color: rgba(255, 255, 255, 0.08);
        }
        
        @keyframes popIn { 
            from { opacity: 0; transform: scale(0.9) translateY(20px); } 
            to { opacity: 1; transform: scale(1) translateY(0); } 
        }
        
        .auth-logo {
            font-size: 3.5rem;
            color: var(--primary-color);
            margin-bottom: 15px;
            text-shadow: 0 0 25px hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.6);
            animation: floatLogo 3.5s ease-in-out infinite;
        }
        
        @keyframes floatLogo {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-10px); }
        }
        
        h2 { 
            margin-top: 0;
            margin-bottom: 30px; 
            font-size: 1.75em; 
            font-weight: 700; 
        } 
        
        h2 span { 
            color: var(--primary-color);
            text-shadow: 0 0 10px hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.4);
        }
        
        .input-group {
            position: relative;
            margin-bottom: 25px;
        }
        
        .input-group .icon-right {
            position: absolute;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            color: var(--text-muted);
            transition: color 0.3s ease;
            font-size: 0.9em;
            z-index: 2;
        }
        
        .input-group .icon-left {
            position: absolute;
            top: 50%;
            left: 20px;
            transform: translateY(-50%);
            color: var(--text-muted);
            transition: color 0.3s ease;
            font-size: 0.9em;
            cursor: pointer;
            z-index: 2;
        }
        
        .input-group .icon-left:hover {
            color: var(--text-primary);
        }
        
        input { 
            width: 100%; 
            padding: 15px 50px 15px 50px; 
            border: 1px solid var(--border-color); 
            background-color: var(--input-bg); 
            color: var(--text-primary); 
            border-radius: 12px; 
            text-align: right; 
            font-size: 1em; 
            font-family: var(--font-family); 
            transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); 
            position: relative;
            z-index: 1;
        }
        
        input:-webkit-autofill,
        input:-webkit-autofill:hover, 
        input:-webkit-autofill:focus, 
        input:-webkit-autofill:active  {
            -webkit-box-shadow: 0 0 0 30px var(--input-bg) inset !important;
            -webkit-text-fill-color: var(--text-primary) !important;
            caret-color: var(--text-primary) !important;
            border-color: var(--primary-color);
        }
        
        input:focus { 
            outline: none; 
            border-color: var(--primary-color); 
            background-color: var(--bg-surface);
            box-shadow: 0 0 20px hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.3); 
        }
        
        .input-group input:focus ~ .icon-right {
            color: var(--primary-color);
        }
        
        .btn-submit { 
            width: 100%;
            padding: 15px; 
            border: none; 
            background: linear-gradient(45deg, var(--primary-color), var(--primary-color-dark)); 
            color: #111314; 
            border-radius: 12px; 
            cursor: pointer; 
            font-size: 1.1em; 
            font-weight: 700; 
            transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); 
            box-shadow: 0 6px 20px hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.25); 
            transform: perspective(1px) scale(1);
        }
        
        .btn-submit:hover { 
            transform: scale(1.05) translateY(-2px); 
            box-shadow: 0 10px 30px hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.5); 
        }
        
        .btn-submit:active {
             transform: scale(1.02) translateY(0);
             box-shadow: 0 6px 20px hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.3);
        }
        
        .alert { 
            margin-top: 20px;
            padding: 13px; 
            border-radius: 10px; 
            font-weight: 500; 
            font-size: 0.9em; 
            animation: fadeIn 0.3s; 
            word-wrap: break-word;
            text-align: right;
            border: 1px solid;
            box-shadow: 0 4px 15px var(--shadow-color);
        }
        
        .alert.error { 
            color: var(--error-text); 
            background-color: var(--error-bg); 
            border-color: var(--error-border);
        }
        
        .alert.success { 
            color: var(--success-text); 
            background-color: var(--success-bg); 
            border-color: var(--success-border);
        }
        
        @keyframes fadeIn { 
            from { opacity: 0; transform: translateY(10px); } 
            to { opacity: 1; transform: translateY(0); } 
        }
        
        .form-switch { 
            margin-top: 30px; 
            font-size: 0.95em; 
            color: var(--text-muted);
        } 
        
        .form-switch a { 
            color: var(--primary-color); 
            text-decoration: none; 
            font-weight: 500; 
            transition: all 0.3s ease;
        }
        
        .form-switch a:hover {
            color: var(--primary-color-dark);
            text-shadow: 0 0 10px var(--primary-color);
        }
        
        [data-theme="dark"] .form-switch a:hover {
            color: #fff;
        }
        
        .form-info { 
            font-size: 0.9em; 
            color: var(--text-muted); 
            margin-bottom: 25px; 
            line-height: 1.6;
        }
        
        @media (max-width: 480px) {
            body {
                align-items: stretch;
                padding: 0;
            }
            .theme-toggle {
                top: 15px;
                left: 15px;
            }
            .auth-container {
                width: 100%;
                height: 100%;
                height: 100dvh;
                max-width: none;
                border-radius: 0;
                border: none;
                box-shadow: none;
                display: flex;
                flex-direction: column;
                justify-content: center;
                padding-left: 25px;
                padding-right: 25px;
                background-color: transparent;
            }
            
            [data-theme="dark"] .auth-container {
                backdrop-filter: none;
            }
            
            .background-blobs {
                filter: blur(80px);
                opacity: 0.4;
            }
        }
    </style>
</head>
<body>

    <div class="theme-toggle" id="theme-toggle" title="تغییر تم">
        <i class="fas fa-moon"></i>
        <i class="fas fa-sun"></i>
    </div>

    <div class="background-blobs">
        <div class="blob blob1"></div>
        <div class="blob blob2"></div>
    </div>

    <div class="auth-container" id="auth-container">
        <div class="auth-logo"><i class="fas fa-comments-dollar"></i></div>
        <?php if ($action === 'register_page' || $action === 'register'): ?>
        <h2>ایجاد <span>حساب کاربری</span></h2>
        <form method="post" id="register-form">
            <input type="hidden" name="action" value="register">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
            <div class="input-group">
                <input type="text" name="name" placeholder="نام نمایشی" required>
                <i class="fas fa-user icon-right"></i>
            </div>
            <div class="input-group">
                <input type="text" name="username" placeholder="نام کاربری (انگلیسی)" required pattern="[a-zA-Z0-9_]{3,20}" title="نام کاربری باید بین ۳ تا ۲۰ کاراکتر و فقط شامل حروف انگلیسی، اعداد و _ باشد." autocomplete="username">
                <i class="fas fa-at icon-right"></i>
            </div>
            <div class="input-group">
                <input type="password" name="password" placeholder="رمز عبور" required minlength="6" autocomplete="new-password">
                <i class="fas fa-lock icon-right"></i>
                <i class="fas fa-eye-slash icon-left toggle-password"></i>
            </div>
            <button type="submit" class="btn-submit">ثبت‌نام</button>
        </form>
        <div class="form-switch">حساب کاربری دارید؟ <a href="?action=login_page">وارد شوید</a></div>
        <?php elseif ($action === '2fa_page' || $action === 'verify_2fa'): ?>
        <h2>تایید <span>دو مرحله‌ای</span></h2>
        <p class="form-info">لطفاً یکی از کدهای پشتیبان خود را وارد کنید. (فرمت: xxxx-xxxx)</p>
        <form method="post" id="2fa-form">
            <input type="hidden" name="action" value="verify_2fa">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
            <div class="input-group">
                <input type="text" name="2fa_code" placeholder="کد پشتیبان" required autocomplete="one-time-code" style="text-align: center; font-family: monospace; font-size: 1.2em; letter-spacing: 2px; padding-left: 50px; padding-right: 50px;">
                <i class="fas fa-shield-alt icon-right"></i>
            </div>
            <button type="submit" class="btn-submit">تایید</button>
        </form>
        <div class="form-switch">بازگشت به <a href="?action=login_page">صفحه ورود</a></div>
        <?php else: ?>
        <h2>ورود به <span>ایرنا</span></h2>
        <form method="post" id="login-form">
            <input type="hidden" name="action" value="login">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
            <div class="input-group">
                <input type="text" name="username" placeholder="نام کاربری" required autocomplete="username">
                <i class="fas fa-user icon-right"></i>
            </div>
            <div class="input-group">
                <input type="password" name="password" placeholder="رمز عبور" required autocomplete="current-password">
                <i class="fas fa-lock icon-right"></i>
                <i class="fas fa-eye-slash icon-left toggle-password"></i>
            </div>
            <button type="submit" class="btn-submit">ورود</button>
        </form>
        <div class="form-switch">حساب کاربری ندارید؟ <a href="?action=register_page">ثبت‌نام کنید</a></div>
        <?php endif; ?>
        <?php if ($error) echo '<p class="alert error">' . htmlspecialchars(urldecode($error)) . '</p>'; ?>
        <?php if ($success) echo '<p class="alert success">' . htmlspecialchars($success) . '</p>'; ?>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const passwordToggles = document.querySelectorAll('.toggle-password');
            passwordToggles.forEach(function(toggle) {
                toggle.addEventListener('click', function() {
                    const inputGroup = this.closest('.input-group');
                    if (!inputGroup) return;

                    const input = inputGroup.querySelector('input');
                    if (!input) return;

                    if (input.type === 'password') {
                        input.type = 'text';
                        this.classList.remove('fa-eye-slash');
                        this.classList.add('fa-eye');
                    } else {
                        input.type = 'password';
                        this.classList.remove('fa-eye');
                        this.classList.add('fa-eye-slash');
                    }
                });
            });

            const themeToggle = document.getElementById('theme-toggle');
            const root = document.documentElement;
            let currentTheme = localStorage.getItem('theme') || 'dark';

            function applyTheme(theme) {
                root.setAttribute('data-theme', theme);
                localStorage.setItem('theme', theme);
            }

            themeToggle.addEventListener('click', () => {
                currentTheme = root.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
                applyTheme(currentTheme);
            });

            applyTheme(currentTheme);
        });
    </script>
</body>
</html>

<?php exit; } 
$userInfo = $_SESSION['user_info'];
$userTheme = $userInfo['settings']['theme'] ?? 'dark';
$userColor = htmlspecialchars($userInfo['settings']['primary_color'] ?? '#00DC82');

preg_match('/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/', $userColor, $matches);
if (count($matches) === 4) {
    $userColorH = $matches[1];
    $userColorS = $matches[2] . '%';
    $userColorL = $matches[3] . '%';
} else {
    $userColorH = '158';
    $userColorS = '100%';
    $userColorL = '44%';
}
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>چت</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <style>
        :root {
            --font-family: 'Vazirmatn', sans-serif;
            --primary-hue: <?= $userColorH ?>;
            --primary-saturation: <?= $userColorS ?>;
            --primary-lightness: <?= $userColorL ?>;
            --primary-color: hsl(var(--primary-hue), var(--primary-saturation), var(--primary-lightness));
            --primary-color-light: hsl(var(--primary-hue), var(--primary-saturation), calc(var(--primary-lightness) + 10%));
            --primary-color-dark: hsl(var(--primary-hue), var(--primary-saturation), calc(var(--primary-lightness) - 10%));
            --primary-color-trans: hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.1);
            --text-on-primary: #ffffff;
            --error-color: #ff5252;
            --success-color: #00DC82;
            --border-radius-sm: 8px;
            --border-radius-md: 12px;
            --border-radius-lg: 16px;

            --bg-deep: #f8f9fa;
            --bg-surface-1: #ffffff;
            --bg-surface-2: #f1f3f5;
            --text-primary: #1a202c;
            --text-muted: #718096;
            --border-color: #e2e8f0;
            --shadow-color: rgba(45, 55, 72, 0.08);
            --shadow-color-lg: rgba(45, 55, 72, 0.12);
        }
        
        [data-theme="dark"] {
            --bg-deep: #111314;
            --bg-surface-1: #1A1D21;
            --bg-surface-2: #23272C;
            --text-primary: #E1E3E4;
            --text-muted: #8E9297;
            --border-color: #2a2f35;
            --shadow-color: rgba(0, 0, 0, 0.15);
            --shadow-color-lg: rgba(0, 0, 0, 0.25);
        }

        * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        
        body { 
            margin: 0; 
            font-family: var(--font-family); 
            background: var(--bg-deep); 
            color: var(--text-primary); 
            display: flex; 
            justify-content: center;
            align-items: center;
            height: 100vh;
            height: 100dvh; 
            overflow: hidden; 
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        
        .app-wrapper {
            display: flex;
            width: 100%;
            height: 100%;
            height: 100dvh;
            background-color: var(--bg-surface-1);
            transition: all 0.3s ease;
        }
        
        .desktop-sidebar {
            display: none;
            flex-direction: column;
            width: 80px;
            background: var(--bg-surface-2);
            padding: 20px 0;
            flex-shrink: 0;
            align-items: center;
            border-left: 1px solid var(--border-color);
            transition: background-color 0.3s ease, border-color 0.3s ease;
        }
        
        .sidebar-logo {
            font-size: 1.8rem;
            color: var(--primary-color);
            margin-bottom: 30px;
        }
        
        .sidebar-nav {
            display: flex;
            flex-direction: column;
            gap: 15px;
            width: 100%;
            align-items: center;
        }
        
        .desktop-sidebar .nav-item {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: var(--border-radius-md);
            color: var(--text-muted);
            font-size: 1.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .desktop-sidebar .nav-item:hover {
            color: var(--primary-color);
            background: var(--primary-color-trans);
        }
        
        .desktop-sidebar .nav-item.active {
            color: var(--text-on-primary);
            background: var(--primary-color);
            box-shadow: 0 5px 15px hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.3);
        }
        
        .sidebar-footer {
            margin-top: auto;
        }
        
        .sidebar-footer a {
            color: var(--text-muted);
            font-size: 1.4rem;
            transition: color 0.3s ease;
        }
        
        .sidebar-footer a:hover {
            color: var(--error-color);
        }
        
        .container { 
            width: 100%; 
            height: 100%; 
            display: flex; 
            flex-direction: column; 
            position: relative;
            overflow: hidden;
        }
        
        .page { display: none; flex-direction: column; height: 100%; width: 100%; overflow: hidden;}
        .page.active { display: flex; animation: pageFadeIn 0.4s ease; }
        @keyframes pageFadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        
        .header { 
            padding: 15px 20px; 
            background-color: var(--bg-surface-1); 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            flex-shrink: 0; 
            border-bottom: 1px solid var(--border-color); 
            transition: background-color 0.3s ease, border-color 0.3s ease;
            box-shadow: 0 2px 5px var(--shadow-color);
            z-index: 10;
        }
        
        .header h1 { margin: 0; font-size: 1.3rem; font-weight: 600; }
        .header .header-icon { color: var(--text-muted); text-decoration: none; font-size: 1.3rem; transition: color 0.2s; }
        .header .header-icon:hover { color: var(--primary-color); }
        
        .search-container { padding: 10px 15px; border-bottom: 1px solid var(--border-color); flex-shrink: 0; transition: border-color 0.3s ease; }
        #search-input { 
            width: 100%; 
            padding: 12px 20px; 
            border: 1px solid var(--border-color); 
            border-radius: 25px; 
            background-color: var(--bg-surface-2); 
            color: var(--text-primary); 
            font-family: var(--font-family); 
            font-size: 1em; 
            transition: all 0.3s ease; 
        }
        #search-input:focus { 
            outline: none; 
            background: var(--bg-surface-1); 
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px var(--primary-color-trans); 
        }
        
        .content-area { flex-grow: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; padding: 8px; }
        .chat-list, .search-results { list-style: none; padding: 0; margin: 0; }
        .chat-item { 
            display: flex; 
            align-items: center; 
            padding: 12px 15px; 
            cursor: pointer; 
            transition: all 0.2s ease; 
            border-radius: var(--border-radius-lg); 
            margin: 4px; 
            text-decoration: none; 
            color: inherit; 
            position: relative; 
        }
        .chat-item:hover { 
            background-color: var(--bg-surface-2); 
            transform: scale(1.02); 
            box-shadow: 0 4px 10px var(--shadow-color);
        }
        
        .avatar-container { position: relative; cursor: pointer; }
        .avatar { 
            width: 50px; 
            height: 50px; 
            border-radius: 50%; 
            margin-left: 15px; 
            background-color: var(--primary-color); 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            font-weight: bold; 
            font-size: 1.2rem; 
            color: var(--text-on-primary); 
            object-fit: cover; 
            border: 2px solid var(--border-color);
            transition: border-color 0.3s ease;
        }
        .online-indicator { 
            position: absolute; 
            bottom: 2px; 
            left: 0px; 
            width: 14px; 
            height: 14px; 
            background-color: #2ecc71; 
            border-radius: 50%; 
            border: 3px solid var(--bg-surface-1); 
            transition: border-color 0.3s ease;
        }
        
        .chat-info { flex-grow: 1; overflow: hidden; }
        .chat-name { font-weight: 600; display: flex; align-items: center; font-size: 1.05em; }
        .chat-name .fa-thumbtack { font-size: 0.8em; margin-right: 8px; color: var(--primary-color); }
        .last-message { font-size: 0.9rem; color: var(--text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 4px; }
        .chat-meta { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
        .unread-badge { 
            background-color: var(--primary-color); 
            color: var(--text-on-primary); 
            font-size: 0.8rem; 
            font-weight: bold; 
            padding: 3px 8px; 
            border-radius: 12px; 
            min-width: 22px; 
            text-align: center; 
        }
        
        .more-actions-btn { 
            color: var(--text-muted); 
            cursor: pointer; 
            padding: 5px; 
            font-size: 1em; 
            border-radius: 50%; 
            width: 30px; 
            height: 30px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            transition: all 0.2s ease; 
        }
        .more-actions-btn:hover { background-color: var(--bg-surface-2); color: var(--text-primary); }
        .loading, .no-results { text-align: center; padding: 30px; color: var(--text-muted); font-size: 1.1em; }
        
        .context-menu { 
            position: absolute; 
            background-color: var(--bg-surface-1); 
            border-radius: var(--border-radius-md); 
            padding: 5px; 
            display: none; 
            z-index: 1000; 
            box-shadow: 0 5px 20px var(--shadow-color-lg); 
            border: 1px solid var(--border-color); 
            transition: all 0.3s ease;
        }
        .context-menu ul { list-style: none; margin: 0; padding: 0; }
        .context-menu li { 
            padding: 10px 15px; 
            cursor: pointer; 
            transition: all 0.2s; 
            border-radius: var(--border-radius-sm); 
            font-size: 0.9em; 
            display: flex; 
            align-items: center; 
            white-space: nowrap; 
        }
        .context-menu li:hover { background-color: var(--primary-color-trans); color: var(--primary-color-dark); }
        [data-theme="dark"] .context-menu li:hover { color: var(--primary-color-light); }
        .context-menu li i { margin-left: 10px; width: 15px; text-align: center;}
        
        .bottom-nav { 
            display: flex; 
            background-color: var(--bg-surface-1); 
            flex-shrink: 0; 
            border-top: 1px solid var(--border-color); 
            box-shadow: 0 -2px 5px var(--shadow-color);
            transition: all 0.3s ease;
        }
        .nav-item { flex-grow: 1; text-align: center; padding: 12px 0; color: var(--text-muted); cursor: pointer; transition: all 0.2s; }
        .nav-item.active { color: var(--primary-color); }
        .nav-item i { font-size: 1.5rem; }
        
        .settings-content { padding: 20px; }
        .setting-section { 
            margin-bottom: 25px; 
            background: var(--bg-surface-1); 
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius-lg); 
            padding: 20px; 
            transition: all 0.3s ease;
        }
        [data-theme="dark"] .setting-section { background: var(--bg-surface-2); }
        
        .setting-section h3 { margin-top: 0; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; font-size: 1.2rem; transition: border-color 0.3s ease; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-size: 0.95em; font-weight: 500; }
        .form-group input, .form-group textarea, .form-group select { 
            width: 100%; 
            padding: 12px; 
            background: var(--bg-surface-2); 
            border: 1px solid var(--border-color); 
            border-radius: var(--border-radius-md); 
            color: var(--text-primary); 
            font-family: var(--font-family); 
            font-size: 1em; 
            transition: all 0.3s ease; 
        }
        .form-group input:focus, .form-group textarea:focus, .form-group select:focus { 
            outline: none; 
            border-color: var(--primary-color); 
            background: var(--bg-surface-1); 
            box-shadow: 0 0 0 3px var(--primary-color-trans); 
        }
        .form-group textarea { resize: vertical; min-height: 80px; }
        
        .avatar-setting { display: flex; align-items: center; gap: 20px; }
        #avatar-preview { 
            width: 80px; 
            height: 80px; 
            border-radius: 50%; 
            object-fit: cover; 
            cursor: pointer; 
            background-color: var(--bg-surface-2); 
            border: 2px dashed var(--border-color); 
            transition: all 0.3s ease;
        }
        
        .btn { 
            padding: 12px 22px; 
            border: none; 
            border-radius: var(--border-radius-md); 
            background-color: var(--primary-color); 
            color: var(--text-on-primary); 
            font-weight: 600; 
            cursor: pointer; 
            transition: all 0.3s ease; 
            display: inline-flex; 
            justify-content: center; 
            align-items: center; 
            gap: 8px; 
            text-decoration: none; 
            font-family: var(--font-family); 
            font-size: 1em; 
            transform: translateY(0);
            box-shadow: 0 4px 12px hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.2);
        }
        .btn:hover { 
            transform: translateY(-3px); 
            background-color: var(--primary-color-light); 
            box-shadow: 0 6px 15px hsla(var(--primary-hue), var(--primary-saturation), var(--primary-lightness), 0.3); 
        }
        [data-theme="dark"] .btn:hover { background-color: var(--primary-color-light); }
        [data-theme="light"] .btn:hover { background-color: var(--primary-color-dark); }
        
        .btn:active { transform: translateY(-1px); }
        .btn.btn-danger { background-color: var(--error-color); box-shadow: 0 4px 12px rgba(255, 82, 82, 0.2); }
        .btn.btn-danger:hover { background-color: #ff2a2a; box-shadow: 0 6px 15px rgba(255, 82, 82, 0.3); }
        .btn:disabled { background-color: var(--text-muted); cursor: not-allowed; transform: none; filter: brightness(0.7); box-shadow: none; }
        
        .toast { 
            position: fixed; 
            bottom: 20px; 
            left: 50%; 
            transform: translateX(-50%); 
            background: #333; 
            color: white; 
            padding: 12px 25px; 
            border-radius: 25px; 
            z-index: 2000; 
            display: none; 
            font-size: 0.95em; 
            box-shadow: 0 5px 20px var(--shadow-color-lg); 
        }
        [data-theme="light"] .toast { background: #333; color: white; }
        [data-theme="dark"] .toast { background: #f0f0f0; color: #333; }
        
        .color-swatches { display: flex; gap: 10px; margin-top: 10px; flex-wrap: wrap; }
        .color-swatch { 
            width: 35px; 
            height: 35px; 
            border-radius: 50%; 
            cursor: pointer; 
            border: 3px solid var(--bg-surface-1); 
            transition: all 0.2s ease; 
        }
        .color-swatch:hover { transform: scale(1.1); }
        .color-swatch.active { border-color: var(--primary-color); box-shadow: 0 0 10px var(--primary-color); }
        
        .theme-switch-wrapper {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .theme-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 28px;
        }
        .theme-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--bg-surface-2);
            border: 1px solid var(--border-color);
            transition: .4s;
            border-radius: 34px;
        }
        .slider:before {
            position: absolute;
            content: "\f185";
            font-family: "Font Awesome 6 Free";
            font-weight: 900;
            color: #f39c12;
            height: 20px;
            width: 20px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8em;
        }
        input:checked + .slider {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        input:checked + .slider:before {
            transform: translateX(22px);
            content: "\f186";
            color: #34495e;
        }

        .modal-backdrop { 
            position: fixed; 
            top: 0; 
            left: 0; 
            width: 100%; 
            height: 100%; 
            background: rgba(0,0,0,0.5); 
            z-index: 1500; 
            display: none; 
            justify-content: center; 
            align-items: center; 
            backdrop-filter: blur(5px); 
        }
        [data-theme="light"] .modal-backdrop { background: rgba(255, 255, 255, 0.5); }
        
        .modal-content { 
            background: var(--bg-surface-1); 
            padding: 20px; 
            border-radius: var(--border-radius-lg); 
            width: 350px; 
            max-width: 90%; 
            display: flex; 
            flex-direction: column; 
            align-items: center; 
            animation: popInModal 0.4s cubic-bezier(0.18, 0.89, 0.32, 1.28); 
            border: 1px solid var(--border-color); 
            box-shadow: 0 10px 30px var(--shadow-color-lg);
        }
        @keyframes popInModal { from { opacity: 0; transform: scale(0.9); } to { opacity: 1; transform: scale(1); } }
        
        #profile-modal-content {
            padding: 0;
        }
        .profile-modal-header { width: 100%; height: 100px; border-radius: 16px 16px 0 0; margin: 0; position: relative; transition: background-color 0.3s ease; }
        .profile-modal-avatar { 
            width: 120px; 
            height: 120px; 
            border-radius: 50%; 
            object-fit: cover; 
            border: 6px solid var(--bg-surface-1); 
            position: absolute; 
            bottom: -60px; 
            left: 50%; 
            transform: translateX(-50%); 
            background-color: var(--bg-surface-2); 
            transition: all 0.3s ease;
        }
        .profile-modal-body { padding: 70px 20px 0 20px; text-align: center; width: 100%; }
        .profile-modal-body h3 { margin: 10px 0 5px; font-size: 1.5rem; }
        .profile-modal-body .username { color: var(--text-muted); font-size: 0.9em; }
        .profile-modal-body .profile-status { display: flex; align-items: center; justify-content: center; gap: 5px; margin-top: 5px; font-size: 0.9em; }
        .profile-modal-body .bio { margin: 15px 0; color: var(--text-primary); white-space: pre-wrap; word-wrap: break-word; font-size: 0.95em; }
        .profile-modal-info { text-align: right; width: 100%; margin-top: 20px; border-top: 1px solid var(--bg-surface-2); padding-top: 15px; transition: border-color 0.3s ease; }
        .info-item { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; font-size: 0.9em; }
        .info-item i { width: 20px; text-align: center; color: var(--text-muted); }
        .profile-modal-actions { margin-top: 20px; display: flex; gap: 10px; width: 100%; padding: 0 20px 20px 20px; box-sizing: border-box; }
        .profile-modal-actions .btn { flex-grow: 1; }
        
        .backup-codes-container { margin-top: 15px; background: var(--bg-surface-2); padding: 20px; border-radius: var(--border-radius-md); transition: background-color 0.3s ease; }
        .backup-codes-container h4 { margin: 0 0 10px 0; }
        .backup-codes-list { 
            display: grid; 
            grid-template-columns: 1fr 1fr; 
            gap: 12px; 
            font-family: monospace; 
            font-size: 1.1em; 
            color: var(--success-color); 
        }
        
        #status-emoji-picker { 
            display: none; 
            position: absolute; 
            background: var(--bg-surface-1); 
            border-radius: var(--border-radius-md); 
            padding: 5px; 
            box-shadow: 0 5px 15px var(--shadow-color-lg); 
            z-index: 10; 
            border: 1px solid var(--border-color); 
            transition: all 0.3s ease;
        }
        .emoji-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 2px; }
        .emoji-grid span { 
            cursor: pointer; 
            padding: 5px; 
            border-radius: var(--border-radius-sm); 
            transition: background 0.2s; 
            font-size: 1.2em; 
            text-align: center;
        }
        .emoji-grid span:hover { background: var(--bg-surface-2); }
        
        .mobile-logout-section { display: block; }

        @media (min-width: 768px) {
            body { padding: 20px; }
            .app-wrapper {
                width: 95%;
                max-width: 1200px;
                height: 90vh;
                max-height: 900px;
                border-radius: 24px;
                box-shadow: 0 20px 60px var(--shadow-color-lg);
                overflow: hidden;
            }
            .desktop-sidebar { display: flex; }
            .container { flex-grow: 1; height: 100%; }
            .bottom-nav { display: none; }
            .mobile-logout-section { display: none; }
            .toast { bottom: 40px; }
            .back-from-settings { display: none !important; }
        }
    </style>
</head>
<body data-user-id="<?= htmlspecialchars($_SESSION['username']) ?>" data-csrf-token="<?= htmlspecialchars($_SESSION['csrf_token']) ?>" data-theme="<?= $userTheme ?>">
    
    <div class="app-wrapper">
        <nav class="desktop-sidebar">
            <div class="sidebar-logo">
                <i class="fas fa-comments"></i>
            </div>
            <div class="sidebar-nav">
                <div class="nav-item active" data-page="home-page" title="چت‌ها">
                    <i class="fas fa-comments"></i>
                </div>
                <div class="nav-item" data-page="settings-page" title="تنظیمات">
                    <i class="fas fa-cog"></i>
                </div>
            </div>
            <div class="sidebar-footer">
                <a href="?action=logout" title="خروج">
                    <i class="fas fa-sign-out-alt"></i>
                </a>
            </div>
        </nav>

        <div class="container">
            <div id="home-page" class="page active">
                <header class="header">
                    <h1>IRna</h1>
                    <span class="header-icon" style="width: 24px;"></span>
                </header>
                <div class="search-container">
                    <input type="text" id="search-input" placeholder="Search 🌠">
                </div>
                <main class="content-area">
                    <ul class="chat-list" id="chat-list-container"></ul>
                    <ul class="search-results" id="search-results-container" style="display: none;"></ul>
                </main>
            </div>
            
            <div id="settings-page" class="page">
                 <header class="header">
                     <a href="#" class="back-from-settings header-icon" title="بازگشت" style="display: none;"><i class="fas fa-arrow-right"></i></a>
                     <h1>settings</h1>
                     <span class="header-icon" style="width: 24px;"></span>
                 </header>
                 <main class="content-area settings-content">
                    <div class="setting-section">
                        <h3>اطلاعات کاربری</h3>
                        <form id="profile-form">
                            <div class="avatar-setting form-group">
                                <img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" id="avatar-preview" alt="Avatar">
                                <div>
                                    <input type="file" id="avatar-input" accept="image/*" style="display: none;">
                                    <button type="button" class="btn" onclick="$('#avatar-input').click();">تغییر عکس</button>
                                    <small style="display: block; margin-top: 10px; color: var(--text-muted); font-size: 0.85em;">حداکثر ۵ مگابایت</small>
                                </div>
                            </div>
                            <div class="form-group"><label for="name-input">نام نمایشی</label><input type="text" id="name-input" name="name"></div>
                            <div class="form-group"><label for="username-input">نام کاربری</label><input type="text" id="username-input" name="username" pattern="[a-zA-Z0-9_]{3,20}"></div>
                            <div class="form-group"><label for="bio-input">بیوگرافی</label><textarea id="bio-input" name="bio" rows="3"></textarea></div>
                            <button type="submit" class="btn"><i class="fas fa-save"></i><span class="btn-text">ذخیره اطلاعات</span></button>
                        </form>
                    </div>
                    
                    <div class="setting-section">
                        <h3>تنظیم وضعیت</h3>
                        <form id="profile-status-form">
                            <div class="form-group" style="display: flex; gap: 10px; align-items: flex-end;">
                                <div style="position: relative;">
                                    <label>ایموجی</label>
                                    <input type="text" id="status-emoji-input" name="emoji" style="width: 60px; text-align: center; font-size: 1.2em;" readonly>
                                    <div id="status-emoji-picker"></div>
                                </div>
                                <div style="flex-grow: 1;">
                                    <label for="status-text-input">وضعیت</label>
                                    <input type="text" id="status-text-input" name="text" placeholder="چه خبر؟">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="status-duration-select">پاک شدن خودکار</label>
                                <select id="status-duration-select" name="duration">
                                    <option value="clear">همین الان پاک کن</option>
                                    <option value="30_mins">تا ۳۰ دقیقه دیگر</option>
                                    <option value="1_hour">تا ۱ ساعت دیگر</option>
                                    <option value="today">امشب</option>
                                    <option value="never" selected>هرگز</option>
                                </select>
                            </div>
                            <button type="submit" class="btn"><i class="fas fa-smile"></i><span class="btn-text">ثبت وضعیت</span></button>
                        </form>
                    </div>
                    
                     <div class="setting-section">
                        <h3>امنیت</h3>
                         <form id="password-form">
                            <h4>تغییر رمز عبور</h4>
                            <div class="form-group"><label for="current-password">رمز فعلی</label><input type="password" id="current-password" name="current_password" required autocomplete="current-password"></div>
                            <div class="form-group"><label for="new-password">رمز جدید</label><input type="password" id="new-password" name="new_password" required minlength="6" autocomplete="new-password"></div>
                            <button type="submit" class="btn"><i class="fas fa-key"></i><span class="btn-text">تغییر رمز</span></button>
                         </form>
                         
                         <div id="2fa-section" style="margin-top: 25px;">
                             <h4>تایید دو مرحله‌ای (2FA)</h4>
                             <div id="2fa-status-enabled" style="display: none;">
                                 <p style="color: var(--success-color);"><i class="fas fa-check-circle"></i> تایید دو مرحله‌ای فعال است.</p>
                                 <form id="disable-2fa-form">
                                     <div class="form-group">
                                         <label for="disable-2fa-password">برای غیرفعال‌سازی، رمز عبور خود را وارد کنید:</label>
                                         <input type="password" id="disable-2fa-password" name="password" required>
                                     </div>
                                     <button type="submit" class="btn btn-danger"><i class="fas fa-shield-alt"></i><span class="btn-text">غیرفعال کردن 2FA</span></button>
                                 </form>
                             </div>
                             <div id="2fa-status-disabled" style="display: none;">
                                 <p>با فعال‌سازی تایید دو مرحله‌ای، برای هر بار ورود به یک کد پشتیبان یکبار مصرف نیاز خواهید داشت.</p>
                                 <button id="enable-2fa-btn" class="btn"><i class="fas fa-shield-alt"></i><span class="btn-text">فعال کردن 2FA</span></button>
                             </div>
                             <div id="2fa-backup-codes-container" class="backup-codes-container" style="display: none;">
                                 <h4>کدهای پشتیبان شما</h4>
                                 <p style="font-size: 0.9em; color: var(--text-muted);">این کدها را در جای امنی ذخیره کنید. پس از بستن این پنجره، دیگر نمایش داده نخواهند شد.</p>
                                 <div id="2fa-backup-codes-list" class="backup-codes-list"></div>
                                 <button id="close-2fa-codes" class="btn" style="margin-top: 15px;">متوجه شدم، ذخیره کردم</button>
                             </div>
                         </div>
                     </div>
                     
                     <div class="setting-section">
                        <h3>شخصی‌سازی</h3>
                        <form id="theme-form">
                            <div class="form-group">
                                <label>تم برنامه</label>
                                <div class="theme-switch-wrapper">
                                    <label class="theme-switch">
                                        <input type="checkbox" id="theme-toggle-checkbox" <?= $userTheme === 'dark' ? 'checked' : '' ?>>
                                        <span class="slider"></span>
                                    </label>
                                    <span id="theme-label"><?= $userTheme === 'dark' ? 'تاریک' : 'روشن' ?></span>
                                </div>
                            </div>
                            <div class="form-group">
                               <label for="primary-color-input">رنگ اصلی برنامه</label>
                               <div class="color-swatches" id="color-swatches-container"></div>
                               <input type="hidden" id="primary-color-input" name="primary_color" value="<?= $userColor ?>">
                            </div>
                        </form>
                     </div>
                     <div class="setting-section">
                        <h3>حریم خصوصی</h3>
                         <form id="privacy-form">
                            <div class="form-group">
                                <label for="last-seen-select">آخرین بازدید من را چه کسی ببیند؟</label>
                                <select id="last-seen-select" name="last_seen">
                                    <option value="everyone">همه</option>
                                    <option value="nobody">هیچکس</option>
                                </select>
                            </div>
                         </form>
                     </div>
                     <div class="setting-section mobile-logout-section">
                        <a href="?action=logout" class="btn btn-danger" style="width: 100%;"><i class="fas fa-sign-out-alt"></i> خروج از حساب</a>
                     </div>
                 </main>
            </div>

            <nav class="bottom-nav">
                <div class="nav-item active" data-page="home-page"><i class="fas fa-comments"></i></div>
                <div class="nav-item" data-page="settings-page"><i class="fas fa-cog"></i></div>
            </nav>
        </div>
    </div>

    <div class="modal-backdrop" id="profile-modal">
        <div class="modal-content" id="profile-modal-content">
             <div class="profile-modal-header">
                <div id="profile-modal-avatar-container"></div>
             </div>
             <div class="profile-modal-body">
                <h3 id="profile-modal-name"></h3>
                <div id="profile-modal-username" class="username"></div>
                <div id="profile-modal-status" class="profile-status"></div>
                <p id="profile-modal-bio" class="bio"></p>
                
                <div class="profile-modal-info">
                    <div class="info-item">
                        <i class="fas fa-eye"></i>
                        <span id="profile-modal-last-seen"></span>
                    </div>
                     <div class="info-item">
                        <i class="fas fa-link"></i>
                        <a href="#" id="profile-modal-link" style="color: var(--primary-color); text-decoration: none;"></a>
                    </div>
                </div>
             </div>
             <div class="profile-modal-actions">
                <button class="btn" id="close-profile-modal">بستن</button>
                <a href="#" id="profile-modal-message-btn" class="btn">ارسال پیام</a>
             </div>
        </div>
    </div>
    <div class="toast" id="toast"></div>
    <div class="context-menu" id="chat-list-context-menu"></div>
    <div class="modal-backdrop" id="forward-modal">
        <div class="modal-content">
             <h3 style="margin-top:0; width: 100%;">هدایت پیام به...</h3>
             <input type="text" id="forward-search" placeholder="جستجوی چت..." style="width: 100%; padding: 10px; background: var(--bg-deep); border: 1px solid var(--border-color); border-radius: 8px; color: var(--text-primary); font-family: var(--font-family); margin-bottom: 10px; transition: all 0.3s ease;">
             <div id="forward-chat-list" style="width: 100%; max-height: 300px; overflow-y: auto;"></div>
             <div class="modal-actions" style="margin-top: 15px; display: flex; gap: 10px; width: 100%;">
                <button class="btn btn-danger" id="cancel-forward-btn" style="flex-grow: 1;">لغو</button>
                <button class="btn" id="confirm-forward-btn" disabled style="flex-grow: 1;">ارسال</button>
             </div>
        </div>
    </div>

    <script>
    $(document).ready(function() {
        const csrfToken = $('body').data('csrfToken');
        const myUsername = $('body').data('userId');
        let allChatsCache = [];

        $.ajaxSetup({
            error: function(jqXHR, textStatus, errorThrown) {
                if (jqXHR.status === 401 || jqXHR.status === 403) {
                    const response = jqXHR.responseJSON;
                    let message = response ? response.message : 'نشست شما منقضی شده است. لطفاً دوباره وارد شوید.';
                    if (jqXHR.status === 401) {
                         alert(message);
                         window.location.href = 'index.php?action=logout';
                    } else if (response && response.message.includes('suspended')) {
                         alert(message);
                         window.location.href = 'index.php?action=logout';
                    }
                }
            }
        });

        function switchPage(pageId) {
            $('.nav-item').removeClass('active');
            $(`.nav-item[data-page="${pageId}"]`).addClass('active');
            $('.page').removeClass('active');
            $('#' + pageId).addClass('active');
            if (pageId === 'settings-page') loadUserSettings();
            if (pageId === 'home-page' && $(window).width() < 768) $('.back-from-settings').show();
        }

        $('.nav-item').on('click', function() { switchPage($(this).data('page')); });
        $('.back-from-settings').on('click', function(e){ e.preventDefault(); switchPage('home-page'); });
        
        function showToast(message, isError = false) {
            const toast = $('#toast');
            toast.text(message).css('background-color', isError ? 'var(--error-color)' : '').fadeIn(400).delay(2500).fadeOut(400);
        }

        const chatListContainer = $('#chat-list-container');
        const searchResultsContainer = $('#search-results-container');
        const searchInput = $('#search-input');
        let searchTimeout;

        function getInitials(name) { return name ? name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase() : ''; }
        
        function getContrastYIQ(hexcolor){
            if (!hexcolor) return '#111314';
            let r, g, b, h;
            if (hexcolor.startsWith('hsl')) {
                let parts = hexcolor.match(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/);
                if (!parts) return '#111314';
                h = parseInt(parts[1]);
                let s = parseInt(parts[2]) / 100;
                let l = parseInt(parts[3]) / 100;
                let c = (1 - Math.abs(2 * l - 1)) * s,
                    x = c * (1 - Math.abs((h / 60) % 2 - 1)),
                    m = l - c/2;
                if (0 <= h && h < 60) { r = c; g = x; b = 0; }
                else if (60 <= h && h < 120) { r = x; g = c; b = 0; }
                else if (120 <= h && h < 180) { r = 0; g = c; b = x; }
                else if (180 <= h && h < 240) { r = 0; g = x; b = c; }
                else if (240 <= h && h < 300) { r = x; g = 0; b = c; }
                else { r = c; g = 0; b = x; }
                r = Math.round((r + m) * 255);
                g = Math.round((g + m) * 255);
                b = Math.round((b + m) * 255);
            } else {
                hexcolor = hexcolor.replace("#", "");
                if (hexcolor.length === 3) hexcolor = hexcolor.split('').map(char => char + char).join('');
                r = parseInt(hexcolor.substr(0,2),16);
                g = parseInt(hexcolor.substr(2,2),16);
                b = parseInt(hexcolor.substr(4,2),16);
            }
            if (isNaN(r) || isNaN(g) || isNaN(b)) return '#111314';
            var yiq = ((r*299)+(g*587)+(b*114))/1000;
            return (yiq >= 128) ? '#111314' : '#ffffff';
        }

        function sanitizeHTML(str) {
            const temp = document.createElement('div');
            temp.textContent = str;
            return temp.innerHTML;
        }

        function renderAvatar(item, cssClass = 'avatar') {
            const onlineIndicator = item.is_online ? '<div class="online-indicator"></div>' : '';
            const avatarContainerStart = `<div class="avatar-container">`;
            const avatarContainerEnd = `${onlineIndicator}</div>`;
            const contrastColor = getContrastYIQ(item.color);

            if (item.type === 'group') return `${avatarContainerStart}<div class="${cssClass}" style="background-color: #6c757d; color: #fff;"><i class="fas fa-users"></i></div>${avatarContainerEnd}`;
            if (item.type === 'saved') return `${avatarContainerStart}<div class="${cssClass}" style="background-color: #5865f2; color: #fff;"><i class="fas fa-bookmark"></i></div>${avatarContainerEnd}`;
            if (item.type === 'announcements') return `${avatarContainerStart}<div class="${cssClass}" style="background-color: #17a2b8; color: #fff;"><i class="fas fa-bullhorn"></i></div>${avatarContainerEnd}`;
            if (item.avatar) return `${avatarContainerStart}<img src="${item.avatar}?t=${Date.now()}" class="${cssClass}" alt="${item.name}">${avatarContainerEnd}`;
            return `${avatarContainerStart}<div class="${cssClass}" style="background-color: ${item.color || '#888'}; color: ${contrastColor}">${getInitials(item.name)}</div>${avatarContainerEnd}`;
        }
        
        function renderLastMessage(msg) {
            if (!msg) return 'هنوز پیامی ارسال نشده است.';
            let prefix = msg.sender === myUsername ? 'شما: ' : (msg.sender === 'system' ? '' : '');
            if (msg.forward_info) prefix += '<i class="fas fa-share" style="font-size: 0.8em; margin-left: 3px;"></i> ';
            if (msg.type === 'deleted') return '<em>پیام حذف شده</em>';
            let content = '';
            if (msg.type === 'text') content = msg.content;
            else if (msg.caption) content = `🖼️ ${msg.caption}`;
            else if (msg.type === 'image') return prefix + 'عکس';
            else if (msg.type === 'video') return prefix + 'ویدیو';
            else if (msg.type === 'voice') return prefix + 'پیام صوتی';
            else return prefix + (msg.filename || 'فایل');
            return prefix + $('<div>').html(content).text();
        }

        function getPinnedChats() {
            try { return JSON.parse(localStorage.getItem('pinnedChats_v2') || '[]'); } catch (e) { return []; }
        }
        function setPinnedChats(pinned) {
            localStorage.setItem('pinnedChats_v2', JSON.stringify(pinned));
        }

        function loadChatList() {
            if (chatListContainer.find('.loading').length === 0 && chatListContainer.is(':empty')) {
                 chatListContainer.html('<div class="loading">درحال بارگذاری چت‌ها...</div>');
            }
            $.ajax({
                url: 'chat.php', type: 'GET', data: { action: 'get_chat_list' }, dataType: 'json',
                success: function(response) {
                    if (response.status === 'success' && response.chats) {
                        allChatsCache = response.chats;
                        chatListContainer.empty();
                        if (response.chats.length === 0) {
                             chatListContainer.html('<div class="no-results">چتی یافت نشد. یک کاربر را جستجو کنید.</div>');
                        }
                        
                        const pinnedChats = getPinnedChats();
                        response.chats.sort((a, b) => {
                            const isAPinned = pinnedChats.includes(a.id);
                            const isBPinned = pinnedChats.includes(b.id);
                            if (isAPinned !== isBPinned) return isAPinned ? -1 : 1;
                            return (b.last_message?.timestamp || 0) - (a.last_message?.timestamp || 0);
                        });

                        response.chats.forEach(chat => {
                            const unreadHtml = chat.unread_count > 0 ? `<div class="unread-badge">${chat.unread_count}</div>` : '';
                            const isPinned = pinnedChats.includes(chat.id);
                            const pinIcon = isPinned ? '<i class="fas fa-thumbtack"></i>' : '';
                            
                            const chatItem = $(`
                                <a href="pv.php?chat_id=${encodeURIComponent(chat.id)}" class="chat-item" data-chat-id="${chat.id}" data-type="${chat.type}">
                                    ${renderAvatar(chat)}
                                    <div class="chat-info">
                                        <div class="chat-name">${pinIcon}${sanitizeHTML(chat.name)}</div>
                                        <div class="last-message">${renderLastMessage(chat.last_message)}</div>
                                    </div>
                                    <div class="chat-meta">
                                        ${unreadHtml}
                                        <div class="more-actions-btn"><i class="fas fa-ellipsis-v"></i></div>
                                    </div>
                                </a>`);

                            chatItem.find('.more-actions-btn').on('click', function(e) {
                                e.preventDefault();
                                e.stopPropagation();
                                showChatContextMenu(e, chat.id, isPinned);
                            });
                             
                            chatItem.find('.avatar-container').on('click', function(e) {
                                if(chat.type === 'pv') {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    showProfileModal(chat.id);
                                }
                            });

                            chatListContainer.append(chatItem);
                        });
                    }
                },
                error: () => chatListContainer.html('<div class="no-results">خطا در بارگذاری چت‌ها.</div>')
            });
        }
        
        window.openForwardModal = function(originalMessageId, originalChatId) {
            const modal = $('#forward-modal');
            const list = $('#forward-chat-list');
            const search = $('#forward-search');
            const confirmBtn = $('#confirm-forward-btn');
            
            modal.data('message-id', originalMessageId);
            modal.data('chat-id', originalChatId);
            
            let selectedChats = new Set();
            
            function renderForwardList(query = '') {
                list.empty();
                const filteredChats = allChatsCache.filter(chat => 
                    chat.type !== 'announcements' && 
                    chat.name.toLowerCase().includes(query.toLowerCase())
                );
                
                filteredChats.forEach(chat => {
                    const item = $(`
                        <div class="chat-item" data-chat-id="${chat.id}" style="padding: 8px 10px;">
                            <input type="checkbox" id="fwd-check-${chat.id}" style="margin-left: 10px;" ${selectedChats.has(chat.id) ? 'checked' : ''}>
                            ${renderAvatar(chat)}
                            <div class="chat-info">
                                <div class="chat-name">${sanitizeHTML(chat.name)}</div>
                            </div>
                        </div>
                    `);
                    
                    item.on('click', function(e) {
                        const checkbox = $(this).find('input[type="checkbox"]');
                        if (e.target.type !== 'checkbox') {
                            checkbox.prop('checked', !checkbox.prop('checked'));
                        }
                        if (checkbox.prop('checked')) {
                            selectedChats.add(chat.id);
                        } else {
                            selectedChats.delete(chat.id);
                        }
                        confirmBtn.prop('disabled', selectedChats.size === 0);
                    });
                    
                    list.append(item);
                });
            }
            
            search.val('');
            renderForwardList();
            modal.fadeIn(200).css('display', 'flex');
            
            search.off('input').on('input', function() {
                renderForwardList($(this).val());
            });

            confirmBtn.off('click').on('click', function() {
                if (selectedChats.size === 0) return;
                
                $(this).prop('disabled', true).text('درحال ارسال...');
                
                $.post('chat.php', {
                    action: 'forward_message',
                    csrf_token: csrfToken,
                    message_id: modal.data('message-id'),
                    original_chat_id: modal.data('chat-id'),
                    target_chat_ids: JSON.stringify(Array.from(selectedChats))
                }, (res) => {
                    if (res.status === 'success') {
                        showToast(res.message);
                        modal.fadeOut(200);
                    } else {
                        showToast(res.message || 'خطا در هدایت پیام', true);
                    }
                }, 'json').always(() => {
                    confirmBtn.prop('disabled', false).text('ارسال');
                });
            });

            $('#cancel-forward-btn').off('click').on('click', () => modal.fadeOut(200));
        };

        function showChatContextMenu(e, chatId, isPinned) {
            const menu = $('#chat-list-context-menu');
            const pinAction = isPinned ? 'unpin' : 'pin';
            const pinText = isPinned ? 'برداشتن سنجاق' : 'سنجاق کردن';
            
            let items = `<ul>
                <li data-action="${pinAction}" data-chat-id="${chatId}"><i class="fas fa-thumbtack"></i>${pinText}</li>`;
            if (chatId !== myUsername && chatId !== 'announcements') {
                items += `<li data-action="clear" data-chat-id="${chatId}"><i class="fas fa-eraser"></i>پاک کردن تاریخچه</li>`;
            }
            items += `</ul>`;
            menu.html(items);
            
            menu.css({ display: 'block' });
            const menuWidth = menu.outerWidth(); const menuHeight = menu.outerHeight();
            let left = e.pageX; let top = e.pageY;
            
            const vpWidth = $(window).width();
            const vpHeight = $(window).height();

            if (left + menuWidth > vpWidth - 10) left = vpWidth - menuWidth - 10;
            if (left < 10) left = 10;
            if (top + menuHeight > vpHeight - 10) top = vpHeight - menuHeight - 10;
            if (top < 10) top = 10;

            menu.css({ top: top, left: left });
        }
        
        $(document).on('click', (e) => {
            if (!$(e.target).closest('.context-menu, .more-actions-btn').length) {
                $('#chat-list-context-menu').hide();
            }
        });

        $('#chat-list-context-menu').on('click', 'li', function() {
            const action = $(this).data('action');
            const chatId = $(this).data('chatId');
            
            if (action === 'pin' || action === 'unpin') {
                let pinned = getPinnedChats();
                if (action === 'pin') {
                    if (!pinned.includes(chatId)) pinned.push(chatId);
                } else {
                    pinned = pinned.filter(id => id !== chatId);
                }
                setPinnedChats(pinned);
                loadChatList();
            } else if (action === 'clear') {
                if(confirm('آیا از پاک کردن تمام پیام‌های این چت مطمئن هستید؟ این عمل غیرقابل بازگشت است.')) {
                    $.post('chat.php', { action: 'clear_history', chat_id: chatId, csrf_token: csrfToken }, (res) => {
                        if (res.status === 'success') {
                            showToast('تاریخچه چت پاک شد.');
                            loadChatList();
                        } else {
                            showToast('خطا در پاک کردن تاریخچه.', true);
                        }
                    }, 'json');
                }
            }
            $('#chat-list-context-menu').hide();
        });

        function performSearch(query) {
             if (query.length < 2) { searchResultsContainer.empty().hide(); chatListContainer.show(); return; }
             searchResultsContainer.html('<div class="loading">درحال جستجو...</div>').show(); chatListContainer.hide();
             $.ajax({
                url: 'chat.php', type: 'GET', data: { action: 'search_users', query: query }, dataType: 'json',
                success: function(results) {
                    searchResultsContainer.empty();
                    if (results.length === 0) { searchResultsContainer.html('<div class="no-results">کاربری یافت نشد.</div>'); return; }
                    results.forEach(user => {
                        const userItem = $(`
                            <a href="pv.php?chat_id=${encodeURIComponent(user.id)}" class="chat-item" data-user-id="${user.id}">
                                ${renderAvatar(user)}
                                <div class="chat-info">
                                    <div class="chat-name">${sanitizeHTML(user.name)}</div>
                                    <div class="last-message">@${user.id}</div>
                                </div>
                            </a>`);
                        searchResultsContainer.append(userItem);
                    });
                },
                error: () => searchResultsContainer.html('<div class="no-results">خطا در جستجو.</div>')
            });
        }

        searchInput.on('input', function() { clearTimeout(searchTimeout); const query = $(this).val(); searchTimeout = setTimeout(() => { performSearch(query); }, 300); });

        function showProfileModal(userId) {
            $.ajax({
                url: 'chat.php', type: 'GET', data: { action: 'get_user_details', user_id: userId }, dataType: 'json',
                success: function(res) {
                    if(res.status === 'success') {
                        const user = res.user;
                        const contrastColor = getContrastYIQ(user.color);
                        const avatarHtml = user.avatar ? `<img src="${user.avatar}?t=${Date.now()}" class="profile-modal-avatar">` : `<div class="profile-modal-avatar" style="display:flex; align-items:center; justify-content:center; background:${user.color || '#888'}; font-size: 3rem; color: ${contrastColor};">${getInitials(user.name)}</div>`;
                        const bioHtml = user.bio ? sanitizeHTML(user.bio).replace(/\n/g, '<br>') : 'بیوگرافی ثبت نشده.';
                        
                        $('#profile-modal-avatar-container').html(avatarHtml);
                        $('#profile-modal-name').html(sanitizeHTML(user.name));
                        $('#profile-modal-username').text(`@${user.username}`);
                        $('#profile-modal-bio').html(bioHtml);
                        $('#profile-modal-last-seen').text(user.last_active_formatted);
                        $('#profile-modal-link').text(`.../${user.link}`).attr('href', user.link);
                        
                        let statusHtml = '';
                        if (user.profile_status) {
                            if(user.profile_status.emoji) statusHtml += `<span>${user.profile_status.emoji}</span>`;
                            if(user.profile_status.text) statusHtml += `<span>${sanitizeHTML(user.profile_status.text)}</span>`;
                        }
                        $('#profile-modal-status').html(statusHtml);
                        
                        const msgBtn = $('#profile-modal-message-btn');
                        if (user.username === myUsername) {
                            msgBtn.hide();
                        } else {
                            msgBtn.attr('href', `pv.php?chat_id=${encodeURIComponent(user.username)}`).show();
                        }
                        
                        $('#profile-modal-content').find('.profile-modal-header').css('background-color', user.color || 'var(--primary-color)');
                        $('#profile-modal').fadeIn(200).css('display', 'flex');
                    }
                }
            });
        }
        $(document).on('click', '#close-profile-modal', () => $('#profile-modal').fadeOut(200));
        $('#profile-modal').on('click', function(e) { if (e.target === this) $(this).fadeOut(200); });

        function loadUserSettings() {
             $.ajax({
                url: 'chat.php', type: 'GET', data: { action: 'get_user_details' }, dataType: 'json',
                success: function(res) {
                    if (res.status === 'success') {
                        const user = res.user;
                        $('#name-input').val(user.name);
                        $('#username-input').val(user.username);
                        $('#bio-input').val(user.bio);
                        const avatarSrc = user.avatar ? `${user.avatar}?t=${Date.now()}` : 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
                        $('#avatar-preview').attr('src', avatarSrc);
                        $('#last-seen-select').val(user.privacy.last_seen);
                        
                        const theme = user.settings?.theme || 'dark';
                        $('#theme-toggle-checkbox').prop('checked', theme === 'dark');
                        $('#theme-label').text(theme === 'dark' ? 'تاریک' : 'روشن');
                        applyTheme(theme);
                        
                        if (user.settings && user.settings.primary_color) {
                           updateThemeColor(user.settings.primary_color, false);
                        }
                        
                        if (user.profile_status) {
                            $('#status-emoji-input').val(user.profile_status.emoji || '');
                            $('#status-text-input').val(user.profile_status.text || '');
                            if (user.profile_status.expires_at === 0) {
                                $('#status-duration-select').val('never');
                            }
                        }
                        
                        if (user.status['2fa_enabled']) {
                            $('#2fa-status-enabled').show();
                            $('#2fa-status-disabled').hide();
                        } else {
                            $('#2fa-status-enabled').hide();
                            $('#2fa-status-disabled').show();
                        }
                    }
                }
             });
        }

        $('#avatar-input').on('change', function() {
            if (this.files && this.files[0]) {
                if (this.files[0].size > 5 * 1024 * 1024) { showToast('حجم فایل نباید بیشتر از ۵ مگابایت باشد.', true); this.value = ''; return; }
                const reader = new FileReader();
                reader.onload = e => $('#avatar-preview').attr('src', e.target.result);
                reader.readAsDataURL(this.files[0]);
            }
        });

        $('form').on('submit', function() {
            const btn = $(this).find('.btn[type="submit"]');
            btn.prop('disabled', true);
            btn.find('.btn-text').text('درحال پردازش...');
        });

        $('#profile-form').on('submit', function(e) {
            e.preventDefault();
            const btn = $(this).find('.btn[type="submit"]');
            const formData = new FormData(this);
            formData.append('action', 'update_profile');
            formData.append('csrf_token', csrfToken);
            if ($('#avatar-input')[0].files[0]) formData.append('avatar', $('#avatar-input')[0].files[0]);
            $.ajax({
                url: 'chat.php', type: 'POST', data: formData, processData: false, contentType: false, dataType: 'json',
                success: (res) => { 
                    if(res.status === 'success') {
                        showToast('اطلاعات با موفقیت ذخیره شد.');
                        if (res.user.username !== myUsername) setTimeout(() => window.location.reload(), 1000);
                    } else { showToast('خطا: ' + res.message, true); }
                },
                error: (xhr) => showToast('خطا در ارتباط با سرور: ' + (xhr.responseJSON?.message || 'خطای نامشخص'), true),
                complete: () => { btn.prop('disabled', false); btn.find('.btn-text').text('ذخیره اطلاعات'); }
            });
        });

        $('#password-form').on('submit', function(e){
            e.preventDefault();
            const btn = $(this).find('.btn[type="submit"]');
            if ($('#new-password').val().length < 6) { showToast('رمز عبور جدید باید حداقل ۶ کاراکتر باشد.', true); return; }
            const formData = new FormData(this);
            formData.append('action', 'update_password');
            formData.append('csrf_token', csrfToken);
            $.ajax({
                url: 'chat.php', type: 'POST', data: formData, processData: false, contentType: false, dataType: 'json',
                success: (res) => { if(res.status === 'success') { showToast('رمز عبور با موفقیت تغییر کرد.'); this.reset(); } else { showToast('خطا: ' + res.message, true); } },
                error: (xhr) => showToast('خطا: ' + (xhr.responseJSON?.message || 'خطای نامشخص'), true),
                complete: () => { btn.prop('disabled', false); btn.find('.btn-text').text('تغییر رمز'); }
            });
        });
        
        const colorSwatchesContainer = $('#color-swatches-container');
        const primaryColorInput = $('#primary-color-input');
        const presetColors = [
            'hsl(158, 100%, 44%)', 'hsl(204, 86%, 53%)', 'hsl(283, 60%, 53%)', 
            'hsl(27, 87%, 60%)', 'hsl(348, 83%, 60%)', 'hsl(171, 66%, 44%)', 
            'hsl(45, 100%, 51%)', 'hsl(145, 63%, 49%)'
        ];
        let colorChangeTimeout;

        function updateThemeColor(color, save = false) {
            let h, s, l;
            if (color.startsWith('hsl')) {
                let parts = color.match(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/);
                if (parts) {
                    h = parts[1]; s = parts[2] + '%'; l = parts[3] + '%';
                }
            }
            if (!h) { h = 158; s = '100%'; l = '44%'; color = 'hsl(158, 100%, 44%)'; }

            document.documentElement.style.setProperty('--primary-hue', h);
            document.documentElement.style.setProperty('--primary-saturation', s);
            document.documentElement.style.setProperty('--primary-lightness', l);
            document.documentElement.style.setProperty('--text-on-primary', getContrastYIQ(color));
            
            primaryColorInput.val(color);
            colorSwatchesContainer.find('.color-swatch').removeClass('active');
            colorSwatchesContainer.find(`.color-swatch[data-color="${color}"]`).addClass('active');
            
            if (save) {
                clearTimeout(colorChangeTimeout);
                colorChangeTimeout = setTimeout(() => {
                    $.post('chat.php', { 
                        action: 'update_theme_settings', 
                        primary_color: color, 
                        csrf_token: csrfToken 
                    }, (res) => { if (res.status === 'success') showToast('رنگ تم ذخیره شد.'); }, 'json');
                }, 500);
            }
        }
        presetColors.forEach(color => colorSwatchesContainer.append($(`<div class="color-swatch" style="background-color: ${color};" data-color="${color}"></div>`)));
        colorSwatchesContainer.on('click', '.color-swatch', function() { updateThemeColor($(this).data('color'), true); });
        
        function applyTheme(theme, save = false) {
            document.body.setAttribute('data-theme', theme);
            $('#theme-label').text(theme === 'dark' ? 'تاریک' : 'روشن');
            if (save) {
                 $.post('chat.php', { 
                    action: 'update_theme_settings', 
                    theme: theme, 
                    csrf_token: csrfToken 
                }, (res) => { if (res.status === 'success') showToast('تم ذخیره شد.'); }, 'json');
            }
        }

        $('#theme-toggle-checkbox').on('change', function() {
            const theme = $(this).is(':checked') ? 'dark' : 'light';
            applyTheme(theme, true);
        });

        $('#last-seen-select').on('change', function() {
            $.post('chat.php', { action: 'update_privacy_settings', last_seen: $(this).val(), csrf_token: csrfToken }, (res) => { if(res.status === 'success') showToast('تنظیمات حریم خصوصی ذخیره شد.'); }, 'json');
        });
        
        $('#profile-status-form').on('submit', function(e) {
            e.preventDefault();
            const btn = $(this).find('.btn[type="submit"]');
            const formData = new FormData(this);
            formData.append('action', 'update_profile_status');
            formData.append('csrf_token', csrfToken);
            $.ajax({
                url: 'chat.php', type: 'POST', data: formData, processData: false, contentType: false, dataType: 'json',
                success: (res) => { 
                    if(res.status === 'success') showToast('وضعیت پروفایل به‌روز شد.');
                    else showToast(res.message || 'خطا در ثبت وضعیت', true);
                },
                error: (xhr) => showToast('خطا: ' + (xhr.responseJSON?.message || 'خطای نامشخص'), true),
                complete: () => { btn.prop('disabled', false); btn.find('.btn-text').text('ثبت وضعیت'); }
            });
        });
        
        const emojis = ['😊', '😂', '😍', '🤔', '😴', '👋', '🎉', '🚀', '💻', '☕', '🍔', '🚫'];
        const picker = $('#status-emoji-picker');
        picker.html('<div class="emoji-grid">' + emojis.map(e => `<span>${e}</span>`).join('') + '</div>');
        $('#status-emoji-input').on('click', () => picker.fadeIn(100));
        picker.on('click', 'span', function() {
            $('#status-emoji-input').val($(this).text());
            picker.fadeOut(100);
        });
        $(document).on('click', (e) => { if (!$(e.target).closest('#status-emoji-input, #status-emoji-picker').length) picker.hide(); });

        $('#enable-2fa-btn').on('click', function() {
            const btn = $(this);
            btn.prop('disabled', true).find('.btn-text').text('درحال فعال‌سازی...');
            $.post('chat.php', { action: 'setup_2fa', csrf_token: csrfToken }, (res) => {
                if (res.status === 'success') {
                    $('#2fa-status-disabled').hide();
                    const list = $('#2fa-backup-codes-list');
                    list.empty();
                    res.backup_codes.forEach(code => list.append(`<div>${code}</div>`));
                    $('#2fa-backup-codes-container').show();
                    showToast(res.message);
                } else {
                    showToast(res.message || 'خطا در فعال‌سازی 2FA', true);
                }
            }, 'json').always(() => {
                btn.prop('disabled', false).find('.btn-text').text('فعال کردن 2FA');
            });
        });
        
        $('#close-2fa-codes').on('click', function() {
            $('#2fa-backup-codes-container').hide();
            $('#2fa-status-enabled').show();
        });

        $('#disable-2fa-form').on('submit', function(e) {
            e.preventDefault();
            const btn = $(this).find('.btn[type="submit"]');
            const formData = new FormData(this);
            formData.append('action', 'disable_2fa');
            formData.append('csrf_token', csrfToken);
            $.ajax({
                url: 'chat.php', type: 'POST', data: formData, processData: false, contentType: false, dataType: 'json',
                success: (res) => { 
                    if(res.status === 'success') {
                        showToast(res.message);
                        $('#2fa-status-enabled').hide();
                        $('#2fa-status-disabled').show();
                        this.reset();
                    } else { 
                        showToast('خطا: ' + res.message, true); 
                    } 
                },
                error: (xhr) => showToast('خطا: ' + (xhr.responseJSON?.message || 'خطای نامشخص'), true),
                complete: () => { btn.prop('disabled', false); btn.find('.btn-text').text('غیرفعال کردن 2FA'); }
            });
        });

        updateThemeColor($(':root').css('--primary-color'));
        loadChatList();
        setInterval(loadChatList, 15000);
        
        if ($(window).width() >= 768) {
            $('.back-from-settings').hide();
        }
    });
    </script>
</body>
</html>