# -*- coding: utf-8 -*-
import os
import json
import uuid
import hashlib
import datetime
import mimetypes
from functools import wraps
from flask import Flask, render_template_string, request, jsonify, session, redirect, url_for, make_response
from werkzeug.utils import secure_filename
from flask_socketio import SocketIO, emit, join_room, leave_room  # NEW: برای چت آنلاین

app = Flask(__name__)
app.secret_key = 'chatme_secret_key_instagram_like_app_2026'
app.config['SESSION_TYPE'] = 'filesystem'
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024  # 50MB max

# NEW: SocketIO برای چت لحظه‌ای
socketio = SocketIO(app, cors_allowed_origins="*", ping_timeout=60)

# ========================
# DATA STORAGE (In-memory + JSON backup) - همینطور که بود حفظ شده
# ========================
DATA_FILE = 'chatme_data.json'

def load_data():
    default_data = {
        'users': {},
        'posts': [],
        'stories': [],
        'chats': {},
        'notifications': [],
        'viewed_stories': {},
        'post_views': {}
    }
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                data = json.load(f)
                for key in default_data:
                    if key not in data:
                        data[key] = default_data[key]
                return data
        except:
            return default_data
    return default_data

def save_data(data):
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# Initialize data
DATA = load_data()
if not DATA['users']:
    # Seed users (کامل حفظ شده)
    DATA['users'] = {
        'gods._legend': {
            'email': 'demo@chat.me', 'password': hashlib.md5('123456'.encode()).hexdigest(),
            'username': 'gods._legend', 'fullName': 'Nazanin zahra', 'bio': '✨', 'avatar': None,
            'private': False, 'followers': ['B.enayati', 'moien.s', 'مهدی مرادی', 'امیرحسین سرباز'],
            'following': ['ferioonazi', 'B.enayati', 'moien.s', 'مهدی مرادی', 'امیرحسین سرباز']
        },
        'ferioonazi': {
            'email': 'feri@chat.me', 'password': hashlib.md5('123456'.encode()).hexdigest(),
            'username': 'ferioonazi', 'fullName': 'Feri', 'bio': '🎬', 'avatar': None,
            'private': False, 'followers': [], 'following': []
        },
        'B.enayati': {
            'email': 'b@chat.me', 'password': hashlib.md5('123456'.encode()).hexdigest(),
            'username': 'B.enayati', 'fullName': 'B.enayati', 'bio': '', 'avatar': None,
            'private': False, 'followers': [], 'following': []
        },
        'moien.s': {
            'email': 'moien@chat.me', 'password': hashlib.md5('123456'.encode()).hexdigest(),
            'username': 'moien.s', 'fullName': 'moien.s', 'bio': '', 'avatar': None,
            'private': False, 'followers': [], 'following': []
        },
        'مهدی مرادی': {
            'email': 'mahdi@chat.me', 'password': hashlib.md5('123456'.encode()).hexdigest(),
            'username': 'مهدی مرادی', 'fullName': 'مهدی مرادی', 'bio': 'wfldingdob', 'avatar': None,
            'private': False, 'followers': [], 'following': []
        },
        'امیرحسین سرباز': {
            'email': 'amir@chat.me', 'password': hashlib.md5('123456'.encode()).hexdigest(),
            'username': 'امیرحسین سرباز', 'fullName': 'امیرحسین سرباز', 'bio': '', 'avatar': None,
            'private': False, 'followers': [], 'following': []
        },
        'chanelandrichie': {
            'email': 'channel@chat.me', 'password': hashlib.md5('123456'.encode()).hexdigest(),
            'username': 'chanelandrichie', 'fullName': 'chanelandrichie', 'bio': '...Ani, are you ok?',
            'avatar': None, 'private': False, 'followers': [], 'following': []
        }
    }
    DATA['posts'] = [
        {'id': 1, 'user': 'chanelandrichie', 'caption': '...Ani, are you ok', 'likes': [], 'comments': [],
         'imageColor': '#e84393', 'timestamp': int(datetime.datetime.now().timestamp() * 1000) - 100000, 'media': None},
        {'id': 2, 'user': 'gods._legend', 'caption': '✨', 'likes': [], 'comments': [],
         'imageColor': '#6c5ce7', 'timestamp': int(datetime.datetime.now().timestamp() * 1000) - 50000, 'media': None}
    ]
    DATA['notifications'] = [
        {'user': 'gods._legend', 'type': 'story_share', 'text': 'Nazanin zahra حلقه فیلمی از ferioonazi ارسال کرد',
         'time': int(datetime.datetime.now().timestamp() * 1000) - 600000, 'read': False},
        {'user': 'gods._legend', 'type': 'story_share', 'text': 'B.enayati حلقه فیلمی از marziyeh_zand ارسال کرد',
         'time': int(datetime.datetime.now().timestamp() * 1000) - 500000, 'read': False},
        {'user': 'gods._legend', 'type': 'like', 'text': 'امیرحسین سرباز پیامی را پسندید',
         'time': int(datetime.datetime.now().timestamp() * 1000) - 200000, 'read': True}
    ]
    save_data(DATA)

def save_data_to_file():
    save_data(DATA)

# ========================
# NEW: WebSocket Events برای چت آنلاین و لحظه‌ای
# ========================
@socketio.on('connect')
def handle_connect():
    if 'username' in session:
        join_room(session['username'])
        print(f"🔵 {session['username']} آنلاین شد")

@socketio.on('disconnect')
def handle_disconnect():
    if 'username' in session:
        print(f"⚫ {session['username']} آفلاین شد")

@socketio.on('send_message')
def handle_send_message(data):
    """دریافت پیام و ارسال لحظه‌ای به گیرنده"""
    if 'username' not in session:
        return
    
    sender = session['username']
    receiver = data.get('receiver')
    text = data.get('text', '').strip()
    
    if not receiver or not text:
        return
    
    # ذخیره پیام در DATA (همان ساختار قبلی)
    chat_id = f"{min(sender, receiver)}_{max(sender, receiver)}"
    if chat_id not in DATA['chats']:
        DATA['chats'][chat_id] = []
    
    message = {
        'sender': sender,
        'receiver': receiver,
        'text': text,
        'time': int(datetime.datetime.now().timestamp() * 1000)
    }
    DATA['chats'][chat_id].append(message)
    
    # ذخیره نوتیفیکیشن برای پیام
    add_notification(receiver, sender, 'msg', f'{sender} به شما پیام داد 💬')
    save_data_to_file()
    
    # ارسال لحظه‌ای پیام به گیرنده (بدون رفرش صفحه)
    emit('new_message', message, room=receiver)
    emit('new_message', message, room=sender)

@socketio.on('typing')
def handle_typing(data):
    """نمایش وضعیت تایپ کردن در چت"""
    if 'username' not in session:
        return
    
    sender = session['username']
    receiver = data.get('receiver')
    is_typing = data.get('is_typing', False)
    
    if receiver:
        emit('user_typing', {'sender': sender, 'is_typing': is_typing}, room=receiver)

# ========================
# Helper Functions (همینطور که بودند حفظ شده)
# ========================
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'username' not in session:
            return jsonify({'error': 'Unauthorized', 'redirect': '/'}), 401
        return f(*args, **kwargs)
    return decorated_function

def get_current_user():
    if 'username' in session:
        return DATA['users'].get(session['username'])
    return None

def format_count(n):
    if not n:
        return '0'
    if n >= 1000000:
        return f"{n/1000000:.1f} میلیون"
    if n >= 1000:
        return f"{n/1000:.1f} هزار"
    return str(n)

def add_notification(target_user, from_user, notif_type, text):
    if target_user == from_user:
        return
    DATA['notifications'].insert(0, {
        'user': target_user,
        'type': notif_type,
        'text': text,
        'time': int(datetime.datetime.now().timestamp() * 1000),
        'read': False
    })
    if len(DATA['notifications']) > 100:
        DATA['notifications'] = DATA['notifications'][:100]
    save_data_to_file()

# ========================
# API Routes (همه APIهای اصلی حفظ شده)
# ========================
@app.route('/')
def index():
    if 'username' in session:
        return render_template_string(HTML_TEMPLATE)
    return render_template_string(HTML_TEMPLATE)

@app.route('/api/me', methods=['GET'])
@login_required
def get_me():
    user = get_current_user()
    if not user:
        return jsonify({'error': 'User not found'}), 404
    return jsonify({
        'username': user['username'],
        'fullName': user['fullName'],
        'bio': user['bio'],
        'avatar': user['avatar'],
        'private': user['private'],
        'followers': user.get('followers', []),
        'following': user.get('following', []),
        'followersCount': len(user.get('followers', [])),
        'followingCount': len(user.get('following', []))
    })

@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    email = data.get('email', '').strip().lower()
    password = data.get('password', '')
    hashed = hashlib.md5(password.encode()).hexdigest()
    for username, user in DATA['users'].items():
        if user['email'] == email and user['password'] == hashed:
            session['username'] = username
            return jsonify({'success': True, 'username': username})
    return jsonify({'error': 'ایمیل یا رمز عبور اشتباه است'}), 401

@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()
    email = data.get('email', '').strip().lower()
    fullName = data.get('fullName', '').strip()
    username = data.get('username', '').strip()
    password = data.get('password', '')
    avatar = data.get('avatar', None)
    
    if not email or not fullName or not username or not password:
        return jsonify({'error': 'همه فیلدها الزامی است'}), 400
    if username in DATA['users']:
        return jsonify({'error': 'نام کاربری تکراری است'}), 400
    
    DATA['users'][username] = {
        'email': email,
        'password': hashlib.md5(password.encode()).hexdigest(),
        'username': username,
        'fullName': fullName,
        'bio': '',
        'avatar': avatar,
        'private': False,
        'followers': [],
        'following': []
    }
    save_data_to_file()
    return jsonify({'success': True})

@app.route('/api/logout', methods=['POST'])
@login_required
def logout():
    session.pop('username', None)
    return jsonify({'success': True})

@app.route('/api/posts', methods=['GET'])
@login_required
def get_posts():
    posts = sorted(DATA['posts'], key=lambda x: x['timestamp'], reverse=True)
    for post in posts:
        if str(post['id']) not in DATA['post_views']:
            DATA['post_views'][str(post['id'])] = 1000
    return jsonify({
        'posts': [{
            'id': p['id'],
            'user': p['user'],
            'caption': p['caption'],
            'likes': p['likes'],
            'likesCount': len(p['likes']),
            'commentsCount': len(p.get('comments', [])),
            'media': p.get('media'),
            'imageColor': p.get('imageColor'),
            'timestamp': p['timestamp'],
            'isLiked': session['username'] in p['likes'],
            'views': DATA['post_views'].get(str(p['id']), 0)
        } for p in posts]
    })

@app.route('/api/posts', methods=['POST'])
@login_required
def create_post():
    data = request.get_json()
    caption = data.get('caption', '')
    media = data.get('media', None)
    
    new_post = {
        'id': int(datetime.datetime.now().timestamp() * 1000),
        'user': session['username'],
        'caption': caption,
        'likes': [],
        'comments': [],
        'imageColor': '#' + format(int(uuid.uuid4().hex[:6], 16), '06x'),
        'timestamp': int(datetime.datetime.now().timestamp() * 1000),
        'media': media
    }
    DATA['posts'].insert(0, new_post)
    DATA['post_views'][str(new_post['id'])] = 0
    save_data_to_file()
    return jsonify({'success': True, 'postId': new_post['id']})

@app.route('/api/posts/<int:post_id>/like', methods=['POST'])
@login_required
def like_post(post_id):
    post = next((p for p in DATA['posts'] if p['id'] == post_id), None)
    if not post:
        return jsonify({'error': 'Post not found'}), 404
    
    username = session['username']
    if username in post['likes']:
        post['likes'].remove(username)
        liked = False
    else:
        post['likes'].append(username)
        liked = True
        if post['user'] != username:
            add_notification(post['user'], username, 'like', f'{username} پست شما را ❤️ پسندید')
    
    save_data_to_file()
    return jsonify({'success': True, 'liked': liked, 'likesCount': len(post['likes'])})

@app.route('/api/posts/<int:post_id>/comment', methods=['POST'])
@login_required
def add_comment(post_id):
    post = next((p for p in DATA['posts'] if p['id'] == post_id), None)
    if not post:
        return jsonify({'error': 'Post not found'}), 404
    
    data = request.get_json()
    text = data.get('text', '').strip()
    if not text:
        return jsonify({'error': 'کامنت خالی است'}), 400
    
    if 'comments' not in post:
        post['comments'] = []
    post['comments'].append({
        'user': session['username'],
        'text': text,
        'time': int(datetime.datetime.now().timestamp() * 1000)
    })
    
    if post['user'] != session['username']:
        add_notification(post['user'], session['username'], 'comment', f'{session["username"]} روی پست شما کامنت گذاشت 💬')
    
    save_data_to_file()
    return jsonify({'success': True, 'commentsCount': len(post['comments'])})

@app.route('/api/posts/<int:post_id>/comments', methods=['GET'])
@login_required
def get_comments(post_id):
    post = next((p for p in DATA['posts'] if p['id'] == post_id), None)
    if not post:
        return jsonify({'error': 'Post not found'}), 404
    return jsonify({'comments': post.get('comments', [])})

@app.route('/api/posts/<int:post_id>', methods=['DELETE'])
@login_required
def delete_post(post_id):
    post = next((p for p in DATA['posts'] if p['id'] == post_id), None)
    if not post or post['user'] != session['username']:
        return jsonify({'error': 'Unauthorized'}), 403
    
    DATA['posts'] = [p for p in DATA['posts'] if p['id'] != post_id]
    save_data_to_file()
    return jsonify({'success': True})

@app.route('/api/stories', methods=['GET'])
@login_required
def get_stories():
    current_user = session['username']
    following = DATA['users'][current_user].get('following', [])
    now = int(datetime.datetime.now().timestamp() * 1000)
    twenty_four_hours = 24 * 60 * 60 * 1000
    
    # Clean old stories
    DATA['stories'] = [s for s in DATA['stories'] if now - s['timestamp'] < twenty_four_hours]
    
    user_stories = {}
    for username in [current_user] + following:
        user_stories_list = [s for s in DATA['stories'] if s['user'] == username]
        if user_stories_list:
            user_stories[username] = sorted(user_stories_list, key=lambda x: x['timestamp'], reverse=True)[0]
    
    result = []
    for username, story in user_stories.items():
        viewed_key = f"{story['user']}_{story['timestamp']}"
        result.append({
            'user': username,
            'media': story.get('media'),
            'timestamp': story['timestamp'],
            'viewed': DATA['viewed_stories'].get(viewed_key, False),
            'likesCount': len(story.get('likes', [])),
            'isLiked': session['username'] in story.get('likes', [])
        })
    
    return jsonify({'stories': result})

@app.route('/api/stories', methods=['POST'])
@login_required
def create_story():
    data = request.get_json()
    media = data.get('media')
    
    new_story = {
        'user': session['username'],
        'timestamp': int(datetime.datetime.now().timestamp() * 1000),
        'likes': [],
        'media': media
    }
    DATA['stories'].append(new_story)
    save_data_to_file()
    return jsonify({'success': True})

@app.route('/api/stories/<string:story_user>/<int:story_time>/view', methods=['POST'])
@login_required
def view_story(story_user, story_time):
    viewed_key = f"{story_user}_{story_time}"
    DATA['viewed_stories'][viewed_key] = True
    save_data_to_file()
    return jsonify({'success': True})

@app.route('/api/stories/<string:story_user>/<int:story_time>/like', methods=['POST'])
@login_required
def like_story(story_user, story_time):
    story = next((s for s in DATA['stories'] if s['user'] == story_user and s['timestamp'] == story_time), None)
    if not story:
        return jsonify({'error': 'Story not found'}), 404
    
    username = session['username']
    if 'likes' not in story:
        story['likes'] = []
    
    if username in story['likes']:
        story['likes'].remove(username)
        liked = False
    else:
        story['likes'].append(username)
        liked = True
        if story['user'] != username:
            add_notification(story['user'], username, 'story_like', f'{username} استوری شما را ❤️ پسندید')
    
    save_data_to_file()
    return jsonify({'success': True, 'liked': liked, 'likesCount': len(story['likes'])})

@app.route('/api/users/<string:username>', methods=['GET'])
@login_required
def get_user(username):
    user = DATA['users'].get(username)
    if not user:
        return jsonify({'error': 'User not found'}), 404
    
    current_user = session['username']
    user_posts = [p for p in DATA['posts'] if p['user'] == username]
    
    return jsonify({
        'username': user['username'],
        'fullName': user['fullName'],
        'bio': user['bio'],
        'avatar': user['avatar'],
        'private': user['private'],
        'followers': user.get('followers', []),
        'following': user.get('following', []),
        'followersCount': len(user.get('followers', [])),
        'followingCount': len(user.get('following', [])),
        'postsCount': len(user_posts),
        'isFollowing': current_user in user.get('followers', []),
        'posts': [{
            'id': p['id'],
            'caption': p['caption'],
            'media': p.get('media'),
            'imageColor': p.get('imageColor'),
            'likesCount': len(p['likes']),
            'commentsCount': len(p.get('comments', [])),
            'views': DATA['post_views'].get(str(p['id']), 0)
        } for p in user_posts]
    })

@app.route('/api/users/<string:username>/follow', methods=['POST'])
@login_required
def follow_user(username):
    if username == session['username']:
        return jsonify({'error': 'Cannot follow yourself'}), 400
    
    current_user_data = DATA['users'][session['username']]
    target_user_data = DATA['users'].get(username)
    
    if not target_user_data:
        return jsonify({'error': 'User not found'}), 404
    
    if 'following' not in current_user_data:
        current_user_data['following'] = []
    
    if session['username'] in target_user_data.get('followers', []):
        # Unfollow
        current_user_data['following'].remove(username)
        target_user_data['followers'].remove(session['username'])
        following = False
    else:
        # Follow
        current_user_data['following'].append(username)
        if 'followers' not in target_user_data:
            target_user_data['followers'] = []
        target_user_data['followers'].append(session['username'])
        following = True
        add_notification(username, session['username'], 'follow', f'{session["username"]} شما را دنبال کرد')
    
    save_data_to_file()
    return jsonify({'success': True, 'following': following, 'followersCount': len(target_user_data['followers'])})

@app.route('/api/user/update', methods=['POST'])
@login_required
def update_profile():
    data = request.get_json()
    user = DATA['users'][session['username']]
    
    if 'fullName' in data:
        user['fullName'] = data['fullName']
    if 'bio' in data:
        user['bio'] = data['bio']
    if 'avatar' in data:
        user['avatar'] = data['avatar']
    if 'private' in data:
        user['private'] = data['private']
    
    save_data_to_file()
    return jsonify({'success': True})

@app.route('/api/notifications', methods=['GET'])
@login_required
def get_notifications():
    user_notifs = [n for n in DATA['notifications'] if n['user'] == session['username']]
    for n in user_notifs:
        n['read'] = True
    save_data_to_file()
    return jsonify({'notifications': user_notifs})

@app.route('/api/notifications/count', methods=['GET'])
@login_required
def get_notification_count():
    count = len([n for n in DATA['notifications'] if n['user'] == session['username'] and not n['read']])
    return jsonify({'count': count})

@app.route('/api/chats', methods=['GET'])
@login_required
def get_chats():
    user_chats = {}
    for chat_user, messages in DATA['chats'].items():
        if any(m['sender'] == session['username'] or m['receiver'] == session['username'] for m in messages):
            user_chats[chat_user] = messages
    
    result = []
    for other_user, messages in user_chats.items():
        last_msg = messages[-1] if messages else None
        result.append({
            'user': other_user,
            'lastMessage': last_msg['text'] if last_msg else '',
            'lastTime': last_msg['time'] if last_msg else 0
        })
    
    return jsonify({'chats': result})

@app.route('/api/chats/<string:other_user>', methods=['GET'])
@login_required
def get_chat_messages(other_user):
    chat_id = f"{min(session['username'], other_user)}_{max(session['username'], other_user)}"
    messages = DATA['chats'].get(chat_id, [])
    return jsonify({'messages': messages})

@app.route('/api/chats/<string:other_user>', methods=['POST'])
@login_required
def send_message(other_user):
    data = request.get_json()
    text = data.get('text', '').strip()
    
    if not text:
        return jsonify({'error': 'پیام خالی است'}), 400
    
    chat_id = f"{min(session['username'], other_user)}_{max(session['username'], other_user)}"
    if chat_id not in DATA['chats']:
        DATA['chats'][chat_id] = []
    
    message = {
        'sender': session['username'],
        'receiver': other_user,
        'text': text,
        'time': int(datetime.datetime.now().timestamp() * 1000)
    }
    DATA['chats'][chat_id].append(message)
    
    add_notification(other_user, session['username'], 'msg', f'{session["username"]} به شما پیام داد 💬')
    save_data_to_file()
    
    # NEW: ارسال لحظه‌ای پیام از طریق WebSocket
    socketio.emit('new_message', message, room=other_user)
    socketio.emit('new_message', message, room=session['username'])
    
    return jsonify({'success': True, 'message': message})

@app.route('/api/explore', methods=['GET'])
@login_required
def get_explore():
    posts = sorted(DATA['posts'], key=lambda x: x['timestamp'], reverse=True)[:30]
    return jsonify({
        'posts': [{
            'id': p['id'],
            'user': p['user'],
            'media': p.get('media'),
            'imageColor': p.get('imageColor'),
            'views': DATA['post_views'].get(str(p['id']), 0)
        } for p in posts]
    })

@app.route('/api/search', methods=['GET'])
@login_required
def search_users():
    query = request.args.get('q', '').strip().lower()
    if not query:
        return jsonify({'users': []})
    
    results = []
    for username, user in DATA['users'].items():
        if query in username.lower() and username != session['username']:
            results.append({
                'username': username,
                'fullName': user['fullName'],
                'avatar': user['avatar']
            })
    return jsonify({'users': results[:20]})

# ============= NEW: ارسال پست به کاربر دیگر =============
@app.route('/api/send_post_to_user', methods=['POST'])
@login_required
def send_post_to_user():
    """ارسال یک پست برای کاربر دیگر (مثل اشتراک‌گذاری پست در چت)"""
    data = request.get_json()
    target_username = data.get('target_username', '').strip()
    post_id = data.get('post_id')
    
    if not target_username or not post_id:
        return jsonify({'error': 'نام کاربری مقصد و آیدی پست الزامی است'}), 400
    
    if target_username not in DATA['users']:
        return jsonify({'error': 'کاربر مورد نظر یافت نشد'}), 404
    
    # پیدا کردن پست
    post = next((p for p in DATA['posts'] if p['id'] == post_id), None)
    if not post:
        return jsonify({'error': 'پست یافت نشد'}), 404
    
    # ارسال پیام حاوی لینک پست به کاربر
    chat_id = f"{min(session['username'], target_username)}_{max(session['username'], target_username)}"
    if chat_id not in DATA['chats']:
        DATA['chats'][chat_id] = []
    
    post_link_message = f"📷 {session['username']} یک پست برای شما ارسال کرد: [مشاهده پست] - {post['caption'][:50]}..."
    
    message = {
        'sender': session['username'],
        'receiver': target_username,
        'text': post_link_message,
        'post_id': post_id,  # ذخیره آیدی پست برای نمایش
        'time': int(datetime.datetime.now().timestamp() * 1000)
    }
    DATA['chats'][chat_id].append(message)
    
    add_notification(target_username, session['username'], 'post_share', f'{session["username"]} یک پست برای شما ارسال کرد')
    save_data_to_file()
    
    # ارسال لحظه‌ای
    socketio.emit('new_message', message, room=target_username)
    
    return jsonify({'success': True, 'message': 'پست با موفقیت ارسال شد'})

# ============= NEW: گرفتن اطلاعات کامل یک کاربر برای جستجو =============
@app.route('/api/user_full/<string:username>', methods=['GET'])
@login_required
def get_user_full(username):
    """گرفتن اطلاعات کامل یک کاربر برای نمایش پیج"""
    user = DATA['users'].get(username)
    if not user:
        return jsonify({'error': 'User not found'}), 404
    
    current_user = session['username']
    user_posts = [p for p in DATA['posts'] if p['user'] == username]
    
    return jsonify({
        'username': user['username'],
        'fullName': user['fullName'],
        'bio': user['bio'],
        'avatar': user['avatar'],
        'private': user['private'],
        'followersCount': len(user.get('followers', [])),
        'followingCount': len(user.get('following', [])),
        'postsCount': len(user_posts),
        'isFollowing': current_user in user.get('followers', []),
        'posts': [{
            'id': p['id'],
            'caption': p['caption'],
            'media': p.get('media'),
            'imageColor': p.get('imageColor'),
            'likesCount': len(p['likes']),
            'timestamp': p['timestamp']
        } for p in user_posts[:9]]  # آخرین 9 پست
    })

# ========================
# HTML Template (کامل و بدون تغییر - فقط اضافه شدن بخش چت آنلاین و جستجو)
# ========================
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes, viewport-fit=cover">
  <title>ChatMe | چت‌می - اینستاگرام کامل</title>
  <style>
    /* تمام استایل‌های اصلی شما همینطور که بودند حفظ شده */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', 'Vazirmatn', Tahoma, sans-serif;
    }
    :root {
      --bg: #ffffff;
      --surface: #fafafa;
      --text: #262626;
      --textSecondary: #8e8e8e;
      --border: #dbdbdb;
      --accent: #0095f6;
      --accentHover: #1877f2;
      --danger: #ed4956;
      --online: #2ecc71;
      --storyGradient: linear-gradient(45deg, #f09433, #e6683c, #dc2743, #cc2366, #bc1888);
      --shadow: 0 2px 12px rgba(0,0,0,0.08);
      --cardBg: #ffffff;
      --inputBg: #fafafa;
      --overlay: rgba(0,0,0,0.65);
      --modalBg: #ffffff;
      --hoverBg: #f5f5f5;
      --fbBlue: #385185;
      --notifBlue: #e8f0fe;
    }
    body.dark {
      --bg: #0a0a0a;
      --surface: #1a1a1a;
      --text: #f5f5f5;
      --textSecondary: #a0a0a0;
      --border: #2a2a2a;
      --cardBg: #1e1e1e;
      --inputBg: #2a2a2a;
      --overlay: rgba(0,0,0,0.9);
      --modalBg: #1e1e1e;
      --hoverBg: #252525;
      --notifBlue: #1a2a3a;
    }
    body {
      background: var(--bg);
      color: var(--text);
      transition: all 0.3s ease;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      padding: 0;
    }
    #app {
      width: 100%;
      max-width: 430px;
      height: 100vh;
      max-height: 932px;
      background: var(--surface);
      display: flex;
      flex-direction: column;
      overflow: hidden;
      position: relative;
      border: 1px solid var(--border);
    }
    @media(min-width:768px) {
      #app {
        border-radius: 28px;
        box-shadow: 0 25px 60px rgba(0,0,0,0.25);
        height: 93vh;
        margin: 10px;
      }
    }
    .screen {
      display: none;
      flex-direction: column;
      height: 100%;
      width: 100%;
      overflow-y: auto;
      scrollbar-width: thin;
      scrollbar-color: var(--border) transparent;
      background: var(--bg);
    }
    .screen.active { display: flex; }
    .screen::-webkit-scrollbar { width: 4px; }
    .screen::-webkit-scrollbar-thumb { background: var(--border); border-radius: 10px; }

    .main-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 16px;
      background: var(--surface);
      border-bottom: 1px solid var(--border);
      position: sticky;
      top: 0;
      z-index: 20;
      min-height: 50px;
    }
    .header-logo {
      font-size: 26px;
      font-weight: 800;
      background: linear-gradient(45deg, #f09433, #e6683c, #dc2743, #cc2366, #bc1888);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      cursor: pointer;
    }
    .header-actions { display: flex; gap: 16px; align-items: center; }
    .header-actions i, .header-actions svg { font-size: 20px; cursor: pointer; color: var(--text); transition: transform 0.2s; position: relative; }
    .header-actions i:hover { transform: scale(1.1); }
    .header-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: var(--storyGradient);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
      font-size: 14px;
      overflow: hidden;
      cursor: pointer;
    }
    .header-avatar img { width: 100%; height: 100%; object-fit: cover; }

    .stories-section { padding: 8px 0; background: var(--surface); border-bottom: 1px solid var(--border); }
    .story-row { display: flex; gap: 10px; overflow-x: auto; padding: 6px 12px; scrollbar-width: none; }
    .story-row::-webkit-scrollbar { display: none; }
    .story-item { display: flex; flex-direction: column; align-items: center; gap: 4px; cursor: pointer; flex-shrink: 0; }
    .story-ring {
      width: 64px;
      height: 64px;
      border-radius: 50%;
      background: var(--storyGradient);
      padding: 3px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: transform 0.2s;
    }
    .story-ring:hover { transform: scale(1.06); }
    .story-ring.viewed { background: var(--border); }
    .story-ring.my-story { background: var(--border); }
    .story-img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background: var(--cardBg);
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      font-size: 18px;
      overflow: hidden;
      border: 2px solid var(--surface);
    }
    .story-img img, .story-img video { width: 100%; height: 100%; object-fit: cover; border-radius: 50%; }
    .story-username { font-size: 11px; color: var(--textSecondary); max-width: 68px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center; }
    .add-story { font-size: 28px; color: var(--textSecondary); background: var(--inputBg); width: 58px; height: 58px; border-radius: 50%; display: flex; align-items: center; justify-content: center; }

    .post {
      background: var(--cardBg);
      border-bottom: 1px solid var(--border);
      margin-bottom: 0;
      padding: 0;
    }
    .post-header { display: flex; align-items: center; gap: 10px; padding: 10px 12px; }
    .post-avatar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: var(--storyGradient);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
      font-size: 14px;
      overflow: hidden;
      cursor: pointer;
      flex-shrink: 0;
    }
    .post-avatar img { width: 100%; height: 100%; object-fit: cover; }
    .post-user-info { flex: 1; cursor: pointer; }
    .post-user-info strong { font-size: 13px; display: block; }
    .post-user-info small { font-size: 10px; color: var(--textSecondary); }
    .post-media {
      width: 100%;
      aspect-ratio: 4/5;
      max-height: 500px;
      background: #000;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      overflow: hidden;
      cursor: pointer;
    }
    .post-media img, .post-media video { width: 100%; height: 100%; object-fit: cover; }
    .post-media video { pointer-events: auto; }
    .play-icon {
      position: absolute;
      font-size: 50px;
      color: white;
      opacity: 0.9;
      pointer-events: none;
      text-shadow: 0 0 10px rgba(0,0,0,0.5);
    }
    .like-animation {
      position: absolute;
      font-size: 90px;
      color: white;
      opacity: 0;
      transform: scale(0);
      pointer-events: none;
      animation: likePop 0.9s ease forwards;
      text-shadow: 0 0 20px rgba(0,0,0,0.3);
    }
    @keyframes likePop {
      0% { opacity: 1; transform: scale(0.3); }
      40% { opacity: 1; transform: scale(1.3); }
      100% { opacity: 0; transform: scale(1.6); }
    }
    .post-actions { display: flex; gap: 14px; padding: 8px 12px; font-size: 22px; }
    .post-actions i { cursor: pointer; transition: all 0.2s; }
    .post-actions i:hover { transform: scale(1.15); }
    .post-actions i.liked { color: #ed4956; }
    .post-likes { padding: 0 12px 4px; font-size: 13px; font-weight: 600; cursor: pointer; }
    .post-caption { padding: 0 12px 4px; font-size: 13px; line-height: 1.4; }
    .post-caption strong { margin-left: 4px; }
    .post-comments-link { padding: 0 12px 8px; font-size: 12px; color: var(--textSecondary); cursor: pointer; }
    .post-time { padding: 0 12px 10px; font-size: 10px; color: var(--textSecondary); }

    .notif-tabs {
      display: flex;
      border-bottom: 1px solid var(--border);
      position: sticky;
      top: 50px;
      background: var(--surface);
      z-index: 10;
    }
    .notif-tab {
      flex: 1;
      text-align: center;
      padding: 12px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      border-bottom: 2px solid transparent;
      color: var(--textSecondary);
      transition: all 0.2s;
    }
    .notif-tab.active {
      color: var(--text);
      border-bottom: 2px solid var(--text);
    }
    .notification-item {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      padding: 14px 16px;
      border-bottom: 1px solid var(--border);
      cursor: pointer;
      transition: background 0.2s;
    }
    .notification-item:hover { background: var(--hoverBg); }
    .notification-item.unread { background: var(--notifBlue); }
    .notif-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: var(--storyGradient);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
      font-size: 16px;
      overflow: hidden;
      flex-shrink: 0;
    }
    .notif-avatar img { width: 100%; height: 100%; object-fit: cover; }
    .notif-content { flex: 1; min-width: 0; }
    .notif-content p { font-size: 13px; line-height: 1.5; word-wrap: break-word; }
    .notif-content small { font-size: 11px; color: var(--textSecondary); display: block; margin-top: 2px; }
    .notif-thumbnail {
      width: 40px;
      height: 40px;
      border-radius: 4px;
      object-fit: cover;
      flex-shrink: 0;
      background: var(--border);
    }
    .notif-follow-btn {
      background: var(--accent);
      color: white;
      border: none;
      padding: 6px 16px;
      border-radius: 6px;
      font-size: 12px;
      font-weight: 600;
      cursor: pointer;
      flex-shrink: 0;
    }
    .notif-follow-btn.following {
      background: var(--inputBg);
      color: var(--text);
      border: 1px solid var(--border);
    }

    .chat-preview { display: flex; align-items: center; gap: 12px; padding: 12px 16px; cursor: pointer; border-bottom: 1px solid var(--border); }
    .chat-preview:hover { background: var(--hoverBg); }
    .chat-avatar {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background: var(--storyGradient);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
      font-size: 18px;
      overflow: hidden;
      flex-shrink: 0;
      position: relative;
    }
    .chat-avatar img { width: 100%; height: 100%; object-fit: cover; }
    .chat-info { flex: 1; min-width: 0; }
    .chat-info strong { font-size: 14px; }
    .chat-info p { font-size: 12px; color: var(--textSecondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

    .profile-header { display: flex; align-items: center; gap: 20px; padding: 20px 16px; }
    .profile-avatar-large {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: var(--storyGradient);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
      font-size: 30px;
      overflow: hidden;
      flex-shrink: 0;
    }
    .profile-avatar-large img { width: 100%; height: 100%; object-fit: cover; }
    .profile-stats { display: flex; gap: 20px; flex: 1; justify-content: space-around; }
    .stat-item { text-align: center; cursor: pointer; }
    .stat-item strong { font-size: 18px; display: block; }
    .stat-item span { font-size: 12px; color: var(--textSecondary); }
    .profile-bio { padding: 0 16px 12px; font-size: 13px; line-height: 1.5; }
    .profile-name { padding: 0 16px 4px; font-size: 13px; font-weight: 600; }
    .profile-buttons { display: flex; gap: 8px; padding: 0 16px 16px; }
    .profile-buttons button { flex: 1; padding: 8px; font-size: 13px; border-radius: 8px; }
    .posts-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 2px; }
    .grid-item {
      aspect-ratio: 1;
      cursor: pointer;
      overflow: hidden;
      position: relative;
      background: var(--border);
    }
    .grid-item img, .grid-item video { width: 100%; height: 100%; object-fit: cover; }
    .grid-item .overlay-icon { position: absolute; top: 8px; right: 8px; color: white; font-size: 18px; text-shadow: 0 0 4px rgba(0,0,0,0.5); }
    .grid-item .delete-post-btn {
      position: absolute;
      top: 4px;
      left: 4px;
      background: rgba(237,73,86,0.9);
      color: white;
      border: none;
      border-radius: 50%;
      width: 24px;
      height: 24px;
      font-size: 12px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 5;
    }
    .grid-item .view-count {
      position: absolute;
      bottom: 4px;
      left: 6px;
      color: white;
      font-size: 11px;
      font-weight: 600;
      text-shadow: 0 0 4px rgba(0,0,0,0.7);
      display: flex;
      align-items: center;
      gap: 3px;
    }
    .grid-item .comment-count {
      position: absolute;
      bottom: 4px;
      right: 6px;
      color: white;
      font-size: 11px;
      font-weight: 600;
      text-shadow: 0 0 4px rgba(0,0,0,0.7);
      display: flex;
      align-items: center;
      gap: 3px;
    }

    .explore-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 2px; }
    .explore-item { aspect-ratio: 1; cursor: pointer; overflow: hidden; position: relative; background: var(--border); }
    .explore-item img, .explore-item video { width: 100%; height: 100%; object-fit: cover; }
    .explore-item .explore-overlay { position: absolute; bottom: 0; left: 0; right: 0; padding: 20px 8px 8px; background: linear-gradient(transparent, rgba(0,0,0,0.6)); color: white; font-size: 11px; font-weight: bold; }

    .search-container { padding: 10px 12px; position: sticky; top: 0; background: var(--surface); z-index: 10; }
    .search-input { width: 100%; padding: 10px 16px; border-radius: 10px; border: none; background: var(--inputBg); color: var(--text); font-size: 14px; outline: none; }
    .search-results { padding: 0 12px; }
    .search-user-item { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid var(--border); cursor: pointer; }

    .settings-list { padding: 0; }
    .settings-item { display: flex; justify-content: space-between; align-items: center; padding: 14px 16px; border-bottom: 1px solid var(--border); cursor: pointer; font-size: 14px; }
    .settings-item:hover { background: var(--hoverBg); }

    .modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: var(--overlay); display: none; align-items: center; justify-content: center; z-index: 200; }
    .modal.active { display: flex; }
    .modal-content { background: var(--modalBg); padding: 20px; border-radius: 18px; width: 90%; max-width: 380px; max-height: 80vh; overflow-y: auto; }
    .toast { position: fixed; top: 30px; left: 50%; transform: translateX(-50%); background: var(--accent); color: white; padding: 12px 24px; border-radius: 30px; z-index: 300; font-weight: bold; animation: toastAnim 2.5s ease forwards; }
    @keyframes toastAnim { 0% { opacity: 0; top: 0; } 15% { opacity: 1; top: 35px; } 75% { opacity: 1; top: 35px; } 100% { opacity: 0; top: 0; } }
    .toggle-switch { width: 48px; height: 26px; background: var(--border); border-radius: 13px; position: relative; cursor: pointer; transition: background 0.3s; }
    .toggle-switch.active { background: var(--accent); }
    .toggle-switch::after { content: ''; position: absolute; top: 3px; left: 3px; width: 20px; height: 20px; background: white; border-radius: 50%; transition: left 0.3s; }
    .toggle-switch.active::after { left: 25px; }
    .badge { position: absolute; top: -6px; right: -8px; background: var(--danger); color: white; border-radius: 50%; min-width: 18px; height: 18px; font-size: 10px; display: flex; align-items: center; justify-content: center; font-weight: bold; }
    .online-dot { position: absolute; bottom: 1px; right: 1px; width: 10px; height: 10px; background: var(--online); border: 2px solid white; border-radius: 50%; }
    .file-input-wrapper { position: relative; overflow: hidden; display: inline-block; width: 100%; margin: 4px 0; }
    .file-input-wrapper input[type=file] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
    .file-input-label { display: block; padding: 12px; background: var(--inputBg); border: 2px dashed var(--border); border-radius: 12px; text-align: center; cursor: pointer; color: var(--textSecondary); font-size: 13px; }
    .nav-bar { display: flex; justify-content: space-around; align-items: center; padding: 6px 4px; background: var(--surface); border-top: 1px solid var(--border); min-height: 44px; }
    .nav-bar button { background: none; border: none; font-size: 20px; cursor: pointer; color: var(--textSecondary); padding: 8px 10px; border-radius: 8px; transition: all 0.2s; position: relative; }
    .nav-bar button.active { color: var(--accent); }
    .nav-bar button:hover { color: var(--accent); }
    .followers-list { max-height: 300px; overflow-y: auto; }
    .follower-item { display: flex; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid var(--border); cursor: pointer; }

    .auth-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 20px;
      min-height: 100%;
    }
    .auth-box {
      background: var(--cardBg);
      border: 1px solid var(--border);
      padding: 30px 20px;
      width: 100%;
      max-width: 350px;
      text-align: center;
      margin-bottom: 10px;
    }
    .auth-box input {
      width: 100%;
      padding: 10px 12px;
      margin: 5px 0;
      border: 1px solid var(--border);
      border-radius: 4px;
      background: var(--inputBg);
      color: var(--text);
      font-size: 13px;
      outline: none;
    }
    .auth-box input:focus { border-color: var(--textSecondary); }
    .auth-btn {
      width: 100%;
      padding: 8px;
      margin: 10px 0;
      background: var(--accent);
      color: white;
      border: none;
      border-radius: 8px;
      font-weight: 700;
      font-size: 14px;
      cursor: pointer;
    }
    .auth-divider {
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 15px 0;
      color: var(--textSecondary);
      font-size: 12px;
    }
    .auth-divider::before, .auth-divider::after { content: ''; flex: 1; height: 1px; background: var(--border); }
    .fb-login { color: var(--fbBlue); font-weight: 600; font-size: 13px; cursor: pointer; margin: 10px 0; }
    .forgot-password { color: var(--fbBlue); font-size: 12px; cursor: pointer; margin-top: 10px; }
    .auth-switch {
      background: var(--cardBg);
      border: 1px solid var(--border);
      padding: 20px;
      width: 100%;
      max-width: 350px;
      text-align: center;
      font-size: 13px;
    }
    .auth-switch a { color: var(--accent); font-weight: 600; text-decoration: none; cursor: pointer; }
    .get-app { text-align: center; margin: 15px 0; font-size: 13px; }
    .app-badges { display: flex; gap: 8px; justify-content: center; }
    .app-badge { background: var(--text); color: var(--bg); padding: 6px 12px; border-radius: 6px; font-size: 11px; font-weight: 600; cursor: pointer; }
    .chat-bubble {
      max-width: 75%;
      padding: 8px 12px;
      border-radius: 18px;
      margin: 4px;
      font-size: 13px;
    }
    .chat-bubble.me {
      background: var(--accent);
      color: white;
      align-self: flex-end;
    }
    .chat-bubble:not(.me) {
      background: var(--inputBg);
      color: var(--text);
      align-self: flex-start;
    }
    #chatMessages {
      display: flex;
      flex-direction: column;
    }
    .typing-indicator {
      font-size: 11px;
      color: var(--textSecondary);
      padding: 4px 12px;
      font-style: italic;
    }
    @media (max-width: 380px) {
      .post-actions { gap: 10px; font-size: 20px; }
      .story-ring { width: 56px; height: 56px; }
      .profile-stats { gap: 12px; }
    }
  </style>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
</head>
<body>
<div id="app">
  <div id="authScreen" class="screen active">
    <div class="auth-container">
      <div class="auth-box">
        <div style="font-size:36px; font-weight:800; margin-bottom:20px;"><span class="header-logo" style="font-size:38px;">ChatMe</span></div>
        <div id="loginForm">
          <input type="email" id="loginEmail" placeholder="ایمیل" dir="ltr">
          <input type="password" id="loginPassword" placeholder="رمز عبور" dir="ltr">
          <button class="auth-btn" id="loginBtn">ورود</button>
          <div class="auth-divider">یا</div>
          <div class="fb-login"><i class="fab fa-facebook-square"></i> ورود با Facebook</div>
          <div class="forgot-password">رمز عبور را فراموش کرده‌اید؟</div>
        </div>
        <div id="registerForm" style="display:none;">
          <input type="email" id="regEmail" placeholder="ایمیل" dir="ltr">
          <input type="text" id="regFullName" placeholder="نام نمایشی">
          <input type="text" id="regUsername" placeholder="نام کاربری">
          <input type="password" id="regPassword" placeholder="رمز عبور" dir="ltr">
          <div class="file-input-wrapper"><div class="file-input-label">📸 عکس پروفایل</div><input type="file" id="regAvatarFile" accept="image/*"></div>
          <button class="auth-btn" id="registerBtn">ثبت نام</button>
        </div>
      </div>
      <div class="auth-switch">
        <span id="switchText">حساب ندارید؟</span> <a id="switchLink" style="cursor:pointer;">ثبت نام کنید</a>
      </div>
      <div class="get-app">دریافت برنامه</div>
      <div class="app-badges">
        <div class="app-badge">Google Play</div>
        <div class="app-badge">App Store</div>
      </div>
    </div>
  </div>

  <div id="homeScreen" class="screen">
    <div class="main-header">
      <span class="header-logo" id="logoHome">ChatMe</span>
      <div class="header-actions">
        <i class="far fa-plus-square" id="openCreatePost" title="پست جدید"></i>
        <i class="far fa-bell" id="openNotifications" style="position:relative;" title="اعلان‌ها"><span class="badge" id="notifBadge" style="display:none;">0</span></i>
        <i class="far fa-moon" id="darkModeToggle" title="تغییر تم"></i>
        <div class="header-avatar" id="headerAvatar" title="پروفایل من"></div>
      </div>
    </div>
    <div class="stories-section"><div class="story-row" id="storyRow"></div></div>
    <div id="feedPosts"></div>
  </div>

  <div id="notificationsScreen" class="screen">
    <div class="main-header">
      <span style="font-size:22px; font-weight:800;">اعلان‌ها</span>
    </div>
    <div class="notif-tabs">
      <div class="notif-tab active" data-tab="all">عمومی</div>
      <div class="notif-tab" data-tab="follows">درخواست‌ها</div>
      <div class="notif-tab" data-tab="main">اصلی</div>
    </div>
    <div id="notificationsList"></div>
  </div>

  <div id="searchScreen" class="screen">
    <div class="search-container"><input type="text" class="search-input" id="searchInput" placeholder="🔍 جستجوی کاربر..."></div>
    <div class="search-results" id="searchResults"></div>
  </div>

  <div id="exploreScreen" class="screen">
    <div class="main-header"><span style="font-size:22px; font-weight:800;">🌍 کاوش کردن</span></div>
    <div class="explore-grid" id="exploreGrid"></div>
  </div>

  <div id="chatListScreen" class="screen">
    <div class="main-header"><span style="font-size:22px; font-weight:800;">💬 پیام‌ها</span></div>
    <div id="chatListContainer"></div>
  </div>

  <div id="profileScreen" class="screen">
    <div class="main-header"><span style="font-size:20px; font-weight:800;" id="profileHeaderUsername"></span><i class="fas fa-cog" id="openSettingsFromProfile" style="font-size:20px; cursor:pointer;"></i></div>
    <div class="profile-header">
      <div class="profile-avatar-large" id="profileAvatarLarge"></div>
      <div class="profile-stats">
        <div class="stat-item"><strong id="profilePostCount">0</strong><span>پست</span></div>
        <div class="stat-item" id="followersStat"><strong id="profileFollowerCount">0</strong><span>دنبال‌کننده</span></div>
        <div class="stat-item" id="followingStat"><strong id="profileFollowingCount">0</strong><span>دنبال‌شونده</span></div>
      </div>
    </div>
    <div class="profile-name" id="profileFullName"></div>
    <div class="profile-bio" id="profileBioText"></div>
    <div class="profile-buttons"><button id="editProfileBtn">✏️ ویرایش پروفایل</button><button id="logoutBtn" class="danger">🚪 خروج</button></div>
    <div class="posts-grid" id="myPostsGrid"></div>
  </div>

  <div id="settingsScreen" class="screen">
    <div class="main-header"><span style="font-size:22px; font-weight:800;">⚙️ تنظیمات</span></div>
    <div class="settings-list">
      <div class="settings-item" id="settingsDarkMode"><span>🌙 حالت تاریک</span><div class="toggle-switch" id="darkModeSwitch"></div></div>
      <div class="settings-item" id="settingsPrivateAccount"><span>🔒 حساب خصوصی</span><div class="toggle-switch" id="privateSwitch"></div></div>
      <div class="settings-item" id="settingsClearChats"><span>🗑️ پاک کردن چت‌ها</span><i class="fas fa-chevron-left"></i></div>
      <div class="settings-item" id="settingsAbout"><span>ℹ️ درباره ChatMe</span><i class="fas fa-chevron-left"></i></div>
    </div>
  </div>

  <div class="nav-bar" id="mainNav" style="display:none;">
    <button id="navHome" class="active"><i class="fas fa-home"></i></button>
    <button id="navSearch"><i class="fas fa-search"></i></button>
    <button id="navExplore"><i class="far fa-compass"></i></button>
    <button id="navChat"><i class="fas fa-comment"></i><span class="badge" id="chatBadge" style="display:none;">0</span></button>
    <button id="navProfile"><i class="fas fa-user"></i></button>
  </div>
</div>

<div id="postModal" class="modal"><div class="modal-content"><h4>📝 پست جدید</h4><input type="text" id="postCaption" placeholder="کپشن..."><div class="file-input-wrapper"><div class="file-input-label" id="postFileLabel">📁 عکس یا ویدیو</div><input type="file" id="postMediaFile" accept="image/*,video/*"></div><div style="display:flex; gap:8px; margin-top:8px;"><button id="submitPost" style="flex:1;">📤 ارسال</button><button class="danger" id="closePostModal" style="flex:1;">لغو</button></div></div></div>
<div id="editProfileModal" class="modal"><div class="modal-content"><h4>✏️ ویرایش پروفایل</h4><input id="editFullName" placeholder="نام نمایشی"><input id="editBioInput" placeholder="بیوگرافی"><div class="file-input-wrapper"><div class="file-input-label">📸 عکس جدید</div><input type="file" id="editAvatarFile" accept="image/*"></div><div style="display:flex; gap:8px; margin-top:8px;"><button id="saveProfile">💾 ذخیره</button><button class="danger" id="closeEditProfile">لغو</button></div></div></div>
<div id="storyViewModal" class="modal"><div class="modal-content" style="text-align:center; max-width:95%; background:black; border-radius:20px; padding:10px;"><div id="storyMediaContainer" style="width:100%; max-height:70vh; border-radius:16px; overflow:hidden; display:flex; align-items:center; justify-content:center; background:#000;"></div><p id="storyUserDisplay" style="color:white; margin:10px 0;"></p><i class="far fa-heart" id="storyLikeBtn" style="font-size:28px; color:white; cursor:pointer;"></i><button id="closeStory" style="margin-top:8px; width:100%;">بستن</button></div></div>

<!-- NEW: چت دیالوگ با قابلیت تایپینگ و پیام لحظه‌ای -->
<div id="chatDetailModal" class="modal">
  <div class="modal-content" style="display:flex; flex-direction:column; height:70vh;">
    <div style="display:flex; justify-content:space-between; margin-bottom:8px;">
      <strong id="chatPartnerName"></strong>
      <div><span id="chatOnlineStatus" style="font-size:11px; color:var(--online);"></span><button class="danger" id="closeChatDetail" style="width:auto; padding:6px 12px;">✕</button></div>
    </div>
    <div id="chatMessages" style="flex:1; overflow-y:auto; display:flex; flex-direction:column; gap:4px; padding:8px;"></div>
    <div class="typing-indicator" id="typingIndicator" style="display:none;"></div>
    <div style="display:flex; gap:6px; margin-top:8px;">
      <input id="chatMessageInput" placeholder="پیام..." style="flex:1; padding:8px; border-radius:20px; border:1px solid var(--border); background:var(--inputBg);">
      <button id="sendMessageBtn" style="width:auto; padding:8px 16px; border-radius:20px;">📨</button>
    </div>
    <button id="recordVoiceBtn" style="background:var(--danger); margin-top:6px; padding:6px;">🎤 پیام صوتی</button>
  </div>
</div>

<div id="commentsModal" class="modal"><div class="modal-content"><h4>💬 کامنت‌ها</h4><div id="commentsList" style="max-height:250px; overflow-y:auto;"></div><div style="display:flex; gap:6px;"><input id="newCommentInput" placeholder="کامنت..." style="flex:1;"><button id="addCommentBtn" style="width:auto;">📝</button></div><button class="danger" id="closeComments" style="margin-top:8px;">بستن</button></div></div>
<div id="userProfileModal" class="modal"><div class="modal-content" id="userProfileContent"></div></div>
<div id="followersModal" class="modal"><div class="modal-content"><h4 id="followersModalTitle"></h4><div class="followers-list" id="followersList"></div><button class="danger" id="closeFollowersModal" style="margin-top:8px;">بستن</button></div></div>

<script>
// ========================
// FULL FRONTEND JAVASCRIPT (اصلی + قابلیت‌های جدید)
// ========================
const API_BASE = '';
let currentUser = null;
let currentTheme = localStorage.getItem('theme') === 'dark';
let currentStory = null;
let currentCommentPostId = null;
let currentActiveChat = null;

// NEW: Socket for real-time chat
let socket = null;
let typingTimeout = null;

function showToast(msg) {
  let toast = document.querySelector('.toast');
  if(toast) toast.remove();
  toast = document.createElement('div');
  toast.className = 'toast';
  toast.innerText = msg;
  document.body.appendChild(toast);
  setTimeout(() => toast.remove(), 2500);
}

async function apiCall(url, options = {}) {
  try {
    const res = await fetch(API_BASE + url, {
      ...options,
      headers: { 'Content-Type': 'application/json', ...options.headers }
    });
    if(res.status === 401) {
      sessionStorage.clear();
      window.location.reload();
      return null;
    }
    return await res.json();
  } catch(e) {
    showToast('❌ خطا در ارتباط با سرور');
    return null;
  }
}

// NEW: Initialize Socket.IO
function initSocket() {
  if(socket) socket.disconnect();
  socket = io();
  
  socket.on('connect', () => {
    console.log('✅ Connected to chat server');
  });
  
  socket.on('new_message', (message) => {
    // اگر در چت با همان فرد هستیم، پیام رو نمایش بده
    if(currentActiveChat === message.sender || currentActiveChat === message.receiver) {
      appendMessageToChat(message);
    }
    // رفرش لیست چت‌ها برای نمایش آخرین پیام
    loadChatList();
    // نوتیفیکیشن صوتی (اختیاری)
    if(currentActiveChat !== message.sender) {
      showToast(`📩 پیام جدید از ${message.sender}`);
    }
  });
  
  socket.on('user_typing', (data) => {
    if(currentActiveChat === data.sender) {
      const typingDiv = document.getElementById('typingIndicator');
      if(data.is_typing) {
        typingDiv.style.display = 'block';
        typingDiv.innerText = `${data.sender} در حال تایپ کردن...`;
      } else {
        typingDiv.style.display = 'none';
      }
    }
  });
}

function appendMessageToChat(message) {
  const container = document.getElementById('chatMessages');
  const isMe = message.sender === currentUser;
  const div = document.createElement('div');
  div.className = `chat-bubble ${isMe ? 'me' : ''}`;
  div.innerHTML = `${message.text}<br><small style="opacity:0.7;">${new Date(message.time).toLocaleString('fa-IR')}</small>`;
  container.appendChild(div);
  container.scrollTop = container.scrollHeight;
}

// Auth functions
async function login(email, password) {
  const data = await apiCall('/api/login', { method: 'POST', body: JSON.stringify({ email, password }) });
  if(data && data.success) {
    sessionStorage.setItem('user', JSON.stringify({ username: data.username }));
    currentUser = data.username;
    showToast('✅ ورود موفق');
    await loadApp();
    return true;
  } else {
    showToast(data?.error || 'خطا در ورود');
    return false;
  }
}

async function register(email, fullName, username, password, avatar) {
  const data = await apiCall('/api/register', { method: 'POST', body: JSON.stringify({ email, fullName, username, password, avatar }) });
  if(data && data.success) {
    showToast('✅ ثبت نام موفق! وارد شوید');
    return true;
  } else {
    showToast(data?.error || 'خطا در ثبت نام');
    return false;
  }
}

async function logout() {
  await apiCall('/api/logout', { method: 'POST' });
  if(socket) socket.disconnect();
  sessionStorage.clear();
  currentUser = null;
  showToast('🚪 خارج شدید');
  window.location.reload();
}

async function loadApp() {
  const stored = sessionStorage.getItem('user');
  if(!stored) {
    document.getElementById('authScreen').classList.add('active');
    document.getElementById('mainNav').style.display = 'none';
    return;
  }
  currentUser = JSON.parse(stored).username;
  document.getElementById('authScreen').classList.remove('active');
  document.getElementById('mainNav').style.display = 'flex';
  if(currentTheme) document.body.classList.add('dark');
  
  // Initialize WebSocket
  initSocket();
  
  await Promise.all([loadNotificationsCount(), loadFeed(), loadStories(), loadProfile(), loadChatList(), loadExplore()]);
  switchScreen(document.getElementById('homeScreen'));
  document.getElementById('navHome').classList.add('active');
}

async function loadFeed() {
  const data = await apiCall('/api/posts');
  if(!data) return;
  const container = document.getElementById('feedPosts');
  container.innerHTML = '';
  for(const post of data.posts) {
    const userData = await apiCall(`/api/users/${post.user}`);
    const avatar = userData?.avatar ? `<img src="${userData.avatar}" alt="a">` : (post.user[0] || '?').toUpperCase();
    const isLiked = post.isLiked;
    const div = document.createElement('div');
    div.className = 'post';
    div.innerHTML = `
      <div class="post-header">
        <div class="post-avatar view-profile" data-user="${post.user}">${avatar}</div>
        <div class="post-user-info view-profile" data-user="${post.user}"><strong>${post.user}</strong><small>${new Date(post.timestamp).toLocaleString('fa-IR')}</small></div>
        <i class="fas fa-ellipsis-h" style="cursor:pointer;"></i>
      </div>
      <div class="post-media" data-postid="${post.id}">
        ${post.media ? (post.media.type === 'video' ? `<video src="${post.media.data}" loop playsinline preload="auto"></video><div class="play-icon">▶️</div>` : `<img src="${post.media.data}" alt="post">`) : `<div style="font-size:60px;color:white;background:${post.imageColor};display:flex;align-items:center;justify-content:center;height:100%;">📷</div>`}
      </div>
      <div class="post-actions">
        <i class="fa${isLiked ? 's' : 'r'} fa-heart like-btn ${isLiked ? 'liked' : ''}" data-id="${post.id}"></i>
        <i class="far fa-comment comment-btn" data-id="${post.id}"></i>
        <i class="far fa-paper-plane share-btn" data-id="${post.id}" title="ارسال پست برای کاربر دیگر"></i>
      </div>
      <div class="post-likes">${formatCount(post.likesCount)} پسند</div>
      <div class="post-caption"><strong>${post.user}</strong> ${post.caption}</div>
      <div class="post-comments-link comment-btn" data-id="${post.id}">مشاهده ${post.commentsCount} کامنت</div>
      <div class="post-time">${new Date(post.timestamp).toLocaleString('fa-IR')} · ${formatCount(post.views)} بازدید</div>
    `;
    container.appendChild(div);
  }
  attachPostEvents();
}

// NEW: ارسال پست به کاربر دیگر
async function sharePostToUser(postId) {
  const targetUsername = prompt('نام کاربری کاربر مورد نظر برای ارسال پست:');
  if(!targetUsername || targetUsername === currentUser) {
    showToast('❌ نام کاربری نامعتبر');
    return;
  }
  
  const data = await apiCall('/api/send_post_to_user', {
    method: 'POST',
    body: JSON.stringify({ target_username: targetUsername, post_id: postId })
  });
  
  if(data && data.success) {
    showToast(`✅ پست برای ${targetUsername} ارسال شد`);
  } else {
    showToast('❌ خطا در ارسال پست');
  }
}

function attachPostEvents() {
  document.querySelectorAll('.like-btn').forEach(btn => {
    btn.onclick = async (e) => {
      e.stopPropagation();
      const id = parseInt(btn.dataset.id);
      const data = await apiCall(`/api/posts/${id}/like`, { method: 'POST' });
      if(data && data.success) {
        if(data.liked) btn.classList.add('liked'), btn.classList.replace('far', 'fas');
        else btn.classList.remove('liked'), btn.classList.replace('fas', 'far');
        const likesSpan = btn.closest('.post').querySelector('.post-likes');
        likesSpan.innerText = formatCount(data.likesCount) + ' پسند';
      }
    };
  });
  
  document.querySelectorAll('.post-media').forEach(el => {
    const vid = el.querySelector('video');
    if(vid) {
      vid.muted = false;
      const playIcon = el.querySelector('.play-icon');
      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if(entry.isIntersecting) { vid.play().catch(()=>{}); if(playIcon) playIcon.style.display = 'none'; }
          else { vid.pause(); if(playIcon) playIcon.style.display = 'block'; }
        });
      }, { threshold: 0.6 });
      observer.observe(el);
      el.onclick = (e) => {
        if(vid.paused) { vid.play(); if(playIcon) playIcon.style.display = 'none'; }
        else { vid.pause(); if(playIcon) playIcon.style.display = 'block'; }
      };
    }
    el.ondblclick = async (e) => {
      const id = parseInt(el.dataset.postid);
      const data = await apiCall(`/api/posts/${id}/like`, { method: 'POST' });
      if(data && data.liked) {
        const heart = document.createElement('div');
        heart.className = 'like-animation';
        heart.innerHTML = '❤️';
        el.appendChild(heart);
        setTimeout(() => heart.remove(), 900);
        const btn = document.querySelector(`.like-btn[data-id="${id}"]`);
        if(btn) btn.classList.add('liked'), btn.classList.replace('far', 'fas');
        const likesSpan = btn.closest('.post').querySelector('.post-likes');
        likesSpan.innerText = formatCount(data.likesCount) + ' پسند';
      }
    };
  });
  
  document.querySelectorAll('.comment-btn').forEach(btn => {
    btn.onclick = (e) => { e.stopPropagation(); openComments(parseInt(btn.dataset.id)); };
  });
  
  // NEW: دکمه اشتراک‌گذاری پست
  document.querySelectorAll('.share-btn').forEach(btn => {
    btn.onclick = (e) => { 
      e.stopPropagation(); 
      sharePostToUser(parseInt(btn.dataset.id)); 
    };
  });
  
  document.querySelectorAll('.view-profile').forEach(el => {
    el.onclick = () => { const u = el.dataset.user; if(u && u !== currentUser) viewUserProfile(u); };
  });
}

async function openComments(postId) {
  currentCommentPostId = postId;
  const data = await apiCall(`/api/posts/${postId}/comments`);
  if(!data) return;
  const list = document.getElementById('commentsList');
  list.innerHTML = '';
  if(data.comments.length) {
    data.comments.forEach(c => {
      list.innerHTML += `<div style="padding:6px 0;border-bottom:1px solid var(--border);"><strong>${c.user}</strong> ${c.text} <small>${new Date(c.time).toLocaleString('fa-IR')}</small></div>`;
    });
  } else list.innerHTML = '<p style="color:var(--textSecondary);text-align:center;">کامنتی نیست</p>';
  document.getElementById('commentsModal').classList.add('active');
}

async function addComment() {
  const text = document.getElementById('newCommentInput').value.trim();
  if(!text || !currentCommentPostId) return;
  const data = await apiCall(`/api/posts/${currentCommentPostId}/comment`, { method: 'POST', body: JSON.stringify({ text }) });
  if(data && data.success) {
    document.getElementById('newCommentInput').value = '';
    openComments(currentCommentPostId);
    loadFeed();
  }
}

async function loadStories() {
  const data = await apiCall('/api/stories');
  if(!data) return;
  const row = document.getElementById('storyRow');
  row.innerHTML = '';
  
  const addDiv = document.createElement('div');
  addDiv.className = 'story-item';
  addDiv.innerHTML = `<div class="story-ring my-story"><div class="story-img add-story">+</div></div><span class="story-username">استوری</span>`;
  addDiv.onclick = () => {
    const inp = document.createElement('input');
    inp.type = 'file';
    inp.accept = 'image/*,video/*';
    inp.onchange = async (e) => {
      const f = e.target.files[0];
      if(!f) return;
      const reader = new FileReader();
      reader.onload = async (ev) => {
        const media = { type: f.type.startsWith('video/') ? 'video' : 'image', data: ev.target.result };
        await apiCall('/api/stories', { method: 'POST', body: JSON.stringify({ media }) });
        showToast('📸 استوری اضافه شد');
        loadStories();
        loadFeed();
      };
      reader.readAsDataURL(f);
    };
    inp.click();
  };
  row.appendChild(addDiv);
  
  for(const story of data.stories) {
    const div = document.createElement('div');
    div.className = 'story-item';
    div.innerHTML = `<div class="story-ring ${story.viewed ? 'viewed' : ''}"><div class="story-img">${story.media?.type === 'image' ? `<img src="${story.media.data}" alt="s">` : (story.user[0] || '?').toUpperCase()}</div></div><span class="story-username">${story.user}</span>`;
    div.onclick = () => viewStory(story);
    row.appendChild(div);
  }
}

async function viewStory(story) {
  await apiCall(`/api/stories/${story.user}/${story.timestamp}/view`, { method: 'POST' });
  currentStory = story;
  document.getElementById('storyViewModal').classList.add('active');
  document.getElementById('storyUserDisplay').innerText = story.user;
  const cont = document.getElementById('storyMediaContainer');
  if(story.media) {
    if(story.media.type === 'video') cont.innerHTML = `<video src="${story.media.data}" controls autoplay style="width:100%;max-height:70vh;border-radius:16px;"></video>`;
    else cont.innerHTML = `<img src="${story.media.data}" style="width:100%;max-height:70vh;object-fit:cover;border-radius:16px;">`;
  } else cont.innerHTML = '<div style="font-size:80px;color:white;">📸</div>';
  const likeBtn = document.getElementById('storyLikeBtn');
  likeBtn.className = story.isLiked ? 'fas fa-heart liked' : 'far fa-heart';
}

async function likeStory() {
  if(!currentStory) return;
  const data = await apiCall(`/api/stories/${currentStory.user}/${currentStory.timestamp}/like`, { method: 'POST' });
  if(data && data.success) {
    const likeBtn = document.getElementById('storyLikeBtn');
    if(data.liked) likeBtn.className = 'fas fa-heart liked';
    else likeBtn.className = 'far fa-heart';
  }
}

async function loadProfile() {
  const data = await apiCall('/api/me');
  if(!data) return;
  document.getElementById('profileHeaderUsername').innerText = data.username;
  document.getElementById('profileAvatarLarge').innerHTML = data.avatar ? `<img src="${data.avatar}" alt="a">` : data.username[0].toUpperCase();
  document.getElementById('profilePostCount').innerText = '0';
  document.getElementById('profileFollowerCount').innerText = data.followersCount;
  document.getElementById('profileFollowingCount').innerText = data.followingCount;
  document.getElementById('profileFullName').innerText = data.fullName || '';
  document.getElementById('profileBioText').innerText = data.bio || '';
  document.getElementById('followersStat').onclick = () => showFollowList('followers');
  document.getElementById('followingStat').onclick = () => showFollowList('following');
  
  const userData = await apiCall(`/api/users/${data.username}`);
  if(userData) {
    document.getElementById('profilePostCount').innerText = userData.postsCount;
    const grid = document.getElementById('myPostsGrid');
    grid.innerHTML = '';
    if(!userData.posts.length) grid.innerHTML = '<p style="grid-column:1/-1;text-align:center;padding:40px;color:var(--textSecondary);">پستی نیست 📷</p>';
    else {
      for(const p of userData.posts) {
        const div = document.createElement('div');
        div.className = 'grid-item';
        if(p.media?.type === 'image') div.innerHTML = `<img src="${p.media.data}" alt="p">`;
        else if(p.media?.type === 'video') div.innerHTML = `<video src="${p.media.data}" muted></video><div class="overlay-icon">▶️</div>`;
        else { div.style.background = p.imageColor; div.innerHTML = '<div class="overlay-icon">📷</div>'; }
        div.innerHTML += `<div class="view-count"><i class="fas fa-play"></i> ${formatCount(p.views)}</div>`;
        div.innerHTML += `<div class="comment-count"><i class="fas fa-comment"></i> ${p.commentsCount}</div>`;
        const delBtn = document.createElement('button');
        delBtn.className = 'delete-post-btn';
        delBtn.innerHTML = '🗑️';
        delBtn.onclick = async (e) => {
          e.stopPropagation();
          if(confirm('حذف شود؟')) {
            await apiCall(`/api/posts/${p.id}`, { method: 'DELETE' });
            loadProfile();
            loadFeed();
            loadExplore();
            showToast('🗑️ پست حذف شد');
          }
        };
        div.appendChild(delBtn);
        div.onclick = () => { switchScreen(document.getElementById('homeScreen')); document.getElementById('navHome').classList.add('active'); setTimeout(() => { const el = document.querySelector(`.post-media[data-postid="${p.id}"]`); if(el) el.scrollIntoView({ behavior: 'smooth' }); }, 100); };
        grid.appendChild(div);
      }
    }
  }
}

async function loadExplore() {
  const data = await apiCall('/api/explore');
  if(!data) return;
  const grid = document.getElementById('exploreGrid');
  grid.innerHTML = '';
  for(const post of data.posts) {
    const div = document.createElement('div');
    div.className = 'explore-item';
    if(post.media?.type === 'image') div.innerHTML = `<img src="${post.media.data}" alt="e"><div class="explore-overlay">${formatCount(post.views)} <i class="fas fa-play"></i></div>`;
    else if(post.media?.type === 'video') div.innerHTML = `<video src="${post.media.data}" muted loop></video><div class="explore-overlay">▶️ ${formatCount(post.views)}</div>`;
    else { div.style.background = post.imageColor; div.innerHTML = `<div class="explore-overlay">📷 ${post.user}</div>`; }
    div.onclick = () => { switchScreen(document.getElementById('homeScreen')); document.getElementById('navHome').classList.add('active'); setTimeout(() => { const el = document.querySelector(`.post-media[data-postid="${post.id}"]`); if(el) el.scrollIntoView({ behavior: 'smooth' }); }, 100); };
    grid.appendChild(div);
  }
}

async function loadChatList() {
  const data = await apiCall('/api/chats');
  if(!data) return;
  const container = document.getElementById('chatListContainer');
  container.innerHTML = '';
  if(!data.chats.length) { container.innerHTML = '<p style="text-align:center;padding:40px;color:var(--textSecondary);">چتی نیست 💬</p>'; return; }
  for(const chat of data.chats) {
    const div = document.createElement('div');
    div.className = 'chat-preview';
    const userData = await apiCall(`/api/users/${chat.user}`);
    const avatar = userData?.avatar ? `<img src="${userData.avatar}" alt="a">` : (chat.user[0] || '?').toUpperCase();
    div.innerHTML = `<div class="chat-avatar">${avatar}</div><div class="chat-info"><strong>${chat.user}</strong><p>${chat.lastMessage?.substring(0, 40) || ''}</p></div>`;
    div.onclick = () => openChat(chat.user);
    container.appendChild(div);
  }
}

// NEW: چت واقعی با WebSocket
async function openChat(otherUser) {
  currentActiveChat = otherUser;
  
  // دریافت تاریخچه پیام‌ها
  const data = await apiCall(`/api/chats/${otherUser}`);
  if(!data) return;
  
  document.getElementById('chatDetailModal').classList.add('active');
  document.getElementById('chatPartnerName').innerHTML = otherUser;
  
  const container = document.getElementById('chatMessages');
  container.innerHTML = '';
  for(const msg of data.messages) {
    const isMe = msg.sender === currentUser;
    const bubble = document.createElement('div');
    bubble.className = `chat-bubble ${isMe ? 'me' : ''}`;
    bubble.innerHTML = `${msg.text}<br><small style="opacity:0.7;">${new Date(msg.time).toLocaleString('fa-IR')}</small>`;
    container.appendChild(bubble);
  }
  container.scrollTop = container.scrollHeight;
  
  // ریست کردن تایپینگ ایندیکاتور
  document.getElementById('typingIndicator').style.display = 'none';
  document.getElementById('chatMessageInput').focus();
}

async function sendMessage() {
  const text = document.getElementById('chatMessageInput').value.trim();
  if(!text || !currentActiveChat) return;
  
  // ارسال پیام به سرور (هم از طریق REST و هم WebSocket بعداً)
  const data = await apiCall(`/api/chats/${currentActiveChat}`, { 
    method: 'POST', 
    body: JSON.stringify({ text }) 
  });
  
  if(data && data.success) {
    document.getElementById('chatMessageInput').value = '';
    // WebSocket قبلاً پیام را ارسال کرده، فقط صفحه رو بروز می‌کنیم
    await openChat(currentActiveChat);
    loadChatList();
    loadNotificationsCount();
  }
}

// NEW: ارسال وضعیت تایپ کردن
function sendTypingStatus(isTyping) {
  if(!currentActiveChat || !socket) return;
  socket.emit('typing', { receiver: currentActiveChat, is_typing: isTyping });
}

async function loadNotificationsCount() {
  const data = await apiCall('/api/notifications/count');
  if(data) {
    const badge = document.getElementById('notifBadge');
    if(data.count > 0) { badge.style.display = 'flex'; badge.innerText = data.count > 99 ? '99+' : data.count; }
    else badge.style.display = 'none';
  }
}

async function loadNotifications() {
  const data = await apiCall('/api/notifications');
  if(!data) return;
  const container = document.getElementById('notificationsList');
  container.innerHTML = '';
  if(!data.notifications.length) { container.innerHTML = '<p style="text-align:center;padding:40px;color:var(--textSecondary);">اعلانی نیست</p>'; return; }
  for(const n of data.notifications) {
    const div = document.createElement('div');
    div.className = 'notification-item';
    const avatar = n.user[0].toUpperCase();
    div.innerHTML = `<div class="notif-avatar">${avatar}</div><div class="notif-content"><p>${n.text}</p><small>${new Date(n.time).toLocaleString('fa-IR')}</small></div>`;
    container.appendChild(div);
  }
  await loadNotificationsCount();
}

// NEW: جستجوی پیشرفته کاربران
async function searchUsers() {
  const query = document.getElementById('searchInput').value.trim();
  if(!query) {
    document.getElementById('searchResults').innerHTML = '';
    return;
  }
  
  const data = await apiCall(`/api/search?q=${encodeURIComponent(query)}`);
  if(data && data.users) {
    const resultsDiv = document.getElementById('searchResults');
    resultsDiv.innerHTML = '';
    for(const user of data.users) {
      const userDiv = document.createElement('div');
      userDiv.className = 'search-user-item';
      userDiv.innerHTML = `
        <div class="post-avatar">${user.avatar ? `<img src="${user.avatar}" alt="a">` : (user.username[0] || '?').toUpperCase()}</div>
        <div style="flex:1;">
          <strong>${user.username}</strong><br>
          <small style="color:var(--textSecondary)">${user.fullName || ''}</small>
        </div>
        <button class="view-profile-btn" data-user="${user.username}" style="background:var(--accent);color:white;border:none;padding:6px 12px;border-radius:8px;">مشاهده</button>
      `;
      userDiv.querySelector('.view-profile-btn').onclick = () => viewUserProfile(user.username);
      resultsDiv.appendChild(userDiv);
    }
  }
}

async function viewUserProfile(username) {
  const userData = await apiCall(`/api/user_full/${username}`);
  if(!userData) return;
  
  const isFollowing = userData.isFollowing;
  const modal = document.getElementById('userProfileModal');
  const content = document.getElementById('userProfileContent');
  content.innerHTML = `
    <div style="display:flex; gap:12px; align-items:center; margin-bottom:12px;">
      <div class="profile-avatar-large" style="width:60px;height:60px;font-size:22px;">${userData.avatar ? `<img src="${userData.avatar}" alt="a">` : (userData.username[0] || '?').toUpperCase()}</div>
      <div style="flex:1;">
        <h4>${userData.username}</h4>
        <p style="font-size:12px;">${userData.fullName || ''}</p>
        <p style="font-size:12px;color:var(--textSecondary);">${userData.bio || ''}</p>
        <p style="font-size:11px;">${userData.followersCount} دنبال‌کننده · ${userData.followingCount} دنبال‌شونده</p>
      </div>
    </div>
    <div style="display:flex; gap:8px; margin-bottom:12px;">
      <button id="followUserBtn" style="flex:1;">${isFollowing ? '✅ دنبال شده' : '➕ دنبال کردن'}</button>
      <button id="messageUserBtn" class="secondary" style="flex:1;">💬 پیام</button>
      <button id="sendPostToUserBtn" style="flex:1;">📷 ارسال پست</button>
    </div>
    <div class="posts-grid" style="max-height:200px; overflow-y:auto; display:grid; grid-template-columns:repeat(3,1fr); gap:2px;">
      ${userData.posts.map(p => `<div class="grid-item" style="background:${p.imageColor || '#ccc'}"><img src="${p.media?.data || ''}" style="width:100%;height:100%;object-fit:cover;" onerror="this.style.display='none'"><div class="view-count">❤️ ${p.likesCount}</div></div>`).join('')}
    </div>
    <button class="danger" id="closeUserProfile" style="margin-top:8px;">بستن</button>
  `;
  modal.classList.add('active');
  
  document.getElementById('followUserBtn').onclick = async () => {
    await apiCall(`/api/users/${username}/follow`, { method: 'POST' });
    viewUserProfile(username);
    loadProfile();
    loadFeed();
  };
  
  document.getElementById('messageUserBtn').onclick = () => {
    modal.classList.remove('active');
    openChat(username);
  };
  
  // NEW: ارسال پست به کاربر از داخل پیج ایشان
  document.getElementById('sendPostToUserBtn').onclick = async () => {
    const postId = prompt('آیدی پستی که می‌خواهید ارسال کنید را وارد کنید:');
    if(postId) {
      const sendData = await apiCall('/api/send_post_to_user', {
        method: 'POST',
        body: JSON.stringify({ target_username: username, post_id: parseInt(postId) })
      });
      if(sendData && sendData.success) showToast(`✅ پست برای ${username} ارسال شد`);
      else showToast('❌ پست یافت نشد');
    }
  };
  
  document.getElementById('closeUserProfile').onclick = () => modal.classList.remove('active');
}

async function showFollowList(type) {
  const userData = await apiCall('/api/me');
  if(!userData) return;
  const list = type === 'followers' ? userData.followers : userData.following;
  document.getElementById('followersModalTitle').innerText = type === 'followers' ? 'دنبال‌کننده‌ها' : 'دنبال‌شونده‌ها';
  const container = document.getElementById('followersList');
  container.innerHTML = '';
  if(!list.length) container.innerHTML = '<p style="text-align:center;padding:20px;color:var(--textSecondary);">لیست خالی است</p>';
  else {
    for(const username of list) {
      const user = await apiCall(`/api/users/${username}`);
      const div = document.createElement('div');
      div.className = 'follower-item';
      div.innerHTML = `<div class="post-avatar">${user?.avatar ? `<img src="${user.avatar}" alt="a">` : (username[0] || '?').toUpperCase()}</div><div style="flex:1;"><strong>${username}</strong><br><small>${user?.fullName || ''}</small></div>`;
      div.onclick = () => { document.getElementById('followersModal').classList.remove('active'); viewUserProfile(username); };
      container.appendChild(div);
    }
  }
  document.getElementById('followersModal').classList.add('active');
}

async function createPost(caption, media) {
  const data = await apiCall('/api/posts', { method: 'POST', body: JSON.stringify({ caption, media }) });
  if(data && data.success) {
    loadFeed();
    loadExplore();
    loadProfile();
    showToast('✅ منتشر شد');
    return true;
  }
  return false;
}

async function updateProfile(fullName, bio, avatar) {
  const data = await apiCall('/api/user/update', { method: 'POST', body: JSON.stringify({ fullName, bio, avatar }) });
  if(data && data.success) {
    loadProfile();
    showToast('✅ به‌روز شد');
    return true;
  }
  return false;
}

function formatCount(n) { if(!n) return '0'; if(n>=1000000) return (n/1000000).toFixed(1)+' میلیون'; if(n>=1000) return (n/1000).toFixed(1)+' هزار'; return n.toString(); }

function switchScreen(screen) {
  document.querySelectorAll('.screen').forEach(s => s.classList.remove('active'));
  screen.classList.add('active');
}

// Event Listeners
document.getElementById('switchLink').onclick = () => {
  const login = document.getElementById('loginForm');
  const register = document.getElementById('registerForm');
  const switchText = document.getElementById('switchText');
  const switchLink = document.getElementById('switchLink');
  if(login.style.display === 'none') {
    login.style.display = 'block';
    register.style.display = 'none';
    switchText.innerText = 'حساب ندارید؟';
    switchLink.innerText = 'ثبت نام کنید';
  } else {
    login.style.display = 'none';
    register.style.display = 'block';
    switchText.innerText = 'حساب دارید؟';
    switchLink.innerText = 'ورود کنید';
  }
};

document.getElementById('loginBtn').onclick = async () => {
  const email = document.getElementById('loginEmail').value.trim().toLowerCase();
  const password = document.getElementById('loginPassword').value;
  await login(email, password);
};

document.getElementById('registerBtn').onclick = async () => {
  const email = document.getElementById('regEmail').value.trim().toLowerCase();
  const fullName = document.getElementById('regFullName').value.trim();
  const username = document.getElementById('regUsername').value.trim();
  const password = document.getElementById('regPassword').value;
  const file = document.getElementById('regAvatarFile').files[0];
  let avatar = null;
  if(file) {
    const reader = new FileReader();
    avatar = await new Promise(resolve => { reader.onload = e => resolve(e.target.result); reader.readAsDataURL(file); });
  }
  await register(email, fullName, username, password, avatar);
};

document.getElementById('navHome').onclick = () => { switchScreen(document.getElementById('homeScreen')); document.getElementById('navHome').classList.add('active'); loadFeed(); loadStories(); };
document.getElementById('navSearch').onclick = () => { switchScreen(document.getElementById('searchScreen')); document.getElementById('navSearch').classList.add('active'); };
document.getElementById('navExplore').onclick = () => { switchScreen(document.getElementById('exploreScreen')); document.getElementById('navExplore').classList.add('active'); loadExplore(); };
document.getElementById('navChat').onclick = () => { switchScreen(document.getElementById('chatListScreen')); document.getElementById('navChat').classList.add('active'); loadChatList(); };
document.getElementById('navProfile').onclick = () => { switchScreen(document.getElementById('profileScreen')); document.getElementById('navProfile').classList.add('active'); loadProfile(); };
document.getElementById('openNotifications').onclick = () => { switchScreen(document.getElementById('notificationsScreen')); loadNotifications(); };
document.getElementById('openSettingsFromProfile').onclick = () => switchScreen(document.getElementById('settingsScreen'));
document.getElementById('logoHome').onclick = () => { switchScreen(document.getElementById('homeScreen')); document.getElementById('navHome').classList.add('active'); loadFeed(); };
document.getElementById('headerAvatar').onclick = () => { switchScreen(document.getElementById('profileScreen')); document.getElementById('navProfile').classList.add('active'); loadProfile(); };

document.getElementById('openCreatePost').onclick = () => document.getElementById('postModal').classList.add('active');
document.getElementById('closePostModal').onclick = () => document.getElementById('postModal').classList.remove('active');
let pendingPostMedia = null;
document.getElementById('postMediaFile').onchange = (e) => {
  const f = e.target.files[0];
  if(!f) { pendingPostMedia = null; document.getElementById('postFileLabel').innerText = '📁 عکس یا ویدیو'; return; }
  document.getElementById('postFileLabel').innerText = `✅ ${f.name.substring(0,25)}`;
  const reader = new FileReader();
  reader.onload = (ev) => { pendingPostMedia = { type: f.type.startsWith('video/') ? 'video' : 'image', data: ev.target.result }; };
  reader.readAsDataURL(f);
};
document.getElementById('submitPost').onclick = async () => {
  const cap = document.getElementById('postCaption').value.trim();
  if(!cap && !pendingPostMedia) return showToast('❌ کپشن یا فایل الزامی');
  await createPost(cap || '', pendingPostMedia);
  pendingPostMedia = null;
  document.getElementById('postCaption').value = '';
  document.getElementById('postMediaFile').value = '';
  document.getElementById('postFileLabel').innerText = '📁 عکس یا ویدیو';
  document.getElementById('postModal').classList.remove('active');
};

document.getElementById('editProfileBtn').onclick = () => {
  document.getElementById('editFullName').value = '';
  document.getElementById('editBioInput').value = '';
  document.getElementById('editProfileModal').classList.add('active');
};
document.getElementById('saveProfile').onclick = async () => {
  const fullName = document.getElementById('editFullName').value.trim();
  const bio = document.getElementById('editBioInput').value.trim();
  const file = document.getElementById('editAvatarFile').files[0];
  let avatar = null;
  if(file) {
    const reader = new FileReader();
    avatar = await new Promise(resolve => { reader.onload = e => resolve(e.target.result); reader.readAsDataURL(file); });
  }
  await updateProfile(fullName, bio, avatar);
  document.getElementById('editProfileModal').classList.remove('active');
};
document.getElementById('closeEditProfile').onclick = () => document.getElementById('editProfileModal').classList.remove('active');
document.getElementById('logoutBtn').onclick = async () => await logout();

document.getElementById('closeStory').onclick = () => document.getElementById('storyViewModal').classList.remove('active');
document.getElementById('storyLikeBtn').onclick = likeStory;
document.getElementById('closeComments').onclick = () => document.getElementById('commentsModal').classList.remove('active');
document.getElementById('addCommentBtn').onclick = addComment;

// NEW: رویدادهای چت
document.getElementById('sendMessageBtn').onclick = sendMessage;
document.getElementById('chatMessageInput').onkeypress = (e) => { if(e.key === 'Enter') sendMessage(); };
document.getElementById('chatMessageInput').oninput = (e) => {
  sendTypingStatus(true);
  if(typingTimeout) clearTimeout(typingTimeout);
  typingTimeout = setTimeout(() => sendTypingStatus(false), 1000);
};
document.getElementById('recordVoiceBtn').onclick = async () => {
  if(!currentActiveChat) return;
  await apiCall(`/api/chats/${currentActiveChat}`, { method: 'POST', body: JSON.stringify({ text: '🎤 پیام صوتی' }) });
  openChat(currentActiveChat);
  loadChatList();
  showToast('🎤 ویس ارسال شد');
};
document.getElementById('closeChatDetail').onclick = () => document.getElementById('chatDetailModal').classList.remove('active');
document.getElementById('closeFollowersModal').onclick = () => document.getElementById('followersModal').classList.remove('active');

// NEW: جستجو
document.getElementById('searchInput').oninput = searchUsers;

// Theme
function toggleDark() {
  currentTheme = !currentTheme;
  document.body.classList.toggle('dark', currentTheme);
  localStorage.setItem('theme', currentTheme ? 'dark' : 'light');
  document.getElementById('darkModeSwitch').className = currentTheme ? 'toggle-switch active' : 'toggle-switch';
  document.getElementById('darkModeToggle').className = currentTheme ? 'fas fa-sun' : 'far fa-moon';
}
document.getElementById('darkModeToggle').onclick = toggleDark;
document.getElementById('settingsDarkMode').onclick = toggleDark;
document.getElementById('darkModeSwitch').className = currentTheme ? 'toggle-switch active' : 'toggle-switch';
document.getElementById('darkModeToggle').className = currentTheme ? 'fas fa-sun' : 'far fa-moon';

document.getElementById('settingsClearChats').onclick = () => { if(confirm('همه چت‌ها پاک شوند؟')) { showToast('🗑️ پاک شد'); } };
document.getElementById('settingsAbout').onclick = () => showToast('ℹ️ ChatMe Instagram v6.0 - نسخه کامل با چت آنلاین');
document.getElementById('settingsPrivateAccount').onclick = async () => {
  const data = await apiCall('/api/me');
  if(data) {
    const newPrivate = !data.private;
    await apiCall('/api/user/update', { method: 'POST', body: JSON.stringify({ private: newPrivate }) });
    document.getElementById('privateSwitch').className = newPrivate ? 'toggle-switch active' : 'toggle-switch';
    showToast(newPrivate ? '🔒 حساب خصوصی شد' : '🌐 حساب عمومی شد');
  }
};

loadApp();
</script>
</body>
</html>
'''

if __name__ == '__main__':
    app.run()