<?php
/**
 * صفحة المدونة - تصميم Instagram Style
 */

session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';

$database = new Database();
$conn = $database->getConnection();

// جلب إعدادات الموقع
try {
    $query = "SELECT setting_key, setting_value FROM settings 
              WHERE setting_key IN ('site_name', 'logo_text')";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    $site_name = $settings['site_name'] ?? 'Roz Skin';
    $logo_text = $settings['logo_text'] ?? 'Roz Skin';
} catch (PDOException $e) {
    $site_name = 'Roz Skin';
    $logo_text = 'Roz Skin';
}

// الفلترة
$category = $_GET['category'] ?? '';
$search = $_GET['search'] ?? '';

$where = ["status = 'published'"];
$params = [];

if ($category) {
    $where[] = "category = ?";
    $params[] = $category;
}

if ($search) {
    $where[] = "(title LIKE ? OR content LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = implode(' AND ', $where);

// جلب المنشورات
$stmt = $conn->prepare("SELECT * FROM posts WHERE $where_clause ORDER BY published_at DESC, created_at DESC");
$stmt->execute($params);
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// جلب الفئات
$categories = $conn->query("SELECT DISTINCT category FROM posts WHERE status = 'published' AND category IS NOT NULL AND category != '' ORDER BY category")->fetchAll(PDO::FETCH_COLUMN);

// إحصائيات
$total_posts = count($posts);
$total_categories = count($categories);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>روز فيد - Roz Feed | <?php echo htmlspecialchars($site_name); ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Tajawal', -apple-system, BlinkMacSystemFont, sans-serif;
        }
        
        body {
            background: #fafafa;
            padding-top: 60px;
        }
        
        /* Navigation */
        .nav {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: white;
            border-bottom: 1px solid #dbdbdb;
            padding: 12px 20px;
            z-index: 100;
        }
        
        .nav-content {
            max-width: 975px;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .nav-logo {
            font-size: 24px;
            font-weight: 700;
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            text-decoration: none;
        }
        
        .nav-back {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #262626;
            text-decoration: none;
            font-weight: 500;
            padding: 8px 16px;
            border-radius: 8px;
            transition: background 0.2s;
        }
        
        .nav-back:hover {
            background: #f5f5f5;
        }
        
        /* Profile Header - Instagram Style */
        .profile-header {
            max-width: 975px;
            margin: 30px auto;
            padding: 0 20px;
        }
        
        .profile-info {
            display: flex;
            gap: 80px;
            margin-bottom: 44px;
            padding-bottom: 44px;
            border-bottom: 1px solid #dbdbdb;
        }
        
        .profile-avatar {
            flex-shrink: 0;
        }
        
        .avatar-circle {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 48px;
            font-weight: 700;
            box-shadow: 0 4px 20px rgba(229, 115, 147, 0.3);
        }
        
        .profile-details {
            flex: 1;
        }
        
        .profile-username {
            font-size: 28px;
            font-weight: 400;
            color: #262626;
            margin-bottom: 20px;
        }
        
        .profile-stats {
            display: flex;
            gap: 40px;
            margin-bottom: 20px;
        }
        
        .stat-item {
            display: flex;
            gap: 6px;
            font-size: 16px;
        }
        
        .stat-value {
            font-weight: 600;
            color: #262626;
        }
        
        .stat-label {
            color: #262626;
        }
        
        .profile-bio {
            color: #262626;
            line-height: 1.6;
            margin-bottom: 12px;
        }
        
        .profile-bio strong {
            display: block;
            margin-bottom: 4px;
        }
        
        /* Categories Tabs - Instagram Style */
        .categories-tabs {
            display: flex;
            justify-content: center;
            gap: 60px;
            border-top: 1px solid #dbdbdb;
            padding-top: 0;
        }
        
        .tab-item {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 14px 0;
            color: #8e8e8e;
            text-decoration: none;
            font-size: 12px;
            font-weight: 600;
            letter-spacing: 1px;
            text-transform: uppercase;
            border-top: 1px solid transparent;
            margin-top: -1px;
            transition: all 0.2s;
        }
        
        .tab-item:hover,
        .tab-item.active {
            color: #262626;
            border-top-color: #262626;
        }
        
        .tab-item svg {
            width: 12px;
            height: 12px;
        }
        
        /* Posts Grid - Instagram Style */
        .posts-grid {
            max-width: 975px;
            margin: 0 auto;
            padding: 28px 20px;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 28px;
        }
        
        .post-item {
            position: relative;
            aspect-ratio: 1;
            cursor: pointer;
            overflow: hidden;
            background: #f0f0f0;
        }
        
        .post-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.2s;
        }
        
        .post-item:hover .post-image {
            transform: scale(1.05);
        }
        
        .post-overlay {
            position: absolute;
            inset: 0;
            background: rgba(0, 0, 0, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 30px;
            opacity: 0;
            transition: opacity 0.2s;
            color: white;
            font-weight: 600;
        }
        
        .post-item:hover .post-overlay {
            opacity: 1;
        }
        
        .overlay-stat {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 16px;
        }
        
        .overlay-stat svg {
            width: 20px;
            height: 20px;
            fill: white;
        }
        
        /* Modal - Instagram Style */
        .modal {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.85);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: white;
            max-width: 1200px;
            width: 100%;
            max-height: 90vh;
            border-radius: 12px;
            overflow: hidden;
            display: flex;
        }
        
        .modal-image {
            flex: 1;
            background: #000;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .modal-image img {
            max-width: 100%;
            max-height: 90vh;
            object-fit: contain;
        }
        
        .modal-sidebar {
            width: 400px;
            display: flex;
            flex-direction: column;
            max-height: 90vh;
        }
        
        .modal-header {
            padding: 16px;
            border-bottom: 1px solid #dbdbdb;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .modal-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
            font-weight: 700;
        }
        
        .modal-username {
            font-weight: 600;
            color: #262626;
        }
        
        .modal-body {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
        }
        
        .modal-title {
            font-size: 20px;
            font-weight: 700;
            color: #262626;
            margin-bottom: 12px;
        }
        
        .modal-category {
            display: inline-block;
            padding: 4px 12px;
            background: rgba(229, 115, 147, 0.1);
            color: #E57393;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 16px;
        }
        
        .modal-content-text {
            color: #262626;
            line-height: 1.8;
            font-size: 14px;
        }
        
        .modal-actions {
            padding: 12px 16px;
            border-top: 1px solid #dbdbdb;
            display: flex;
            gap: 16px;
        }
        
        .action-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
            color: #262626;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.2s;
        }
        
        .action-btn:hover {
            opacity: 0.7;
        }
        
        .action-btn svg {
            width: 24px;
            height: 24px;
            transition: all 0.3s;
        }
        
        .action-btn.liked svg {
            fill: #ed4956;
            stroke: #ed4956;
            animation: likeAnimation 0.4s ease;
        }
        
        @keyframes likeAnimation {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.3); }
        }
        
        .modal-likes {
            padding: 0 16px 12px;
            font-weight: 600;
            color: #262626;
            font-size: 14px;
        }
        
        .modal-comments {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
            border-top: 1px solid #dbdbdb;
        }
        
        .comment-item {
            display: flex;
            gap: 12px;
            margin-bottom: 16px;
        }
        
        .comment-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 12px;
            font-weight: 700;
            flex-shrink: 0;
        }
        
        .comment-content {
            flex: 1;
        }
        
        .comment-username {
            font-weight: 600;
            color: #262626;
            margin-left: 8px;
        }
        
        .comment-text {
            color: #262626;
            font-size: 14px;
            line-height: 1.5;
        }
        
        .comment-time {
            color: #8e8e8e;
            font-size: 12px;
            margin-top: 4px;
        }
        
        .comment-form {
            padding: 16px;
            border-top: 1px solid #dbdbdb;
            display: flex;
            gap: 12px;
            align-items: center;
        }
        
        .comment-input {
            flex: 1;
            border: none;
            outline: none;
            font-size: 14px;
            color: #262626;
        }
        
        .comment-input::placeholder {
            color: #8e8e8e;
        }
        
        .comment-submit {
            background: none;
            border: none;
            color: #0095f6;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            padding: 0;
        }
        
        .comment-submit:disabled {
            opacity: 0.3;
            cursor: default;
        }
        
        .modal-footer {
            padding: 12px 16px;
            border-top: 1px solid #dbdbdb;
        }
        
        .modal-date {
            color: #8e8e8e;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 0.2px;
        }
        
        .modal-close {
            position: absolute;
            top: 20px;
            right: 20px;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.9);
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
            z-index: 10;
        }
        
        .modal-close:hover {
            background: white;
            transform: scale(1.1);
        }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: #8e8e8e;
        }
        
        .empty-state svg {
            width: 64px;
            height: 64px;
            margin-bottom: 20px;
            opacity: 0.3;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .profile-info {
                gap: 30px;
                flex-direction: column;
                align-items: center;
                text-align: center;
            }
            
            .avatar-circle {
                width: 100px;
                height: 100px;
                font-size: 36px;
            }
            
            .profile-username {
                font-size: 24px;
            }
            
            .profile-stats {
                justify-content: center;
                gap: 20px;
            }
            
            .categories-tabs {
                gap: 20px;
                overflow-x: auto;
                justify-content: flex-start;
                padding: 0 20px;
            }
            
            .posts-grid {
                grid-template-columns: repeat(3, 1fr);
                gap: 3px;
                padding: 0;
            }
            
            .modal-content {
                flex-direction: column;
                max-height: 95vh;
            }
            
            .modal-sidebar {
                width: 100%;
                max-height: 50vh;
            }
        }
        
        @media (max-width: 480px) {
            .stat-item {
                flex-direction: column;
                gap: 2px;
                text-align: center;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/product-cards.css">
</head>
<body>
    <!-- Navigation -->
    <nav class="nav">
        <div class="nav-content">
            <div class="nav-logo"><?php echo htmlspecialchars($logo_text); ?></div>
            <a href="index.php" class="nav-back">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="19" y1="12" x2="5" y2="12"></line>
                    <polyline points="12 19 5 12 12 5"></polyline>
                </svg>
                الرئيسية
            </a>
        </div>
    </nav>

    <!-- Profile Header -->
    <div class="profile-header">
        <div class="profile-info">
            <div class="profile-avatar">
                <div class="avatar-circle">R</div>
            </div>
            
            <div class="profile-details">
                <h1 class="profile-username">روز فيد</h1>
                
                <div class="profile-stats">
                    <div class="stat-item">
                        <span class="stat-value"><?php echo $total_posts; ?></span>
                        <span class="stat-label">منشور</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-value"><?php echo $total_categories; ?></span>
                        <span class="stat-label">فئة</span>
                    </div>
                </div>
                
                <div class="profile-bio">
                    <strong>Roz Feed - اكتشفي عالم الجمال 💄✨</strong>
                    نصائح يومية لإطلالة مثالية | أحدث صيحات العناية بالبشرة
                    <br>تابعينا لتكوني دائماً في القمة 🌟
                </div>
            </div>
        </div>
        
        <!-- Categories Tabs -->
        <div class="categories-tabs">
            <a href="?category=" class="tab-item <?php echo empty($category) ? 'active' : ''; ?>">
                <svg viewBox="0 0 24 24" fill="currentColor">
                    <rect x="3" y="3" width="18" height="18" rx="2"/>
                </svg>
                الكل
            </a>
            <?php foreach($categories as $cat): ?>
            <a href="?category=<?php echo urlencode($cat); ?>" class="tab-item <?php echo $category === $cat ? 'active' : ''; ?>">
                <?php echo htmlspecialchars($cat); ?>
            </a>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Posts Grid -->
    <?php if (!empty($posts)): ?>
    <div class="posts-grid">
        <?php foreach($posts as $post): 
            $image = $post['featured_image'] ?: 'https://images.unsplash.com/photo-1556228578-8c89e6adf883?w=400&h=400&fit=crop';
            $excerpt = strip_tags(substr($post['content'], 0, 150));
        ?>
        <div class="post-item" onclick='openModal(<?php echo json_encode($post, JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'>
            <img src="../<?php echo htmlspecialchars($image); ?>" 
                 alt="<?php echo htmlspecialchars($post['title']); ?>"
                 class="post-image">
            <div class="post-overlay">
                <div class="overlay-stat">
                    <svg viewBox="0 0 24 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"/>
                    </svg>
                    <span><?php echo rand(50, 500); ?></span>
                </div>
                <div class="overlay-stat">
                    <svg viewBox="0 0 24 24">
                        <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
                    </svg>
                    <span><?php echo rand(10, 100); ?></span>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div class="empty-state">
        <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>
            <circle cx="8.5" cy="8.5" r="1.5"></circle>
            <polyline points="21 15 16 10 5 21"></polyline>
        </svg>
        <h3>لا توجد منشورات</h3>
        <p>لم يتم نشر أي محتوى بعد</p>
    </div>
    <?php endif; ?>

    <!-- Modal -->
    <div class="modal" id="postModal" onclick="if(event.target === this) closeModal()">
        <button class="modal-close" onclick="closeModal()">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
        </button>
        
        <div class="modal-content">
            <div class="modal-image">
                <img id="modalImage" src="" alt="">
            </div>
            
            <div class="modal-sidebar">
                <div class="modal-header">
                    <div class="modal-avatar">R</div>
                    <div class="modal-username">روز سكين</div>
                </div>
                
                <div class="modal-body">
                    <div class="comment-item">
                        <div class="comment-avatar">R</div>
                        <div class="comment-content">
                            <div>
                                <span class="comment-username">روز سكين</span>
                                <span class="comment-text" id="modalCaption"></span>
                            </div>
                            <div class="comment-time" id="modalDate"></div>
                        </div>
                    </div>
                </div>
                
                <!-- Actions (Like, Comment) -->
                <div class="modal-actions">
                    <button class="action-btn" id="likeBtn" onclick="toggleLike()">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="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"/>
                        </svg>
                    </button>
                    <button class="action-btn" onclick="document.getElementById('commentInput').focus()">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
                        </svg>
                    </button>
                    <button class="action-btn" onclick="sharePost()">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <line x1="22" y1="2" x2="11" y2="13"></line>
                            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                        </svg>
                    </button>
                </div>
                
                <!-- Likes Count -->
                <div class="modal-likes">
                    <span id="likesCount">0</span> إعجاب
                </div>
                
                <!-- Comments Section -->
                <div class="modal-comments" id="commentsSection">
                    <!-- Comments will be loaded here -->
                </div>
                
                <!-- Comment Form -->
                <form class="comment-form" onsubmit="submitComment(event)">
                    <input type="text" 
                           class="comment-input" 
                           id="commentInput"
                           placeholder="أضف تعليقاً..."
                           autocomplete="off">
                    <button type="submit" class="comment-submit" id="commentSubmit" disabled>نشر</button>
                </form>
                
                <div class="modal-footer">
                    <div class="modal-date" id="modalDateFooter"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentPostId = null;
        let isLiked = false;
        let likesCount = 0;
        let comments = [];
        
        function openModal(post) {
            currentPostId = post.id;
            const modal = document.getElementById('postModal');
            const image = post.featured_image || 'https://images.unsplash.com/photo-1556228578-8c89e6adf883?w=800&h=800&fit=crop';
            
            document.getElementById('modalImage').src = '../' + image;
            
            // Caption (العنوان + المحتوى المختصر)
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = post.content;
            const excerpt = (tempDiv.textContent || tempDiv.innerText).substring(0, 200);
            document.getElementById('modalCaption').textContent = post.title + ' - ' + excerpt + '...';
            
            // تنسيق التاريخ
            const date = new Date(post.published_at || post.created_at);
            const dateStr = date.toLocaleDateString('ar-EG', {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            });
            document.getElementById('modalDate').textContent = dateStr;
            document.getElementById('modalDateFooter').textContent = dateStr;
            
            // Load likes and comments
            loadPostData(post.id);
            
            modal.classList.add('active');
            document.body.style.overflow = 'hidden';
        }
        
        function closeModal() {
            const modal = document.getElementById('postModal');
            modal.classList.remove('active');
            document.body.style.overflow = '';
            currentPostId = null;
            document.getElementById('commentInput').value = '';
        }
        
        function loadPostData(postId) {
            // محاكاة تحميل البيانات (في الواقع ستكون من API)
            // هنا نستخدم localStorage للتخزين المؤقت
            const savedData = localStorage.getItem('post_' + postId);
            
            if (savedData) {
                const data = JSON.parse(savedData);
                likesCount = data.likes || 0;
                isLiked = data.isLiked || false;
                comments = data.comments || [];
            } else {
                likesCount = Math.floor(Math.random() * 500) + 50;
                isLiked = false;
                comments = generateSampleComments();
            }
            
            updateLikesDisplay();
            updateCommentsDisplay();
        }
        
        function generateSampleComments() {
            const sampleComments = [
                { username: 'سارة أحمد', text: 'محتوى رائع! استفدت كثيراً 💕', time: 'منذ ساعتين' },
                { username: 'منى خالد', text: 'شكراً على المعلومات القيمة ✨', time: 'منذ 5 ساعات' },
                { username: 'ليلى محمد', text: 'ممتاز! في انتظار المزيد 🌸', time: 'منذ يوم' }
            ];
            return sampleComments.slice(0, Math.floor(Math.random() * 3) + 1);
        }
        
        function toggleLike() {
            isLiked = !isLiked;
            likesCount += isLiked ? 1 : -1;
            
            updateLikesDisplay();
            savePostData();
            
            // Animation
            const likeBtn = document.getElementById('likeBtn');
            if (isLiked) {
                likeBtn.classList.add('liked');
            } else {
                likeBtn.classList.remove('liked');
            }
        }
        
        function updateLikesDisplay() {
            document.getElementById('likesCount').textContent = likesCount.toLocaleString('ar-EG');
            const likeBtn = document.getElementById('likeBtn');
            
            if (isLiked) {
                likeBtn.classList.add('liked');
            } else {
                likeBtn.classList.remove('liked');
            }
        }
        
        function updateCommentsDisplay() {
            const commentsSection = document.getElementById('commentsSection');
            
            if (comments.length === 0) {
                commentsSection.innerHTML = '<div style="text-align: center; padding: 40px 20px; color: #8e8e8e;">لا توجد تعليقات بعد<br>كن أول من يعلق!</div>';
                return;
            }
            
            commentsSection.innerHTML = comments.map(comment => `
                <div class="comment-item">
                    <div class="comment-avatar">${comment.username.charAt(0)}</div>
                    <div class="comment-content">
                        <div>
                            <span class="comment-username">${comment.username}</span>
                            <span class="comment-text">${comment.text}</span>
                        </div>
                        <div class="comment-time">${comment.time}</div>
                    </div>
                </div>
            `).join('');
        }
        
        function submitComment(event) {
            event.preventDefault();
            
            const input = document.getElementById('commentInput');
            const text = input.value.trim();
            
            if (!text) return;
            
            <?php if (!isset($_SESSION['user_id'])): ?>
                alert('يجب تسجيل الدخول للتعليق');
                return;
            <?php endif; ?>
            
            // إضافة التعليق
            const newComment = {
                username: '<?php echo isset($_SESSION['user_name']) ? $_SESSION['user_name'] : 'مستخدم'; ?>',
                text: text,
                time: 'الآن'
            };
            
            comments.unshift(newComment);
            updateCommentsDisplay();
            savePostData();
            
            // مسح الحقل
            input.value = '';
            document.getElementById('commentSubmit').disabled = true;
            
            // Scroll to top of comments
            document.getElementById('commentsSection').scrollTop = 0;
        }
        
        function savePostData() {
            if (!currentPostId) return;
            
            const data = {
                likes: likesCount,
                isLiked: isLiked,
                comments: comments
            };
            
            localStorage.setItem('post_' + currentPostId, JSON.stringify(data));
        }
        
        function sharePost() {
            if (navigator.share) {
                navigator.share({
                    title: 'روز فيد - Roz Feed',
                    text: 'شاهدي هذا المنشور الرائع من روز فيد! 💕',
                    url: window.location.href
                }).catch(() => {});
            } else {
                // نسخ الرابط
                const url = window.location.href;
                navigator.clipboard.writeText(url).then(() => {
                    alert('تم نسخ الرابط! 📋');
                });
            }
        }
        
        // Enable/disable comment submit button
        document.getElementById('commentInput').addEventListener('input', function() {
            const submitBtn = document.getElementById('commentSubmit');
            submitBtn.disabled = this.value.trim().length === 0;
        });
        
        // Close on Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeModal();
            }
        });
        
        // Close modal when clicking outside
        document.getElementById('postModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });
    </script>
</body>
</html>
