<?php
session_start();

if (!file_exists('config.php')) {
    header("Location: install.php");
    exit;
}
require 'config.php';

$user_id = $_SESSION['user_id'] ?? null;

// Routing
$view = $_GET['view'] ?? 'home';
if (!$user_id && !in_array($view, ['login', 'register'])) {
    header("Location: ?view=login");
    exit;
}

// Redirect to profile.php if view is profile
if ($view == 'profile') {
    $id = $_GET['id'] ?? $user_id;
    header("Location: profile.php?id=$id");
    exit;
}

// Redirect to settings.php if view is settings
if ($view == 'settings') {
    header("Location: settings.php");
    exit;
}

// Global user info
$curr = null;
if ($user_id) {
    $stmt = $pdo->prepare("SELECT id, username, full_name, avatar, bio FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $curr = $stmt->fetch();
}

// --- Backend Logic ---

$error = '';
$success = '';

// Login
if ($view == 'login' && $_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        header("Location: index.php");
        exit;
    } else {
        $error = "Невірне ім'я користувача або пароль";
    }
}

// Register
if ($view == 'register' && $_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $fullname = $_POST['fullname'];
    
    try {
        $stmt = $pdo->prepare("INSERT INTO users (username, password, full_name) VALUES (?, ?, ?)");
        $stmt->execute([$username, $password, $fullname]);
        $_SESSION['user_id'] = $pdo->lastInsertId();
        header("Location: index.php");
        exit;
    } catch (PDOException $e) {
        $error = "Користувач вже існує";
    }
}

// Fetch Stories (Active ones)
$stories = [];
if ($view == 'home' && $user_id) {
    $stmt = $pdo->query("
        SELECT s.*, u.username, u.avatar 
        FROM stories s 
        JOIN users u ON s.user_id = u.id 
        WHERE s.expires_at > NOW()
        ORDER BY s.created_at ASC
    ");
    $stories = $stmt->fetchAll();
}

// Fetch Feed (Home) - Posts only (type='post')
$posts = [];
if ($view == 'home' && $user_id) {
    $stmt = $pdo->query("
        SELECT p.*, u.username, u.avatar, 
        (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
        (SELECT COUNT(*) FROM likes WHERE post_id = p.id AND user_id = $user_id) as cur_user_liked
        FROM posts p 
        JOIN users u ON p.user_id = u.id 
        WHERE p.type = 'post'
        ORDER BY p.created_at DESC
    ");
    $posts = $stmt->fetchAll();
}

// Fetch Reels (Reels view)
$reels = [];
if ($view == 'reels' && $user_id) {
    $stmt = $pdo->query("
        SELECT p.*, u.username, u.avatar, 
        (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
        (SELECT COUNT(*) FROM likes WHERE post_id = p.id AND user_id = $user_id) as cur_user_liked
        FROM posts p 
        JOIN users u ON p.user_id = u.id 
        WHERE p.type = 'reel' OR p.media_type = 'video'
        ORDER BY p.created_at DESC
    ");
    $reels = $stmt->fetchAll();
}

// Fetch Explore
$explore_posts = [];
if ($view == 'explore' && $user_id) {
    $stmt = $pdo->query("
        SELECT p.*, u.username, u.avatar, 
        (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
        (SELECT COUNT(*) FROM likes WHERE post_id = p.id AND user_id = $user_id) as cur_user_liked,
        (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comment_count
        FROM posts p 
        JOIN users u ON p.user_id = u.id 
        ORDER BY RAND() LIMIT 21
    ");
    $explore_posts = $stmt->fetchAll();
}

// Fetch Profile
$profile_user = null;
$profile_posts = [];
if ($view == 'profile' && $user_id) {
    $target_id = $_GET['id'] ?? $user_id;
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$target_id]);
    $profile_user = $stmt->fetch();
    
    $stmt = $pdo->prepare("SELECT * FROM posts WHERE user_id = ? ORDER BY created_at DESC");
    $stmt->execute([$target_id]);
    $profile_posts = $stmt->fetchAll();
}

// Fetch Saved Posts
$saved_posts = [];
if ($view == 'saved' && $user_id) {
    $stmt = $pdo->prepare("
        SELECT p.*, u.username, u.avatar,
        (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
        (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comment_count
        FROM saved_posts sp
        JOIN posts p ON sp.post_id = p.id
        JOIN users u ON p.user_id = u.id
        WHERE sp.user_id = ?
        ORDER BY sp.created_at DESC
    ");
    $stmt->execute([$user_id]);
    $saved_posts = $stmt->fetchAll();
}

// Fetch Direct Messages (Conversations)
$conversations = [];
if ($view == 'direct' && $user_id) {
    $stmt = $pdo->prepare("
        SELECT c.*, 
               u.username, u.avatar, u.full_name,
               (SELECT message FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_msg,
               (SELECT created_at FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_msg_time
        FROM conversations c
        JOIN users u ON (u.id = c.user1_id OR u.id = c.user2_id) AND u.id != ?
        WHERE c.user1_id = ? OR c.user2_id = ?
        ORDER BY last_msg_time DESC
    ");
    $stmt->execute([$user_id, $user_id, $user_id]);
    $conversations = $stmt->fetchAll();
}

?>
<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>UAgram</title>
    <link rel="stylesheet" href="assets/style.css">
    <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>📱</text></svg>">
</head>
<body>

    <?php if (!$user_id): ?>
        <!-- Auth Views (unchanged from previous step, but included for context if needed, handled by existing code structure) -->
        <div class="auth-container">
            <div class="auth-box">
                <h1 class="logo">UAgram</h1>
                <?php if ($error): ?>
                    <div style="color: red; margin-bottom: 10px;"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <?php if ($view == 'login'): ?>
                    <form class="auth-form" method="POST">
                        <input type="text" name="username" placeholder="Ім'я користувача" required>
                        <input type="password" name="password" placeholder="Пароль" required>
                        <button type="submit">Увійти</button>
                    </form>
                    <div class="auth-switch">
                        Не маєте акаунту? <a href="?view=register">Зареєструватися</a>
                    </div>
                <?php else: ?>
                    <form class="auth-form" method="POST">
                        <input type="text" name="username" placeholder="Ім'я користувача" required>
                        <input type="text" name="fullname" placeholder="Повне ім'я" required>
                        <input type="password" name="password" placeholder="Пароль" required>
                        <button type="submit">Зареєструватися</button>
                    </form>
                    <div class="auth-switch">
                        Вже є акаунт? <a href="?view=login">Увійти</a>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    <?php else: ?>
        <!-- App View -->
        
        <!-- Mobile Header -->
        <header class="app-header">
            <div class="logo">UAgram</div>
            <div class="header-actions">
                <a href="?view=logout"><svg aria-label="Вийти"  fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><path d="M16 11V7a1 1 0 0 0-1-1h-4a1 1 0 0 0 0 2h3v10h-3a1 1 0 0 0 0 2h4a1 1 0 0 0 1-1v-4h3a1 1 0 0 0 0-2h-3zm-1 8h-4a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3h4a3 3 0 0 1 3 3v2h-2V8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-2h2v2a3 3 0 0 1-3 3z"/></svg></a>
            </div>
        </header>

        <!-- Toast Container -->
        <div id="toast-container" style="position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); z-index: 9999; display: flex; flex-direction: column; align-items: center; gap: 10px;"></div>

        <div class="main-wrapper">
            
            <!-- LEFT SIDEBAR (Desktop) -->
            <?php include 'sidebar.php'; ?>

            <!-- SEARCH PANEL -->
            <div id="search-panel" class="notifications-panel">
                <div class="panel-header">
                    <h2>Пошук</h2>
                </div>
                <div class="search-input-header" style="padding: 0 16px 20px 16px; border-bottom: 1px solid var(--border-color);">
                    <div class="search-field" style="background: #262626; border-radius: 8px; padding: 0 12px; height: 40px; display: flex; align-items: center;">
                        <input type="text" id="sidebar-search-input" placeholder="Пошук" style="background: none; border: none; color: white; flex-grow: 1; height: 100%; outline: none;" oninput="handleSidebarSearch(this.value)">
                        <span id="search-clear-btn" style="color: #c7c7c7; cursor: pointer; font-size: 12px; background:#c7c7c7; color:black; border-radius:50%; width:16px; height:16px; display:none; align-items:center; justify-content:center;" onclick="clearSidebarSearch()">✕</span>
                    </div>
                </div>
                <div class="panel-scroll-area">
                    <div id="search-recent-section">
                        <div class="recent-header" style="padding: 12px 16px; display: flex; justify-content: space-between; align-items: center; margin-top: 10px;">
                            <span style="font-weight: 600; font-size: 16px;">Недавні</span>
                            <span style="color: var(--button-blue); font-size: 14px; font-weight: 600; cursor: pointer;">Очистити все</span>
                        </div>
                        <div id="search-results-list">
                             <!-- Example Recent Search -->
                             <div class="notification-item" style="padding: 8px 16px;">
                                 <img src="assets/default_avatar.svg" class="notif-avatar" style="width: 44px; height: 44px;">
                                 <div class="notif-text" style="display: flex; flex-direction: column;">
                                     <span class="notif-username" style="font-size: 14px;">stasia512023</span>
                                     <span style="font-size: 14px; color: var(--text-secondary);">настя • Відстежування</span>
                                 </div>
                                 <div class="search-remove-btn" style="color: var(--text-secondary); cursor: pointer; font-size: 14px; margin-left: auto;">✕</div>
                             </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- NOTIFICATIONS PANEL -->
            <div id="notifications-panel" class="notifications-panel">
                <div class="notifications-header">
                    <h2>Сповіщення</h2>
                    <span style="font-size:14px; color:var(--text-secondary);">Фільтрувати</span>
                </div>
                <div class="notifications-scroll-area">
                    <div class="notif-section-title">Цього місяця</div>
                    
                    <div class="notif-item">
                        <img src="assets/default_avatar.svg" class="notif-avatar">
                        <div class="notif-text">
                            <span class="notif-username">stasia512023</span> вподобала вашу розповідь. <span class="notif-time">8 тиж.</span>
                        </div>
                        <div class="notif-media">
                            <img src="assets/default_avatar.svg">
                        </div>
                    </div>

                    <div class="notif-item">
                        <img src="assets/default_avatar.svg" class="notif-avatar">
                        <div class="notif-text">
                            <span class="notif-username">user_123</span> почав(-ла) стежити за вами. <span class="notif-time">1 дн.</span>
                        </div>
                         <button class="btn-profile" style="font-size:12px; padding: 5px 14px; margin-left:auto;">Стежити</button>
                    </div>

                    <div class="notif-item">
                        <img src="assets/default_avatar.svg" class="notif-avatar">
                        <div class="notif-text">
                            <span class="notif-username">alex_dev</span> вподобав(-ла) ваше відео Reels. <span class="notif-time">2 дн.</span>
                        </div>
                         <div class="notif-media">
                           <img src="assets/default_avatar.svg">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Main Feed/Content Center -->
            <main class="feed-container <?php echo $view=='settings'?'settings-view':''; ?> <?php echo $view=='reels'?'reels-view':''; ?> <?php echo $view=='direct'?'messenger-view':''; ?>">
            
            <?php if ($view == 'home'): ?>
                <script>
                    window.storiesData = <?php echo json_encode($stories); ?>;
                </script>
                <!-- STORIES BAR -->
                <div class="stories-bar">
                    <div class="story-item" onclick="openModal('story')">
                        <div class="story-ring add-story">
                            <span>+</span>
                        </div>
                        <span class="story-username">Ваша історія</span>
                    </div>
                    <?php foreach ($stories as $index => $story): ?>
                        <div class="story-item" onclick="openStoryViewer(<?php echo $index; ?>)">
                            <div class="story-ring active">
                                <img src="<?php echo !empty($story['avatar']) ? htmlspecialchars($story['avatar']) : 'assets/default_avatar.svg'; ?>" alt="">
                            </div>
                            <span class="story-username"><?php echo htmlspecialchars($story['username']); ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- FEED -->
                <?php if (empty($posts)): ?>
                    <div style="text-align: center; padding: 40px; color: var(--text-secondary);">
                        Поки що немає постів.
                    </div>
                <?php endif; ?>
                
                <?php foreach ($posts as $post): ?>
                    <article class="post-card" data-id="<?php echo $post['id']; ?>">
                        <div class="post-header">
                            <img src="<?php echo !empty($post['avatar']) ? htmlspecialchars($post['avatar']) : 'assets/default_avatar.svg'; ?>" class="user-avatar" alt="">
                            <a href="?view=profile&id=<?php echo $post['user_id']; ?>" class="username">
                                <?php echo htmlspecialchars($post['username']); ?>
                            </a>
                            <span style="color:var(--text-secondary);margin:0 4px;">•</span>
                            <span style="color:var(--text-secondary);font-size:12px;"><?php 
                                $diff = time() - strtotime($post['created_at']);
                                if ($diff < 3600) echo floor($diff/60).'хв';
                                elseif ($diff < 86400) echo floor($diff/3600).'год';
                                else echo floor($diff/86400).'д';
                            ?></span>

                            <button class="more-btn" onclick="openPostOptions(<?php echo $post['id']; ?>, <?php echo $post['user_id']; ?>)">
                                <svg aria-label="Більше" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><circle cx="12" cy="12" r="1.5"></circle><circle cx="6" cy="12" r="1.5"></circle><circle cx="18" cy="12" r="1.5"></circle></svg>
                            </button>
                        </div>
                        
                        <?php if ($post['media_type'] === 'video'): ?>
                            <video src="<?php echo htmlspecialchars($post['image_url']); ?>" class="post-image" controls muted loop playsinline></video>
                        <?php else: ?>
                            <img src="<?php echo htmlspecialchars($post['image_url']); ?>" class="post-image" alt="Post content">
                        <?php endif; ?>
                        
                        <div class="post-actions">
                            <button class="action-btn like-btn <?php echo $post['cur_user_liked'] ? 'liked' : ''; ?>" onclick="toggleLike(<?php echo $post['id']; ?>)">
                                <svg viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="<?php echo $post['cur_user_liked'] ? '0' : '2'; ?>">
                                    <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                                </svg>
                            </button>
                            <button class="action-btn comment-btn">
                                <svg aria-label="Коментувати" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><path d="M20.656 17.008a9.993 9.993 0 1 0-3.59 3.615L22 22Z" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="2"></path></svg>
                            </button>
                            <button class="action-btn share-btn">
                                <svg aria-label="Поділитися" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><line fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="2" x1="22" x2="9.218" y1="3" y2="10.083"></line><polygon fill="none" points="11.698 20.334 22 3.001 2 3.001 9.218 10.084 11.698 20.334" stroke="currentColor" stroke-linejoin="round" stroke-width="2"></polygon></svg>
                            </button>
                            
                            <?php
                                // Check if post is saved
                                $stmt = $pdo->prepare("SELECT * FROM saved_posts WHERE user_id = ? AND post_id = ?");
                                $stmt->execute([$user_id, $post['id']]);
                                $is_saved = $stmt->fetch() ? true : false;
                            ?>
                            <button class="action-btn save-btn" onclick="savePost(<?php echo $post['id']; ?>)" style="margin-left: auto;">
                                <?php if ($is_saved): ?>
                                    <svg aria-label="Видалити" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><path d="M20 21V5a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v16l8-4.572L20 21Z"></path></svg>
                                <?php else: ?>
                                    <svg aria-label="Зберегти" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><polygon fill="none" points="20 21 12 13.44 4 21 4 3 20 3 20 21" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></polygon></svg>
                                <?php endif; ?>
                            </button>
                        </div>
                        
                        <div class="post-likes">
                            <span class="like-count"><?php echo $post['like_count']; ?></span> вподобань
                        </div>
                        
                        <div class="post-caption">
                            <span class="username"><?php echo htmlspecialchars($post['username']); ?></span>
                            <?php echo htmlspecialchars($post['caption']); ?>
                        </div>

                        <!-- Display Comments -->
                        <?php
                            $stmt = $pdo->prepare("
                                SELECT c.*, u.username, u.avatar 
                                FROM comments c 
                                JOIN users u ON c.user_id = u.id 
                                WHERE c.post_id = ? 
                                ORDER BY c.created_at DESC 
                                LIMIT 3
                            ");
                            $stmt->execute([$post['id']]);
                            $comments = $stmt->fetchAll();
                            
                            if (!empty($comments)):
                        ?>
                        <div class="post-comments-preview" style="padding: 4px 4px 8px;">
                            <?php foreach ($comments as $comment): ?>
                                <div class="comment-preview" style="margin-bottom: 8px; display: flex; justify-content: space-between; align-items: start;" data-comment-id="<?php echo $comment['id']; ?>">
                                    <div style="flex: 1;">
                                        <span class="username" style="font-weight: 600; margin-right: 6px;"><?php echo htmlspecialchars($comment['username']); ?></span>
                                        <span class="comment-text" style="font-size: 14px;"><?php echo htmlspecialchars($comment['comment_text']); ?></span>
                                        
                                        <!-- Comment Actions -->
                                        <div class="comment-actions" style="margin-top: 4px; display: flex; gap: 12px;">
                                            <button class="comment-action-btn" onclick="replyToComment('<?php echo htmlspecialchars($comment['username']); ?>', <?php echo $post['id']; ?>)" style="background: none; border: none; color: var(--text-secondary); font-size: 12px; cursor: pointer; padding: 0;">
                                                Відповісти
                                            </button>
                                            <?php if ($comment['user_id'] == $user_id): ?>
                                                <button class="comment-action-btn" onclick="deleteComment(<?php echo $comment['id']; ?>, <?php echo $post['id']; ?>)" style="background: none; border: none; color: var(--text-secondary); font-size: 12px; cursor: pointer; padding: 0;">
                                                    Видалити
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Like button for comment -->
                                    <button class="comment-like-btn" onclick="likeComment(<?php echo $comment['id']; ?>)" style="background: none; border: none; cursor: pointer; padding: 4px; margin-left: 8px;">
                                        <svg fill="none" height="12" viewBox="0 0 24 24" width="12" stroke="currentColor" stroke-width="2">
                                            <path d="M16.792 3.904A4.989 4.989 0 0 1 21.5 9.122c0 3.072-2.652 4.959-5.197 7.222-2.512 2.243-3.865 3.469-4.303 3.752-.477-.309-2.143-1.823-4.303-3.752C5.141 14.072 2.5 12.167 2.5 9.122a4.989 4.989 0 0 1 4.708-5.218 4.21 4.21 0 0 1 3.675 1.941c.84 1.175.98 1.763 1.12 1.763s.278-.588 1.11-1.766a4.17 4.17 0 0 1 3.679-1.938m0-2a6.04 6.04 0 0 0-4.797 2.127 6.052 6.052 0 0 0-4.787-2.127A6.985 6.985 0 0 0 .5 9.122c0 3.61 2.55 5.827 5.015 7.97.283.246.569.494.853.747l1.027.918a44.998 44.998 0 0 0 3.518 3.018 2 2 0 0 0 2.174 0 45.263 45.263 0 0 0 3.626-3.115l.922-.824c.293-.26.59-.519.885-.774 2.334-2.025 4.98-4.32 4.98-7.94a6.985 6.985 0 0 0-6.708-7.218Z"></path>
                                        </svg>
                                    </button>
                                </div>
                            <?php endforeach; ?>
                            
                            <?php
                                // Check if there are more comments
                                $stmt = $pdo->prepare("SELECT COUNT(*) FROM comments WHERE post_id = ?");
                                $stmt->execute([$post['id']]);
                                $totalComments = $stmt->fetchColumn();
                                
                                if ($totalComments > 3):
                            ?>
                                <button class="view-all-comments" onclick="openPostModal(<?php echo $post['id']; ?>)" style="background: none; border: none; color: var(--text-secondary); font-size: 14px; cursor: pointer; padding: 4px 0;">
                                    Переглянути всі коментарі (<?php echo $totalComments; ?>)
                                </button>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>

                        <!-- Add Comment Area -->
                        <div class="post-comment-input-area">
                            <svg aria-label="Смайл" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><path d="M15.83 10.997a1.001 1.001 0 1 0 1.002 1.003 1.001 1.001 0 0 0-1.002-1.003ZM12 2a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2Zm0 18a8 8 0 1 1 8-8 8.009 8.009 0 0 1-8 8ZM8.17 10.997a1.001 1.001 0 1 0 1.002 1.003 1.001 1.001 0 0 0-1.002-1.003Zm-1.838 5.71a.998.998 0 0 0 1.332 1.503 5.968 5.968 0 0 1 8.672 0 .999.999 0 0 0 1.332-1.5 7.965 7.965 0 0 0-11.335-.003Z"></path></svg>
                            <input type="text" class="card-comment-input" placeholder="Додайте коментар..." data-post-id="<?php echo $post['id']; ?>" onkeydown="if(event.key === 'Enter') postCardComment(<?php echo $post['id']; ?>)">
                            <button class="card-post-btn" onclick="postCardComment(<?php echo $post['id']; ?>)">Опублікувати</button>
                        </div>
                    </article>
                <?php endforeach; ?>

            <?php elseif ($view == 'reels'): ?>
                <!-- REELS FEED -->
                <div class="reels-nav-tabs">
                    <span class="active">Для вас</span>
                    <span>Ви стежите</span>
                </div>

                <div class="reels-side-nav">
                    <div class="reel-nav-arrow" onclick="scrollReels('up')">
                        <svg fill="currentColor" height="16" viewBox="0 0 24 24" width="16"><path d="M12 4.106L20.894 13l1.412-1.414L12 1.278 1.694 11.586 3.106 13 12 4.106zM12 14.106L20.894 23l1.412-1.414L12 11.278 1.694 21.586 3.106 23 12 14.106z"></path></svg>
                    </div>
                    <div class="reel-nav-arrow" onclick="scrollReels('down')">
                        <svg fill="currentColor" height="16" viewBox="0 0 24 24" width="16"><path d="M12 19.894L3.106 11l-1.412 1.414L12 22.722l10.306-10.306-1.412-1.414L12 19.894zM12 9.894L3.106 1l-1.412 1.414L12 12.722 22.306 2.416l-1.412-1.414L12 9.894z"></path></svg>
                    </div>
                </div>

                <div class="reels-container" id="reels-container">
                    <?php foreach ($reels as $reel): ?>
                        <div class="reel-wrapper" data-id="<?php echo $reel['id']; ?>">
                            <div class="reel-item">
                                <video src="<?php echo htmlspecialchars($reel['image_url']); ?>" loop autoplay muted></video>
                                
                                <div class="reel-mute-btn" onclick="toggleReelMute(this)">
                                    <svg fill="white" height="12" viewBox="0 0 24 24" width="12" class="mute-icon"><path d="M16.636 7.028a1.5 1.5 0 1 0-2.395 1.807 3.5 3.5 0 0 1 0 4.33 1.5 1.5 0 1 0 2.395 1.807 6.5 6.5 0 0 0 0-7.944Z"></path><path d="M12.157 2.189a1.5 1.5 0 0 0-1.941.039L5.47 6.5H2.5A1.5 1.5 0 0 0 1 8v8a1.5 1.5 0 0 0 1.5 1.5h2.97l4.746 4.272a1.5 1.5 0 0 0 1.941.039c.562-.437.843-1.127.843-1.811V4c0-.684-.281-1.374-.843-1.811Z"></path></svg>
                                </div>

                                <div class="reel-overlay">
                                    <div class="reel-user">
                                        <img src="<?php echo !empty($reel['avatar']) ? htmlspecialchars($reel['avatar']) : 'assets/default_avatar.svg'; ?>" class="user-avatar">
                                        <span class="reel-username"><?php echo htmlspecialchars($reel['username']); ?></span>
                                        <span style="color:white; opacity: 0.6;">•</span>
                                        <button class="btn-follow" onclick="toggleFollow(<?php echo $reel['user_id']; ?>)">Стежити</button>
                                    </div>
                                    <div class="reel-caption"><?php echo htmlspecialchars($reel['caption']); ?></div>
                                    <div class="reel-music">
                                        <svg fill="currentColor" height="12" role="img" viewBox="0 0 24 24" width="12"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8 8zm0-14c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6z"/></svg> 
                                        <span><?php echo htmlspecialchars($reel['username']); ?> • Оригінальне аудіо</span>
                                    </div>
                                </div>
                            </div>

                            <div class="reel-actions-side">
                                <div class="reel-action-btn <?php echo $reel['cur_user_liked'] ? 'liked' : ''; ?>" onclick="toggleLike(<?php echo $reel['id']; ?>)">
                                    <svg viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" width="24" height="24">
                                        <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                                    </svg>
                                    <span class="like-count"><?php echo $reel['like_count']; ?></span>
                                </div>
                                
                                <div class="reel-action-btn" onclick="openPostModal(<?php echo $reel['id']; ?>)">
                                    <svg aria-label="Коментувати" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><path d="M20.656 17.008a9.993 9.993 0 1 0-3.59 3.615L22 22Z" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="2"></path></svg>
                                    <span><?php echo rand(5, 50); ?></span>
                                </div>
                                
                                <div class="reel-action-btn">
                                    <svg aria-label="Поділитися" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><line fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="2" x1="22" x2="9.218" y1="3" y2="10.083"></line><polygon fill="none" points="11.698 20.334 22 3.001 2 3.001 9.218 10.084 11.698 20.334" stroke="currentColor" stroke-linejoin="round" stroke-width="2"></polygon></svg>
                                </div>

                                <div class="reel-action-btn">
                                    <svg aria-label="Зберегти" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><polygon fill="none" points="20 21 12 13.44 4 21 4 3 20 3 20 21" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></polygon></svg>
                                </div>

                                <div class="reel-action-btn" onclick="openPostOptions(<?php echo $reel['id']; ?>, <?php echo $reel['user_id']; ?>)">
                                    <svg aria-label="Більше" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><circle cx="12" cy="12" r="1.5"></circle><circle cx="6" cy="12" r="1.5"></circle><circle cx="18" cy="12" r="1.5"></circle></svg>
                                </div>
                                
                                <div class="reel-audio-preview">
                                    <img src="<?php echo htmlspecialchars($reel['avatar']); ?>">
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>


            <?php elseif ($view == 'settings'): ?>
                <!-- SETTINGS (DESKTOP STYLE) -->
                <?php 
                    $me = $curr;
                ?>
                <div class="settings-wrapper">
                    <aside class="settings-sidebar">
                        <h2 class="settings-header-title">Налаштування</h2>
                        
                        <div class="meta-promo-box">
                            <div class="meta-logo-row">
                                <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16" style="margin-right:5px;"><path d="M12.002 2.001c-5.522 0-9.999 4.477-9.999 9.999 0 5.523 4.477 10 10 10 5.523 0 10-4.477 10-10 0-5.522-4.477-9.999-10-9.999zm0 18.401c-4.639 0-8.401-3.763-8.401-8.402 0-4.639 3.762-8.401 8.401-8.401 4.639 0 8.401 3.762 8.401 8.401 0 4.639-3.762 8.402-8.401 8.402z"/></svg> 
                                Meta
                            </div>
                            <div style="color:white; font-size:15px; margin-bottom:5px;">Центр облікових записів</div>
                            <div style="font-weight:400; color:#a8a8a8; margin-bottom:10px;">Керуйте пов'язаними функціями й налаштуваннями облікового запису.</div>
                            <div>Переглянути більше в Центрі облікових записів</div>
                        </div>

                        <div class="settings-menu-item active">Редагувати профіль</div>
                        <div class="settings-menu-item">Сповіщення</div>
                        <div class="settings-menu-item">Створений вами контент</div>
                        <div class="settings-menu-item">Хто може бачити ваш контент</div>
                        <div class="settings-menu-item">Близькі друзі</div>
                        <div class="settings-menu-item">Заблоковані</div>
                    </aside>

                    <main class="settings-content">
                        <h2 class="edit-profile-header">Редагувати профіль</h2>

                        <!-- Avatar Change Row -->
                        <div class="settings-avatar-row">
                            <div class="settings-avatar-info">
                                <img src="<?php echo htmlspecialchars($me['avatar']); ?>" class="settings-avatar-img" id="settings-avatar-preview">
                                <div class="settings-username-stack">
                                    <span style="font-weight:700; color:white;"><?php echo htmlspecialchars($me['username']); ?></span>
                                    <span style="color:var(--text-secondary); font-size:14px;"><?php echo htmlspecialchars($me['full_name']); ?></span>
                                </div>
                            </div>
                            <button class="settings-btn-change-photo" onclick="document.getElementById('avatar-upload-input').click()">Змінити світлину</button>
                            <input type="file" id="avatar-upload-input" hidden onchange="previewSettingsAvatar(this)">
                        </div>

                        <form id="settings-form" onsubmit="updateProfile(event)">
                            <div class="settings-form-group">
                                <label class="settings-label">Сайт</label>
                                <input type="text" class="settings-input" placeholder="Сайт" disabled value="Веб-сайт доступний лише у мобільному додатку">
                                <div class="form-note">Редагування посилань доступне лише на мобільному телефоні.</div>
                            </div>

                            <div class="settings-form-group">
                                <label class="settings-label">Біографія</label>
                                <textarea name="bio" class="settings-textarea" maxlength="150"><?php echo htmlspecialchars($me['bio']); ?></textarea>
                                <div class="char-count">0 / 150</div>
                            </div>

                            <div class="settings-form-group">
                                <label class="settings-label">Стать</label>
                                <select class="settings-input">
                                    <option>Чоловіча</option>
                                    <option>Жіноча</option>
                                    <option>Інша</option>
                                    <option>Не вказувати</option>
                                </select>
                                <div class="form-note">Ця інформація не буде показана у вашому публічному профілі.</div>
                            </div>

                            <div class="settings-form-group">
                                <h3 style="font-size:16px; margin-bottom:10px;">Показувати рекомендовані облікові записи у профілях</h3>
                                <div class="toggle-row">
                                    <div style="font-size:14px; max-width:80%;">
                                        Показувати рекомендації облікових записів у профілях<br>
                                        <span style="color:var(--text-secondary); font-size:12px;">Налаштуйте, чи можуть інші бачити рекомендації схожих облікових записів у вашому профілі.</span>
                                    </div>
                                    <label class="toggle-switch">
                                        <input type="checkbox" checked>
                                        <span class="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>

                            <div style="margin-top:30px; text-align:right;">
                                <button type="submit" class="btn-primary" style="width: auto; padding: 12px 24px;">Надіслати</button>
                            </div>
                        </form>
                    </main>
                </div>

                    </main>
                </div>

            <?php elseif ($view == 'explore'): ?>
                <!-- EXPLORE -->
                <div class="explore-wrapper" style="max-width: 935px; margin: 0 auto; padding: 20px 0;">
                    
                    <div class="explore-search-container" style="padding: 0 16px 20px;">
                        <div class="sidebar-search-box" style="margin: 0; max-width: none;">
                            <svg fill="var(--text-secondary)" height="16" viewBox="0 0 24 24" width="16"><path d="M19 10.5A8.5 8.5 0 1 1 10.5 2a8.5 8.5 0 0 1 8.5 8.5Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></path><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="16.511" x2="22" y1="16.511" y2="22"></line></svg>
                            <input type="text" placeholder="Пошук" oninput="handleSidebarSearch(this.value)">
                        </div>
                    </div>

                    <div style="padding: 0 16px;">
                        <h2 style="margin-bottom: 20px; font-size: 16px; color: white; display: block; width: 100%;">Для вас</h2>
                        
                        <div class="profile-grid">
                            <?php foreach ($explore_posts as $p): ?>
                                <div class="grid-post" data-type="<?php echo ($p['media_type'] == 'video' || $p['type'] == 'reel') ? 'video' : 'image'; ?>" onclick="openPostModal(<?php echo $p['id']; ?>)">
                                    <?php if ($p['media_type'] == 'video'): ?>
                                        <video src="<?php echo htmlspecialchars($p['image_url']); ?>" autoplay muted loop playsinline></video>
                                        <div class="type-icon">
                                            <svg fill="white" height="18" viewBox="0 0 24 24" width="18"><path d="M5.888 22.5a3.46 3.46 0 0 1-1.721-.46l-.003-.002a3.451 3.451 0 0 1-1.72-2.982V4.943a3.445 3.445 0 0 1 5.163-2.987l12.226 7.059a3.444 3.444 0 0 1-.001 5.967l-12.22 7.056a3.462 3.462 0 0 1-1.724.462Z"></path></svg>
                                        </div>
                                    <?php else: ?>
                                        <img src="<?php echo htmlspecialchars($p['image_url']); ?>">
                                        <?php if ($p['type'] === 'reel'): ?>
                                            <div class="type-icon">
                                                <svg fill="white" height="18" viewBox="0 0 24 24" width="18"><path d="m12.823 1 2.974 5.002h-5.58l-2.65-4.971c.206-.013.419-.022.642-.022 2.155 0 3.886.745 4.614 2.89ZM7.227 2.01 9.873 6.99 4.296 6.98 2.302 2.031a.576.576 0 0 1 .157-.021c1.192 0 2.399.882 4.768 0Zm-4.965.021L4.258 7H1V4.943a3.445 3.445 0 0 1 1.262-2.911Zm16.894 18.027v-1.708h-2.14v2.14a2.956 2.956 0 0 1-2.953 2.953h-2.14v-2.14h2.14v-2.14h-2.14v-2.14h2.14v-2.14h-2.14v-2.14h2.14v-2.14h-2.14V7.55h5.093a3.446 3.446 0 0 1 3.445 3.445v9.062Z"></path></svg>
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>

                                    <!-- Grid Hover Overlay -->
                                    <div class="grid-item-overlay">
                                        <div class="overlay-stat">
                                            <svg fill="white" height="19" viewBox="0 0 48 48" width="19"><path d="M34.6 3.1c-4.5 0-7.9 1.8-10.6 5.6-2.7-3.7-6.1-5.5-10.6-5.5C6 3.1 0 9.6 0 17.6c0 7.3 5.4 12 10.6 16.5.6.5 1.3 1.1 1.9 1.7l11.5 10.6c.2.2.6.3.9.3.3 0 .6-.1.9-.3l11.5-10.6c.6-.6 1.3-1.2 1.9-1.7 5.2-4.5 10.6-9.2 10.6-16.5 0-8-6-14.5-13.4-14.5z"></path></svg>
                                            <span><?php echo $p['like_count'] > 1000 ? number_format($p['like_count']/1000, 1, ',', '') . ' тис.' : $p['like_count']; ?></span>
                                        </div>
                                        <div class="overlay-stat">
                                            <svg fill="white" height="19" viewBox="0 0 24 24" width="19"><path d="M20.656 17.008a9.993 9.993 0 1 0-3.59 3.615L22 22Z"></path></svg>
                                            <span><?php echo $p['comment_count']; ?></span>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

            <?php elseif ($view == 'profile' && $profile_user): ?>
                <!-- PROFILE -->
                <div class="profile-header">
                    <div class="profile-avatar-container">
                        <img src="<?php echo htmlspecialchars($profile_user['avatar']); ?>" class="profile-avatar-large">
                    </div>
                    
                    <div class="profile-info">
                        <div class="profile-actions">
                            <h2 class="profile-username"><?php echo htmlspecialchars($profile_user['username']); ?></h2>
                            <?php if ($profile_user['id'] == $user_id): ?>
                                <a href="?view=settings" class="btn-profile">Редагувати профіль</a>
                                <a href="#" class="btn-profile" style="margin-left:8px;">Переглянути архів</a>
                            <?php else: ?>
                                <button class="btn-profile" style="background:var(--button-blue);">Стежити</button>
                                <button class="btn-profile" style="margin-left:8px;">Надіслати повідомлення</button>
                            <?php endif; ?>
                        </div>

                        <div class="profile-stats">
                            <span><span class="stat-count"><?php echo count($profile_posts); ?></span> дописів</span>
                            <span><span class="stat-count">127</span> читачів</span>
                            <span><span class="stat-count">162</span> стежить</span>
                        </div>
                        
                        <div class="profile-bio">
                            <div class="profile-fullname"><?php echo htmlspecialchars($profile_user['full_name']); ?></div>
                            <div style="white-space: pre-wrap;"><?php echo htmlspecialchars($profile_user['bio'] ?? ''); ?></div>
                        </div>
                    </div>
                </div>

                <!-- Highlights -->
                <div class="highlights">
                    <div class="highlight-item">
                        <div class="highlight-circle">
                            <img src="assets/default_avatar.svg" style="width:70px;height:70px;border-radius:50%;object-fit:cover;">
                        </div>
                        <div class="highlight-title">Я бита</div>
                    </div>
                    <div class="highlight-item">
                        <div class="highlight-circle">
                            <svg viewBox="0 0 24 24" fill="white" width="24" height="24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8 8 8z"/></svg>

                        </div>
                        <div class="highlight-title">Бит</div>
                    </div>
                   <div class="highlight-item">
                        <div class="highlight-circle">
                             <div style="font-size:30px;">+</div>
                        </div>
                        <div class="highlight-title">Новий</div>
                    </div>
                </div>
                
                <!-- Simple Profile Tabs -->
                <div class="profile-tabs">
                    <div class="tab-item active" onclick="switchProfileTab('posts', this)">
                        <svg aria-label="" fill="currentColor" height="12" role="img" viewBox="0 0 24 24" width="12"><rect fill="none" height="18" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" width="18" x="3" y="3"></rect><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="9.015" x2="9.015" y1="3" y2="21"></line><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="14.985" x2="14.985" y1="3" y2="21"></line><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="21" x2="3" y1="9.015" y2="9.015"></line><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="21" x2="3" y1="14.985" y2="14.985"></line></svg>
                        <span>ДОПИСИ</span>
                    </div>
                    <div class="tab-item" onclick="switchProfileTab('reels', this)">
                        <svg aria-label="" fill="currentColor" height="12" role="img" viewBox="0 0 24 24" width="12"><path d="M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2Zm0 2a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm-2 5a1 1 0 0 1 1.664-.78l5 3.5a1 1 0 0 1 0 1.56l-5 3.5A1 1 0 0 1 9 14V9Z"></path></svg>
                        <span>REELS</span>
                    </div>
                    <div class="tab-item" onclick="switchProfileTab('saved', this)">
                        <svg aria-label="" fill="currentColor" height="12" role="img" viewBox="0 0 24 24" width="12"><polygon fill="none" points="20 21 12 13.44 4 21 4 3 20 3 20 21" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></polygon></svg>
                        <span>ЗБЕРЕЖЕНЕ</span>
                    </div>
                    <div class="tab-item" onclick="switchProfileTab('tagged', this)">
                        <svg aria-label="" fill="currentColor" height="12" role="img" viewBox="0 0 24 24" width="12"><path d="M10.201 3.797 12 1.997l1.799 1.8a1.59 1.59 0 0 0 1.124.465h5.259A1.818 1.818 0 0 1 22 6.08v14.104a1.818 1.818 0 0 1-1.818 1.818H3.818A1.818 1.818 0 0 1 2 20.184V6.08a1.818 1.818 0 0 1 1.818-1.818h5.26a1.59 1.59 0 0 0 1.123-.465Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></path><path d="M18.598 22.002V21.4a3.949 3.949 0 0 0-3.948-3.949H9.495A3.949 3.949 0 0 0 5.546 21.4v.603" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></path><circle cx="12.072" cy="11.075" fill="none" r="3.556" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></circle></svg>
                        <span>З ВАМИ</span>
                    </div>
                </div>

                <div class="profile-grid-wrapper">
                    <div class="profile-grid">
                        <?php foreach ($profile_posts as $p): ?>
                            <div class="grid-post" data-type="<?php echo ($p['media_type'] == 'video' || $p['type'] == 'reel') ? 'video' : 'image'; ?>" onclick="openPostModal(<?php echo $p['id']; ?>)">
                                <?php if ($p['media_type'] == 'video'): ?>
                                    <video src="<?php echo htmlspecialchars($p['image_url']); ?>" autoplay muted loop playsinline style="width:100%; height:100%; object-fit:cover;"></video>
                                    <div class="type-icon">
                                        <svg fill="white" height="18" viewBox="0 0 24 24" width="18"><path d="M5.888 22.5a3.46 3.46 0 0 1-1.721-.46l-.003-.002a3.451 3.451 0 0 1-1.72-2.982V4.943a3.445 3.445 0 0 1 5.163-2.987l12.226 7.059a3.444 3.444 0 0 1-.001 5.967l-12.22 7.056a3.462 3.462 0 0 1-1.724.462Z"></path></svg>
                                    </div>
                                <?php else: ?>
                                    <img src="<?php echo htmlspecialchars($p['image_url']); ?>">
                                    <?php if ($p['type'] === 'reel'): ?>
                                        <div class="type-icon">
                                            <svg fill="white" height="18" viewBox="0 0 24 24" width="18"><path d="m12.823 1 2.974 5.002h-5.58l-2.65-4.971c.206-.013.419-.022.642-.022 2.155 0 3.886.745 4.614 2.89ZM7.227 2.01 9.873 6.99 4.296 6.98 2.302 2.031a.576.576 0 0 1 .157-.021c1.192 0 2.399.882 4.768 0Zm-4.965.021L4.258 7H1V4.943a3.445 3.445 0 0 1 1.262-2.911Zm16.894 18.027v-1.708h-2.14v2.14a2.956 2.956 0 0 1-2.953 2.953h-2.14v-2.14h2.14v-2.14h-2.14v-2.14h2.14v-2.14h-2.14v-2.14h2.14v-2.14h-2.14V7.55h5.093a3.446 3.446 0 0 1 3.445 3.445v9.062Z"></path></svg>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php elseif ($view == 'direct'): ?>
                <!-- MESSENGER (DIRECT) -->
                <div class="messenger-container">
                    <aside class="messenger-sidebar">
                        <header class="messenger-sidebar-header">
                            <div class="messenger-user-selector">
                                <h2><?php echo htmlspecialchars($curr['username']); ?></h2>
                                <svg aria-label="Низ" fill="currentColor" height="12" viewBox="0 0 24 24" width="12"><path d="M21 17.502a.997.997 0 0 1-.707-.293L12 8.913l-8.293 8.296a1 1 0 1 1-1.414-1.414l9-9a.999.999 0 0 1 1.414 0l9 9a1 1 0 0 1-.707 1.707Z"></path></svg>
                            </div>
                            <button class="new-message-btn" onclick="openNewMsgModal()">
                                <svg aria-label="Нове повідомлення" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><path d="M12.202 3.203H5.202a3 3 0 0 0-3 3V18.8a3 3 0 0 0 3 3h11.598a3 3 0 0 0 3-3V11.802a1 1 0 0 0-2 0V18.8a1 1 0 0 1-1 1H5.202a1 1 0 0 1-1-1V6.203a1 1 0 0 1 1-1h7a1 1 0 0 0 0-2ZM17.702 1.503a1.5 1.5 0 0 0-2.121 0l-7.576 7.575a.5.5 0 0 0-.114.175l-1.414 4.243a.5.5 0 0 0 .633.633l4.242-1.414a.5.5 0 0 0 .176-.114l7.575-7.576a1.5 1.5 0 0 0 0-2.122Z"></path></svg>
                            </button>
                        </header>

                        <div class="messenger-search" style="padding: 0 20px 10px;">
                            <div style="background: #262626; border-radius: 8px; padding: 8px 12px; display: flex; align-items: center; gap: 8px;">
                                <svg aria-label="Пошук" fill="#a8a8a8" height="16" viewBox="0 0 24 24" width="16"><path d="M19 10.5A8.5 8.5 0 1 1 10.5 2a8.5 8.5 0 0 1 8.5 8.5Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></path><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="16.511" x2="22" y1="16.511" y2="22"></line></svg>
                                <input type="text" placeholder="Пошук" style="background:none; border:none; color:white; font-size:14px; outline:none; width:100%;">
                            </div>
                        </div>



                        <div class="messenger-notes-row" id="messenger-notes-row">
                             <!-- Notes will be loaded via JS -->
                            <div class="note-item" onclick="createNote()">
                                <div class="note-avatar-wrapper">
                                    <img src="<?php echo htmlspecialchars($curr['avatar']); ?>" class="note-avatar">
                                    <div class="note-bubble plus">+</div>
                                    <div class="note-sub">Ваша нотатка</div>
                                </div>
                            </div>
                        </div>

                        <div class="messenger-list-header">
                            <h3>Повідомлення</h3>
                            <span class="requests-link">Requests</span>
                        </div>

                        <div class="messenger-list">
                            <?php if (empty($conversations)): ?>
                                <div style="display:flex; flex-direction:column; align-items:center; justify-content:center; padding: 40px 20px; text-align:center;">
                                     <div style="width:56px; height:56px; border:2px solid white; border-radius:50%; display:flex; align-items:center; justify-content:center; margin-bottom:15px;">
                                        <svg aria-label="Direct" fill="currentColor" height="32" viewBox="0 0 24 24" width="32"><path d="M12.003 2.001a9.705 9.705 0 1 1 0 19.41 10.61 10.61 0 0 1-1.479-.108l-5.698 1.626a.998.998 0 0 1-1.229-1.23l1.626-5.698a9.715 9.715 0 0 1-.108-1.479 9.771 9.771 0 0 1 2.887-7.252 9.771 9.771 0 0 1 3.996-2.269ZM6.903 14.887l-.462 1.62-.257.901.901-.257 1.62-.462.636.216a7.712 7.712 0 1 0 5.666-12.906 7.712 7.712 0 0 0-8.32 10.252l.216.636Zm8.513-4.223a.997.997 0 0 1 .485 1.838l-4.996 2.776a1.002 1.002 0 0 1-1.222-1.583l4.996-2.776a.987.987 0 0 1 .737-.255Z"></path></svg>
                                     </div>
                                     <p style="font-weight:600; font-size:14px; margin-bottom:5px;">Немає повідомлень</p>
                                     <p style="font-size:12px; color:var(--text-secondary);">Почніть спілкування з друзями</p>
                                </div>
                            <?php endif; ?>
                            <?php foreach ($conversations as $conv): ?>
                                <div class="chat-item" onclick="loadChat(<?php echo $conv['id']; ?>)">
                                    <img src="<?php echo htmlspecialchars($conv['avatar']); ?>" class="chat-avatar">
                                    <div class="chat-info">
                                        <span class="chat-name"><?php echo htmlspecialchars($conv['full_name'] ?: $conv['username']); ?></span>
                                        <span class="chat-last-msg">
                                            <?php echo htmlspecialchars($conv['last_msg'] ?: 'Надішліть повідомлення'); ?> 
                                            <span class="chat-time">• <?php echo isset($conv['last_msg_time']) ? date('H:i', strtotime($conv['last_msg_time'])) : ''; ?></span>
                                        </span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </aside>

                    <main class="messenger-chat-area">
                        <div id="chat-placeholder" class="chat-placeholder">
                            <div class="placeholder-icon">
                                <svg aria-label="Direct" fill="currentColor" height="96" viewBox="0 0 96 96" width="96"><path d="M48 0C21.49 0 0 21.49 0 48s21.49 48 48 48 48-21.49 48-48S74.51 0 48 0Zm21.17 34.81L56.29 64.12c-1.15 2.56-3.64 4.28-6.43 4.47l-10.45.69c-2.79.19-5.48-1.15-6.96-3.5l-5.61-9c-1.48-2.35-1.57-5.32-.23-7.76l12.88-23.31c1.34-2.44 3.93-3.95 6.72-3.95h10.45c2.79 0 5.38 1.51 6.72 3.95l2.25 4.08h1.01l-2.01-3.64c-1.61-2.92-4.71-4.74-8.06-4.74h-10.45c-3.35 0-6.45 1.82-8.06 4.74L25.35 44.52c-1.61 2.92-1.5 6.49.27 9.3l5.61 9c1.77 2.81 4.99 4.42 8.35 4.42l.6-.04 10.45-.69c3.35-.22 6.34-2.29 7.72-5.36l12.88-29.31c1.38-3.07.69-6.64-1.72-8.85l-7.31-6.72 1.48-1.35 7.31 6.72c2.89 2.65 3.72 6.94 2.07 10.63Z"></path></svg>
                            </div>
                            <h2>Ваші повідомлення</h2>
                            <p>Надсилайте приватні світлини та повідомлення другу або групі</p>
                            <button class="btn-primary" style="width: auto; padding: 10px 20px;">Надіслати повідомлення</button>
                        </div>
                        
                        <div id="active-chat" style="display:none; flex-direction:column; height:100%;">
                            <!-- Dynamic Chat Content -->
                        </div>
                    </main>
                </div>
            <?php endif; ?>
            
            </main> <!-- End Feed Container -->

            <!-- RIGHT SIDEBAR (Desktop) - Hidden on certain views -->
            <?php if (!in_array($view, ['direct', 'settings', 'reels'])): ?>
            <aside class="sidebar-right">
                <div class="mini-profile">
                    <div style="display:flex; align-items:center;">
                        <img src="<?php echo !empty($curr['avatar']) ? htmlspecialchars($curr['avatar']) : 'assets/default_avatar.svg'; ?>" style="width:44px; height:44px; border-radius:50%; margin-right:12px; object-fit:cover;">
                        <div class="user-info-stacked">
                            <a href="?view=profile" class="u-name"><?php echo htmlspecialchars($curr['username']); ?></a>
                            <span class="u-sub"><?php echo htmlspecialchars($curr['full_name']); ?></span>
                        </div>
                    </div>
                    <a href="?view=logout" class="link-blue">Перейти</a>
                </div>

                <div class="suggestions-header">
                    <span style="color:var(--text-secondary); font-size:14px; font-weight:600;">Рекомендації для вас</span>
                    <a href="#" style="color:white; font-size:12px; font-weight:600; text-decoration:none;">Переглянути всіх</a>
                </div>

                <?php 
                    // Fetch suggestions (random users excluding self)
                    $stmt = $pdo->prepare("SELECT id, username, full_name, avatar FROM users WHERE id != ? ORDER BY RAND() LIMIT 5");
                    $stmt->execute([$user_id]);
                    $suggestions = $stmt->fetchAll();
                ?>
                
                <?php foreach ($suggestions as $sug): ?>
                    <div class="suggestion-item">
                        <div style="display:flex; align-items:center;">
                            <img src="<?php echo !empty($sug['avatar']) ? htmlspecialchars($sug['avatar']) : 'assets/default_avatar.svg'; ?>" style="width:32px; height:32px; border-radius:50%; margin-right:12px; object-fit:cover;">
                            <div class="user-info-stacked">
                                <a href="?view=profile&id=<?php echo $sug['id']; ?>" class="u-name" style="text-decoration:none; color:white;"><?php echo htmlspecialchars($sug['username']); ?></a>
                                <span class="u-sub">Рекомендації для вас</span>
                            </div>
                        </div>
                        <a href="#" class="link-blue" style="font-size:12px; font-weight:600; text-decoration:none;">Стежити</a>
                    </div>
                <?php endforeach; ?>

                <div style="margin-top: 30px; font-size: 12px; color: #737373; text-transform: uppercase; letter-spacing: 0.2px;">
                    <p>© 2026 UAGRAM FROM DEEPMIND</p>
                </div>
            </aside>
            <?php endif; ?>
        
        </div> <!-- End Main Wrapper -->

        <!-- Create Post Modal -->
        <div class="modal-overlay" id="create-modal">
            <div class="modal" id="create-modal-container">
                <div class="modal-header">
                    <span id="create-modal-title">Створити допис</span>
                    <button class="close-btn" onclick="closeModal()">✕</button>
                </div>
                <!-- STEP 1: SELECT FILE -->
                <div class="modal-body create-step-1" id="create-step-select">
                    <div class="upload-icon-container">
                        <svg aria-label="Значок, що представляє медіафайли, як-от зображення або відео" fill="currentColor" height="77" role="img" viewBox="0 0 97.6 77.3" width="96"><path d="M16.3 24h.3c.3-.2.6-.4.9-.5 1.7-.7 3.5-1.1 5.4-1.1 9.9 1 18.1 8 19.9 17.7l.2 1.2h77.3c.1 0 .2.1.2.1v34c0 .1-.1.2-.2.2H.2c-.1 0-.2-.1-.2-.2V34c0-.1.1-.2.2-.2h16.1c0-.1 0-.1-.1-.2-.8-4.8-1.5-9.6-2.1-14.4l-.1-1.3c-.6-4.9-1.3-9.9-2.2-14.8-.4-2-.8-4-1.2-6l-.3-1.4c-.1-.7-.2-1.4-.2-2.1V9c0-5 4-9 9-9h13.3c3.7 0 6.1 2.3 8.3 4.2 1 .8 2.3 2.1 3.4 3.1 1 .9 2.1 1.9 3.2 2.8s2.2 2 3.3 3c2.7 2.3 5.3 4.6 9 4.6l.4-.1ZM81.5 0c-4.1 0-7.4 3.3-7.4 7.4s3.3 7.4 7.4 7.4c4.1 0 7.4-3.3 7.4-7.4S85.6 0 81.5 0Z"></path></svg>
                    </div>
                    <p class="drag-text">Перетягніть сюди світлини й відео</p>
                    <label class="btn-primary select-btn">
                        Вибрати з комп'ютера
                        <input type="file" id="file-input" hidden accept="image/*,video/*">
                    </label>
                </div>

                <!-- STEP 2: PREVIEW & CAPTION -->
                <div class="modal-body create-step-2" id="create-step-preview" style="display:none; padding:0; flex-direction:row;">
                    <div class="create-preview-container" style="flex:1; background:black; display:flex; align-items:center; justify-content:center;">
                        <img id="image-preview" style="max-width:100%; max-height:100%; object-fit:contain;">
                        <video id="video-preview" controls style="display:none; max-width:100%; max-height:100%;"></video>
                    </div>
                    <div class="create-sidebar" style="width:340px; border-left:1px solid #363636; display:flex; flex-direction:column;">
                        <div class="sidebar-header" style="padding:16px; display:flex; align-items:center;">
                             <?php 
                                $me = $curr;
                             ?>
                             <img src="<?php echo htmlspecialchars($me['avatar']); ?>" style="width:28px; height:28px; border-radius:50%; margin-right:12px;">
                             <span style="font-weight:600; font-size:14px;"><?php echo htmlspecialchars($me['username']); ?></span>
                        </div>
                        <textarea class="caption-input" id="caption-input" placeholder="Додайте підпис..." style="border:none; flex-grow:1; background:transparent; padding:16px;"></textarea>
                        <div style="padding:16px; border-top:1px solid #363636;">
                            <button class="btn-primary" onclick="uploadPost()">Поділитися</button>
                        </div>
                    </div>
                </div>
            </div>
            </div>
        </div>

        <!-- NEW MESSAGE MODAL -->
        <div class="modal-overlay" id="new-msg-modal">
            <div class="modal" style="width: 400px; height: 600px; max-height: 80vh; display: flex; flex-direction: column;">
                <div class="modal-header">
                    <span style="flex:1; text-align:center;">Нове повідомлення</span>
                    <button class="close-btn" onclick="closeNewMsgModal()">✕</button>
                </div>
                <div style="padding: 10px 16px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center;">
                    <span style="font-weight: 600; margin-right: 10px;">Кому:</span>
                    <input type="text" id="new-msg-search" placeholder="Пошук..." style="background: none; border: none; color: white; flex: 1; outline: none;" oninput="searchUsersForMsg(this.value)">
                </div>
                <div class="modal-body" style="padding: 0; overflow-y: auto; flex: 1;" id="new-msg-results">
                    <div style="padding: 20px; text-align: center; color: var(--text-secondary); font-size: 14px;">
                        Не знайдено жодного облікового запису.
                    </div>
                </div>
                <div style="padding: 16px; border-top: 1px solid var(--border-color);">
                    <button class="btn-primary" id="start-chat-btn" disabled onclick="createChatFromModal()">Чат</button>
                </div>
            </div>
        </div>

        <!-- Bottom Navigation -->
        <nav class="bottom-nav">
            <div class="nav-item <?php echo $view=='home'?'active':''; ?>" onclick="window.location='?view=home'">
                <svg viewBox="0 0 24 24" fill="<?php echo $view=='home'?'currentColor':'none'; ?>" stroke="currentColor" stroke-width="2">
                    <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                    <polyline points="9 22 9 12 15 12 15 22"></polyline>
                </svg>
            </div>
            
            <div class="nav-item" onclick="openModal('post')">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                    <line x1="12" y1="8" x2="12" y2="16"></line>
                    <line x1="8" y1="12" x2="16" y2="12"></line>
                </svg>
            </div>

            <div class="nav-item <?php echo $view=='reels'?'active':''; ?>" onclick="window.location='?view=reels'">
                <svg viewBox="0 0 24 24" fill="<?php echo $view=='reels'?'currentColor':'none'; ?>" stroke="currentColor" stroke-width="2">
                    <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path>
                    <polyline points="16 6 12 2 8 6"></polyline>
                    <line x1="12" y1="2" x2="12" y2="15"></line>
                </svg>
                <!-- Using a video-like icon since standard icons are limited -->
            </div>

            <div class="nav-item <?php echo $view=='profile'?'active':''; ?>" onclick="window.location='?view=profile'">
                <svg viewBox="0 0 24 24" fill="<?php echo $view=='profile'?'currentColor':'none'; ?>" stroke="currentColor" stroke-width="2">
                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                    <circle cx="12" cy="7" r="4"></circle>
                </svg>
            </div>
        </nav>

        <div class="bottom-nav">
            <a href="index.php" class="nav-item <?php echo $view=='home'?'active':''; ?>">
                <svg aria-label="Головна" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><path d="M22 23h-6.001a1 1 0 0 1-1-1v-5.645a3.5 3.5 0 1 0-7 0V22a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V8.869a3.42 3.42 0 0 1 1.104-2.557l8.033-7.273a1.137 1.137 0 0 1 1.527 0l8.232 7.452A3.33 3.33 0 0 1 21 9.157V22a1 1 0 0 1-1 1Z"></path></svg>
            </a>
            <a href="?view=explore" class="nav-item <?php echo $view=='explore'?'active':''; ?>">
                <svg aria-label="Цікаве" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><polygon points="13.941 13.953 7.581 16.424 10.06 10.056 16.42 7.585 13.941 13.953"></polygon><path d="M12 2a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2Zm0 18a8 8 0 1 1 8-8 8.009 8.009 0 0 1-8 8Z"></path></svg>
            </a>
            <a href="?view=reels" class="nav-item <?php echo $view=='reels'?'active':''; ?>">
                <svg aria-label="Reels" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><line x1="2.049" x2="21.95" y1="7.002" y2="7.002"></line><line x1="13.504" x2="16.362" y1="2.001" y2="7.002"></line><line x1="7.207" x2="10.002" y1="2.11" y2="7.002"></line><path d="M2 12.001v3.449c0 2.849.698 4.006 1.606 4.945.94.908 2.098 1.607 4.946 1.607h6.896c2.848 0 4.006-.699 4.946-1.607.908-.939 1.606-2.096 1.606-4.945V8.552c0-2.848-.698-4.006-1.606-4.945C19.454 2.699 18.296 2 15.448 2H8.552c-2.848 0-4.006.699-4.946 1.607C2.698 4.546 2 5.704 2 8.552Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></path><path d="M9.763 17.664a.908.908 0 0 1-.454-.787V11.63a.909.909 0 0 1 1.364-.788l4.545 2.624a.909.909 0 0 1 0 1.575l-4.545 2.624a.91.91 0 0 1-.91 0Z" fill-rule="evenodd"></path></svg>
            </a>
            <div class="nav-item" onclick="openModal('post')">
                <svg aria-label="Створити" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><path d="M2 12v3.45c0 2.849.698 4.005 1.606 4.944.94.909 2.098 1.608 4.946 1.608h6.896c2.848 0 4.006-.7 4.946-1.608C21.302 19.455 22 18.3 22 15.45V8.552c0-2.849-.698-4.006-1.606-4.945C19.454 2.7 18.296 2 15.448 2H8.552c-2.848 0-4.006.699-4.946 1.607C2.698 4.547 2 5.703 2 8.552Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></path><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="6.545" x2="17.455" y1="12.001" y2="12.001"></line><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="12.003" x2="12.003" y1="6.545" y2="17.455"></line></svg>
            </div>
            <a href="?view=direct" class="nav-item <?php echo $view=='direct'?'active':''; ?>">
                <svg aria-label="Повідомлення" fill="currentColor" height="24" viewBox="0 0 24 24" width="24"><path d="M12.003 2.001a9.705 9.705 1 1 1 0 19.41 10.61 10.61 0 0 1-1.479-.108l-5.698 1.626a.998.998 0 0 1-1.229-1.23l1.626-5.698a9.715 9.715 0 0 1-.108-1.479 9.771 9.771 0 0 1 2.887-7.252 9.771 9.771 0 0 1 3.996-2.269ZM6.903 14.887l-.462 1.62-.257.901.901-.257 1.62-.462.636.216a7.712 7.712 1 1 0 5.666-12.906 7.712 7.712 0 0 0-8.32 10.252l.216.636Zm8.513-4.223a.997.997 0 0 1 .485 1.838l-4.996 2.776a1.002 1.002 0 0 1-1.222-1.583l4.996-2.776a.987.987 0 0 1 .737-.255Z"></path></svg>
            </a>
            <a href="?view=profile" class="nav-item <?php echo $view=='profile'?'active':''; ?>">
                <img src="<?php echo !empty($myAv) ? htmlspecialchars($myAv) : 'assets/default_avatar.svg'; ?>" style="width:24px; height:24px; border-radius:50%; object-fit:cover; border: <?php echo $view=='profile'?'2px solid var(--text-main)':'none'; ?>">
            </a>
        </div>

        <script>
            window.currentUserId = <?php echo $user_id; ?>;
            window.currentUserAvatar = "<?php echo !empty($curr['avatar']) ? htmlspecialchars($curr['avatar']) : 'assets/default_avatar.svg'; ?>";
        </script>
        <script src="assets/app.js"></script>
        <div id="toast-container" style="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:999;"></div>

    <?php endif; ?>
</body>
</html>
