import os
import time
import shutil
import base64
import json
import secrets
import psutil
import hashlib
from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Depends, Response, status, Request, Form
from fastapi.responses import HTMLResponse, RedirectResponse
from prometheus_client import Counter, Histogram, generate_latest, CONTENT_TYPE_LATEST
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Import parsers
from parsers.dxf_parser import parse_dxf
from parsers.pdf_parser import parse_pdf, parse_image
import importlib
import parsers.pdf_parser as _pdf_parser_module

app = FastAPI(
    title="Digital Takeoff Engine API",
    description="Python microservice for automatic quantity extraction from architectural blueprints",
    version="1.0.0"
)

# Read configurations from environment
API_KEY = os.getenv("API_KEY", "bonyan_takeoff_secret_token_123")
METRICS_USER = os.getenv("METRICS_USER", "admin")
METRICS_PASS = os.getenv("METRICS_PASS", "takeoff_grafana_pass")

# Define Prometheus metrics
BLUEPRINT_PROCESS_REQUESTS = Counter(
    "blueprint_process_requests_total",
    "Total blueprint processing requests",
    ["status", "file_type"]
)
BLUEPRINT_PROCESS_DURATION = Histogram(
    "blueprint_process_duration_seconds",
    "Blueprint processing duration in seconds",
    buckets=[0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0]
)

# Persistent Analytics File
ANALYTICS_FILE = "analytics.json"

# Load initial state
if os.path.exists(ANALYTICS_FILE):
    try:
        with open(ANALYTICS_FILE, "r") as f:
            ANALYTICS_DATA = json.load(f)
    except Exception:
        ANALYTICS_DATA = {
            "total_requests": 0,
            "success_requests": 0,
            "failed_requests": 0,
            "file_types": {"pdf": 0, "dxf": 0, "dwg": 0},
            "recent_runs": [],
            "durations": []
        }
else:
    ANALYTICS_DATA = {
        "total_requests": 0,
        "success_requests": 0,
        "failed_requests": 0,
        "file_types": {"pdf": 0, "dxf": 0, "dwg": 0},
        "recent_runs": [],
        "durations": []
    }

def save_analytics():
    try:
        with open(ANALYTICS_FILE, "w") as f:
            json.dump(ANALYTICS_DATA, f, indent=4)
    except Exception as e:
        print(f"Error saving analytics file: {e}")

# Session Helper Functions
USERS_FILE = "users.json"

def load_users():
    if os.path.exists(USERS_FILE):
        try:
            with open(USERS_FILE, "r") as f:
                return json.load(f)
        except Exception:
            pass
    # Initialize with default admin user from environment
    default_users = {
        METRICS_USER: {
            "password": METRICS_PASS,
            "role": "admin",
            "name": "المدير العام"
        }
    }
    try:
        with open(USERS_FILE, "w") as f:
            json.dump(default_users, f, indent=4)
    except Exception as e:
        print(f"Error saving users file: {e}")
    return default_users

def save_users(users):
    try:
        with open(USERS_FILE, "w") as f:
            json.dump(users, f, indent=4)
    except Exception as e:
        print(f"Error saving users file: {e}")

def get_user_session_token(username, password):
    data = f"{username}:{password}:{API_KEY}"
    return hashlib.sha256(data.encode()).hexdigest()

def get_current_user(request: Request):
    cookie = request.cookies.get("dashboard_session")
    if not cookie or ":" not in cookie:
        return None
    try:
        username, token = cookie.split(":", 1)
        users = load_users()
        if username in users:
            expected = get_user_session_token(username, users[username]["password"])
            if secrets.compare_digest(token, expected):
                return {
                    "username": username,
                    "name": users[username].get("name", username),
                    "role": users[username].get("role", "employee")
                }
    except Exception:
        pass
    return None

def is_authenticated(request: Request):
    return get_current_user(request) is not None

# Authentication dependency for API endpoints
def verify_api_key(x_api_key: str = Header(None)):
    if not x_api_key:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="X-API-KEY header is missing"
        )
    if not secrets.compare_digest(x_api_key, API_KEY):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid X-API-KEY"
        )
    return x_api_key

# Basic Auth checking for Prometheus Scraping
def verify_metrics_auth(authorization: str = Header(None)):
    if not authorization:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authorization header is missing",
            headers={"WWW-Authenticate": "Basic"}
        )
    try:
        auth_type, credentials = authorization.split()
        if auth_type.lower() != "basic":
            raise ValueError()
        decoded = base64.b64decode(credentials).decode("utf-8")
        username, password = decoded.split(":", 1)
        users = load_users()
        if username in users:
            valid = secrets.compare_digest(password, users[username]["password"]) and users[username]["role"] == "admin"
        else:
            valid = secrets.compare_digest(username, METRICS_USER) and secrets.compare_digest(password, METRICS_PASS)
        if not valid:
            raise ValueError()
    except Exception:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Basic"}
        )

@app.get("/v1/health")
def health_check():
    """Simple API health check endpoint"""
    return {"status": "ok", "timestamp": time.time()}

@app.get("/v1/debug")
def debug_info():
    import parsers.pdf_parser as pp
    import inspect
    return {
        "pdf_parser_file": pp.__file__,
        "pdf_parser_parse_pdf_doc": pp.parse_pdf.__doc__,
        "pdf_parser_source_snippet": inspect.getsource(pp.parse_pdf)[:400]
    }

@app.get("/metrics")
def get_metrics(auth = Depends(verify_metrics_auth)):
    """Exposes Prometheus metrics, protected by Basic Auth"""
    return Response(content=generate_latest(), media_type=CONTENT_TYPE_LATEST)

@app.get("/v1/analytics-data")
def get_analytics_data(request: Request):
    """Returns JSON representation of analytics and hardware utilization, protected by session"""
    if not is_authenticated(request):
        raise HTTPException(status_code=401, detail="Unauthorized")
    
    stats = dict(ANALYTICS_DATA)
    try:
        stats["cpu_percent"] = psutil.cpu_percent()
        stats["ram_percent"] = psutil.virtual_memory().percent
    except Exception:
        stats["cpu_percent"] = 0
        stats["ram_percent"] = 0
    return stats

@app.post("/v1/login")
def login(response: Response, username: str = Form(...), password: str = Form(...)):
    """Accepts username and password to start a session"""
    users = load_users()
    if username in users and secrets.compare_digest(password, users[username]["password"]):
        token = get_user_session_token(username, users[username]["password"])
        cookie_val = f"{username}:{token}"
        response.set_cookie(
            key="dashboard_session",
            value=cookie_val,
            httponly=True,
            max_age=86400 * 7, # 7 days session
            samesite="lax"
        )
        return {"status": "success", "message": "Logged in successfully"}
    raise HTTPException(status_code=401, detail="اسم المستخدم أو كلمة المرور غير صحيحة")

@app.get("/v1/logout")
def logout():
    """Clears session cookie and redirects to homepage with cache-busting query"""
    response = RedirectResponse(url="/?logged_out=1", status_code=status.HTTP_303_SEE_OTHER)
    response.delete_cookie("dashboard_session", httponly=True, samesite="lax")
    response.set_cookie("dashboard_session", "", max_age=0, expires=0, httponly=True, samesite="lax", path="/")
    response.headers["Clear-Site-Data"] = '"cache"'
    return response

@app.post("/v1/edit-account")
def edit_account(request: Request, response: Response, name: str = Form(...), password: str = Form(None)):
    """Edits the currently logged-in user's profile and optional password change"""
    user = get_current_user(request)
    if not user:
        raise HTTPException(status_code=401, detail="غير مصرح")
    
    users = load_users()
    username = user["username"]
    
    if username not in users:
        raise HTTPException(status_code=404, detail="المستخدم غير موجود")
        
    users[username]["name"] = name
    if password and password.strip():
        users[username]["password"] = password
        # Re-set session cookie with the new token so session doesn't expire
        token = get_user_session_token(username, password)
        cookie_val = f"{username}:{token}"
        response.set_cookie(
            key="dashboard_session",
            value=cookie_val,
            httponly=True,
            max_age=86400 * 7,
            samesite="lax"
        )
        
    save_users(users)
    return {"status": "success", "message": "تم تعديل الحساب بنجاح"}

@app.post("/v1/add-employee")
def add_employee(request: Request, username: str = Form(...), name: str = Form(...), password: str = Form(...), role: str = Form(...)):
    """Adds a new employee user to the system (Admin only)"""
    user = get_current_user(request)
    if not user or user["role"] != "admin":
        raise HTTPException(status_code=403, detail="غير مصرح: للمشرفين فقط")
        
    users = load_users()
    if username in users:
        raise HTTPException(status_code=400, detail="اسم المستخدم مستخدم بالفعل")
        
    if role not in ["admin", "employee"]:
        raise HTTPException(status_code=400, detail="دور المستخدم غير صالح")
        
    users[username] = {
        "password": password,
        "role": role,
        "name": name
    }
    save_users(users)
    return {"status": "success", "message": "تم إضافة الموظف بنجاح"}

@app.post("/v1/analyze-blueprint")
def analyze_blueprint(
    response: Response,
    file: UploadFile = File(...),
    x_api_key: str = Depends(verify_api_key)
):
    """
    Main endpoint to analyze a blueprint (PDF, DXF, or DWG) and extract quantities.
    """
    # Set anti-caching headers immediately
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"

    start_time = time.perf_counter()
    filename = file.filename
    file_ext = os.path.splitext(filename)[1].lower()

    # Track metrics locally
    ANALYTICS_DATA["total_requests"] += 1

    # Force reload pdf_parser to pick up any on-disk updates without restart
    try:
        importlib.reload(_pdf_parser_module)
        from parsers.pdf_parser import parse_pdf as _rpdf, parse_image as _rimg
    except Exception:
        _rpdf, _rimg = parse_pdf, parse_image

    if file_ext not in [".pdf", ".dxf", ".dwg", ".png", ".jpg", ".jpeg"]:
        ANALYTICS_DATA["failed_requests"] += 1
        save_analytics()
        BLUEPRINT_PROCESS_REQUESTS.labels(status="failed", file_type="invalid").inc()
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Unsupported file format '{file_ext}'. Only PDF, DXF, DWG, and image formats (PNG, JPG, JPEG) are supported."
        )

    # Save uploaded file to local temporary storage
    temp_dir = "/tmp/takeoff_uploads"
    os.makedirs(temp_dir, exist_ok=True)
    temp_filepath = os.path.join(temp_dir, f"{secrets.token_hex(16)}_{filename}")

    try:
        with open(temp_filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
    except Exception as e:
        ANALYTICS_DATA["failed_requests"] += 1
        save_analytics()
        BLUEPRINT_PROCESS_REQUESTS.labels(status="failed", file_type=file_ext).inc()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to save uploaded file: {str(e)}"
        )

    # Execute analysis based on file type
    try:
        if file_ext == ".pdf":

            data = _rpdf(temp_filepath)
            
            # --- MAP NEW ARCHITECTURE TO LEGACY FRONTEND ---
            # The new parser returns `total_floor_area_m2`, `floors: []`
            # The legacy UI expects `total_built_up_area_m2`, `facade_area_m2`, etc.
            if "total_built_up_area_m2" not in data:
                tfa = data.get("total_floor_area_m2", 0.0)
                data["total_built_up_area_m2"] = tfa
                data["default_floor_height_m"] = data.get("debug", {}).get("wall_height_assumed_m", 3.2)
                data["internal_wall_paint_area_m2"] = data.get("wall_paint_area_m2", 0.0)
                data["facade_area_m2"] = round(tfa * 0.4, 2)
                data["unique_floors_detected"] = data.get("floors_detected", 1)
                data["total_pages_scanned"] = data.get("floors_detected", 1)
                data["net_floor_ceiling_area_m2"] = data.get("ceiling_area_m2", 0.0)
                data["wall_paint_plaster_area_m2"] = data.get("wall_paint_area_m2", 0.0)
                data["columns_detected"] = 0

        elif file_ext in [".png", ".jpg", ".jpeg"]:
            data = _rimg(temp_filepath)
        else:
            if file_ext == ".dwg":
                try:
                    data = parse_dxf(temp_filepath)
                except Exception:
                    raise ValueError(
                        "AutoCAD binary DWG format is not directly parseable by the geometric engine. "
                        "Please save/export the drawing as ASCII DXF format (e.g. AutoCAD 2018 DXF) and upload it."
                    )
            else:
                data = parse_dxf(temp_filepath)

        # Update success metrics
        duration = round(time.perf_counter() - start_time, 3)
        BLUEPRINT_PROCESS_DURATION.observe(duration)
        BLUEPRINT_PROCESS_REQUESTS.labels(status="success", file_type=file_ext).inc()

        # Update Local Persistent Analytics
        ANALYTICS_DATA["success_requests"] += 1
        
        # Increment file type count
        ext_clean = file_ext[1:]
        ANALYTICS_DATA["file_types"][ext_clean] = ANALYTICS_DATA["file_types"].get(ext_clean, 0) + 1
        
        # Keep durations array bounded to last 50 runs
        ANALYTICS_DATA["durations"].append(duration)
        if len(ANALYTICS_DATA["durations"]) > 50:
            ANALYTICS_DATA["durations"].pop(0)

        # Append to recent runs list (max 10 items)
        ANALYTICS_DATA["recent_runs"].insert(0, {
            "filename": filename,
            "file_type": ext_clean,
            "status": "success",
            "duration": duration,
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
        })
        if len(ANALYTICS_DATA["recent_runs"]) > 10:
            ANALYTICS_DATA["recent_runs"].pop()

        save_analytics()

        return {
            "status": "success",
            "data": data
        }

    except Exception as e:
        # Update failure metrics
        ANALYTICS_DATA["failed_requests"] += 1
        
        ext_clean = file_ext[1:]
        ANALYTICS_DATA["recent_runs"].insert(0, {
            "filename": filename,
            "file_type": ext_clean,
            "status": "failed",
            "duration": round(time.perf_counter() - start_time, 3),
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
        })
        if len(ANALYTICS_DATA["recent_runs"]) > 10:
            ANALYTICS_DATA["recent_runs"].pop()

        save_analytics()
        
        BLUEPRINT_PROCESS_REQUESTS.labels(status="failed", file_type=file_ext).inc()
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=str(e)
        )
    finally:
        # Clean up temporary uploaded file
        if os.path.exists(temp_filepath):
            try:
                os.remove(temp_filepath)
            except Exception:
                pass

def serve_login_page():
    return """
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>بنيان بلس | تسجيل الدخول</title>
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700;800&family=Outfit:wght@400;600&display=swap" rel="stylesheet">
    <!-- FontAwesome Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg-color: #070913;
            --card-bg: rgba(13, 17, 30, 0.75);
            --border-color: rgba(255, 255, 255, 0.08);
            --primary: #3b82f6;
            --primary-glow: rgba(59, 130, 246, 0.4);
            --secondary: #06b6d4;
            --text-main: #f3f4f6;
            --text-muted: #9ca3af;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-main);
            font-family: 'Cairo', sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1.5rem;
            background-image: 
                radial-gradient(circle at 10% 20%, rgba(59, 130, 246, 0.1) 0%, transparent 40%),
                radial-gradient(circle at 90% 80%, rgba(6, 182, 212, 0.1) 0%, transparent 40%);
            background-attachment: fixed;
        }

        .login-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 2.5rem;
            width: 100%;
            max-width: 420px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.5);
            text-align: center;
            position: relative;
            overflow: hidden;
            animation: card-appear 0.6s cubic-bezier(0.4, 0, 0.2, 1);
        }

        @keyframes card-appear {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .logo-wrap {
            font-size: 3rem;
            background: linear-gradient(135deg, #60a5fa 0%, #06b6d4 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 1rem;
            display: inline-block;
        }

        .login-card h2 {
            font-size: 1.5rem;
            font-weight: 800;
            margin-bottom: 0.5rem;
            background: linear-gradient(135deg, #f3f4f6 0%, #9ca3af 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .login-card p {
            color: var(--text-muted);
            font-size: 0.85rem;
            margin-bottom: 2rem;
        }

        .form-group {
            position: relative;
            margin-bottom: 1.2rem;
            text-align: right;
        }

        .form-group label {
            display: block;
            font-size: 0.8rem;
            font-weight: 600;
            color: var(--text-muted);
            margin-bottom: 0.4rem;
        }

        .input-wrapper {
            position: relative;
        }

        .input-wrapper i {
            position: absolute;
            top: 50%;
            right: 12px;
            transform: translateY(-50%);
            color: var(--text-muted);
            font-size: 0.95rem;
            transition: color 0.3s;
        }

        .input-field {
            width: 100%;
            background: #090c15;
            border: 1px solid rgba(255, 255, 255, 0.08);
            border-radius: 10px;
            padding: 0.75rem 2.5rem 0.75rem 1rem;
            color: var(--text-main);
            font-size: 0.9rem;
            transition: all 0.3s;
            font-family: 'Outfit', sans-serif;
        }

        .input-field:focus {
            border-color: var(--primary);
            box-shadow: 0 0 10px rgba(59, 130, 246, 0.25);
            outline: none;
        }

        .input-field:focus + i {
            color: var(--primary);
        }

        .btn-login {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            border: none;
            color: white;
            font-family: 'Cairo', sans-serif;
            font-weight: 700;
            font-size: 1rem;
            padding: 0.8rem;
            border-radius: 10px;
            cursor: pointer;
            width: 100%;
            margin-top: 1rem;
            box-shadow: 0 4px 15px var(--primary-glow);
            transition: all 0.3s;
        }

        .btn-login:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(59, 130, 246, 0.5);
        }

        .btn-login:active {
            transform: translateY(0);
        }

        .error-message {
            background: rgba(239, 68, 68, 0.08);
            border: 1px solid rgba(239, 68, 68, 0.2);
            color: #fca5a5;
            font-size: 0.8rem;
            padding: 0.6rem;
            border-radius: 8px;
            margin-bottom: 1.2rem;
            display: none;
            text-align: right;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <div class="logo-wrap"><i class="fa-solid fa-microchip-ai"></i></div>
        <h2>بنيان بلس | محرك السحب</h2>
        <p>الرجاء تسجيل الدخول للوصول إلى لوحة التحكم المفاهيمية</p>
        
        <div class="error-message" id="error-box">
            <i class="fa-solid fa-triangle-exclamation"></i> <span id="error-text"></span>
        </div>
        
        <form id="login-form" onsubmit="handleLogin(event)">
            <div class="form-group">
                <label>اسم المستخدم (Username)</label>
                <div class="input-wrapper">
                    <input type="text" id="username" required class="input-field" placeholder="Username">
                    <i class="fa-solid fa-user"></i>
                </div>
            </div>
            
            <div class="form-group">
                <label>كلمة المرور (Password)</label>
                <div class="input-wrapper">
                    <input type="password" id="password" required class="input-field" placeholder="••••••••">
                    <i class="fa-solid fa-lock"></i>
                </div>
            </div>
            
            <button type="submit" class="btn-login" id="submit-btn">تسجيل الدخول</button>
        </form>
    </div>

    <script>
        function handleLogin(e) {
            e.preventDefault();
            const u = document.getElementById('username').value;
            const p = document.getElementById('password').value;
            const btn = document.getElementById('submit-btn');
            const errBox = document.getElementById('error-box');
            const errText = document.getElementById('error-text');
            
            btn.disabled = true;
            btn.innerText = 'جاري التحقق...';
            errBox.style.display = 'none';
            
            const formData = new URLSearchParams();
            formData.append('username', u);
            formData.append('password', p);
            
            fetch('/v1/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: formData
            })
            .then(async res => {
                const isJson = res.headers.get('content-type')?.includes('application/json');
                const data = isJson ? await res.json() : null;
                if (!res.ok) {
                    throw new Error(data?.detail || 'فشل تسجيل الدخول. يرجى التحقق من الحساب.');
                }
                return data;
            })
            .then(() => {
                window.location.href = '/?v=' + Date.now();
            })
            .catch(err => {
                errBox.style.display = 'block';
                errText.innerText = err.message;
                btn.disabled = false;
                btn.innerText = 'تسجيل الدخول';
            });
        }
    </script>
</body>
</html>
"""

def serve_dashboard_html(username: str, name: str, role: str):
    html_content = """
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>بنيان بلس | لوحة تحكم محرك السحب الرقمي</title>
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <!-- FontAwesome Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --bg-color: #070913;
            --card-bg: rgba(13, 17, 30, 0.7);
            --border-color: rgba(255, 255, 255, 0.06);
            --primary: #3b82f6;
            --primary-glow: rgba(59, 130, 246, 0.35);
            --secondary: #06b6d4;
            --secondary-glow: rgba(6, 182, 212, 0.35);
            --success: #10b981;
            --success-glow: rgba(16, 185, 129, 0.3);
            --danger: #ef4444;
            --warning: #f59e0b;
            --text-main: #f3f4f6;
            --text-muted: #9ca3af;
            --font-arabic: 'Cairo', sans-serif;
            --font-numbers: 'Outfit', sans-serif;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-main);
            font-family: var(--font-arabic);
            min-height: 100vh;
            padding: 2rem;
            background-image: 
                radial-gradient(circle at 5% 15%, rgba(59, 130, 246, 0.09) 0%, transparent 45%),
                radial-gradient(circle at 95% 85%, rgba(6, 182, 212, 0.09) 0%, transparent 45%),
                radial-gradient(circle at 50% 50%, rgba(16, 185, 129, 0.04) 0%, transparent 60%);
            background-attachment: fixed;
            overflow-x: hidden;
        }

        /* Scrollbar Styling */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.02);
        }
        ::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 999px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        /* User Profile & Dropdown Menu */
        .user-menu-container {
            position: relative;
            display: inline-block;
        }
        
        .user-menu-btn {
            color: var(--text-main);
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid var(--border-color);
            padding: 0.6rem 1.2rem;
            border-radius: 9999px;
            display: flex;
            align-items: center;
            gap: 0.6rem;
            cursor: pointer;
            font-family: var(--font-arabic);
            font-size: 0.85rem;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .user-menu-btn:hover {
            background: rgba(255, 255, 255, 0.1);
            border-color: rgba(59, 130, 246, 0.3);
        }
        
        .user-dropdown-menu {
            display: none;
            position: absolute;
            left: 0;
            top: 115%;
            background: #090c15;
            border: 1px solid var(--border-color);
            border-radius: 12px;
            min-width: 190px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.6);
            z-index: 1000;
            overflow: hidden;
            padding: 0.4rem 0;
            backdrop-filter: blur(10px);
            animation: menu-appear 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            text-align: right;
        }
        
        @keyframes menu-appear {
            from { transform: translateY(5px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .user-dropdown-menu a {
            display: flex;
            align-items: center;
            gap: 0.6rem;
            padding: 0.7rem 1.2rem;
            color: var(--text-main);
            text-decoration: none;
            font-size: 0.85rem;
            transition: background 0.2s, color 0.2s;
        }
        
        .user-dropdown-menu a:hover {
            background: rgba(255, 255, 255, 0.05);
        }
        
        /* Glassmorphic Modals */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(4, 5, 11, 0.8);
            backdrop-filter: blur(8px);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 2000;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
        }
        
        .modal-overlay.active {
            opacity: 1;
            pointer-events: auto;
        }
        
        .modal-content {
            background: rgba(13, 17, 30, 0.95);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            padding: 2rem;
            width: 100%;
            max-width: 440px;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.6);
            transform: translateY(20px);
            transition: transform 0.3s ease;
            text-align: right;
        }
        
        .modal-overlay.active .modal-content {
            transform: translateY(0);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            padding-bottom: 0.8rem;
        }
        
        .modal-header h3 {
            font-size: 1.2rem;
            font-weight: 700;
            color: var(--text-main);
        }
        
        .modal-header .close-btn {
            background: none;
            border: none;
            color: var(--text-muted);
            font-size: 1.2rem;
            cursor: pointer;
            transition: color 0.2s;
        }
        
        .modal-header .close-btn:hover {
            color: var(--danger);
        }
        
        .modal-body .form-group {
            margin-bottom: 1.2rem;
        }
        
        .modal-body label {
            display: block;
            font-size: 0.85rem;
            font-weight: 600;
            color: var(--text-muted);
            margin-bottom: 0.4rem;
        }
        
        .modal-body .input-field {
            width: 100%;
            background: #090c15;
            border: 1px solid rgba(255, 255, 255, 0.08);
            border-radius: 10px;
            padding: 0.75rem 1rem;
            color: var(--text-main);
            font-size: 0.9rem;
            transition: all 0.3s;
            font-family: var(--font-numbers), var(--font-arabic);
            text-align: right;
        }
        
        .modal-body .input-field:focus {
            border-color: var(--primary);
            box-shadow: 0 0 10px rgba(59, 130, 246, 0.25);
            outline: none;
        }
        
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
            margin-top: 1.8rem;
        }
        
        .btn-cancel {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid var(--border-color);
            color: var(--text-main);
            padding: 0.7rem 1.5rem;
            border-radius: 10px;
            cursor: pointer;
            font-family: var(--font-arabic);
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-cancel:hover {
            background: rgba(255, 255, 255, 0.1);
        }
        
        .btn-save {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            border: none;
            color: white;
            padding: 0.7rem 1.8rem;
            border-radius: 10px;
            cursor: pointer;
            font-family: var(--font-arabic);
            font-weight: 700;
            box-shadow: 0 4px 15px var(--primary-glow);
            transition: all 0.3s;
        }
        
        .btn-save:hover {
            box-shadow: 0 6px 20px rgba(59, 130, 246, 0.5);
            transform: translateY(-1px);
        }
        
        .modal-alert {
            background: rgba(239, 68, 68, 0.08);
            border: 1px solid rgba(239, 68, 68, 0.2);
            color: #fca5a5;
            font-size: 0.8rem;
            padding: 0.6rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            display: none;
            text-align: right;
        }

        .container {
            max-width: 1500px;
            margin: 0 auto;
        }

        /* Header Layout */
        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2.5rem;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 1.5rem;
            position: relative;
        }

        .logo-section h1 {
            font-size: 1.9rem;
            font-weight: 800;
            background: linear-gradient(135deg, #60a5fa 0%, #06b6d4 50%, #34d399 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            display: flex;
            align-items: center;
            gap: 0.8rem;
        }

        .logo-section p {
            color: var(--text-muted);
            font-size: 0.95rem;
            margin-top: 0.3rem;
            font-weight: 300;
        }

        .server-status {
            display: flex;
            align-items: center;
            gap: 0.6rem;
            background: rgba(16, 185, 129, 0.08);
            border: 1px solid rgba(16, 185, 129, 0.18);
            padding: 0.6rem 1.2rem;
            border-radius: 9999px;
            font-size: 0.85rem;
            color: var(--success);
            font-weight: 600;
            box-shadow: 0 0 15px rgba(16, 185, 129, 0.1);
        }

        .server-status .pulse {
            width: 9px;
            height: 9px;
            background-color: var(--success);
            border-radius: 50%;
            animation: pulse-animation 2s infinite;
        }

        @keyframes pulse-animation {
            0% { transform: scale(0.9); opacity: 0.6; box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); }
            70% { transform: scale(1.2); opacity: 1; box-shadow: 0 0 0 8px rgba(16, 185, 129, 0); }
            100% { transform: scale(0.9); opacity: 0.6; box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
        }

        /* Top Mini Stats Dashboard */
        .stats-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 1.2rem;
            margin-bottom: 2rem;
        }

        .summary-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            backdrop-filter: blur(16px);
            border-radius: 12px;
            padding: 1.2rem 1.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .summary-card:hover {
            border-color: rgba(59, 130, 246, 0.2);
            transform: translateY(-2px);
        }

        .summary-card h3 {
            font-size: 0.8rem;
            color: var(--text-muted);
            margin-bottom: 0.4rem;
            font-weight: 500;
        }

        .summary-card .number {
            font-size: 1.6rem;
            font-weight: 700;
            font-family: var(--font-numbers);
        }

        .summary-card .icon-wrap {
            width: 45px;
            height: 45px;
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.03);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.3rem;
            color: var(--text-muted);
        }

        /* 3-Column main Grid */
        .main-grid {
            display: grid;
            grid-template-columns: repeat(12, 1fr);
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        /* Left Side: Analytics & System Usage */
        .left-pane {
            grid-column: span 4;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        /* Right Side: Conceptual Pipeline & Simulator */
        .right-pane {
            grid-column: span 8;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        @media (max-width: 1200px) {
            .left-pane, .right-pane {
                grid-column: span 12;
            }
        }

        /* Dashboard Boxes */
        .panel {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            backdrop-filter: blur(20px);
            border-radius: 16px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
        }

        .panel-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.04);
            padding-bottom: 1rem;
            margin-bottom: 1.5rem;
        }

        .panel-header h2 {
            font-size: 1.1rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 0.6rem;
        }

        .panel-header h2 i {
            color: var(--secondary);
        }

        /* Tabs Control on Panel Header */
        .tabs-control {
            display: flex;
            gap: 0.5rem;
        }

        .tab-btn {
            background: transparent;
            border: 1px solid rgba(255, 255, 255, 0.06);
            padding: 0.45rem 1rem;
            border-radius: 8px;
            color: var(--text-muted);
            font-family: var(--font-arabic);
            font-size: 0.8rem;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.4rem;
            transition: all 0.3s;
        }

        .tab-btn:hover {
            color: var(--text-main);
            border-color: rgba(255, 255, 255, 0.15);
        }

        .tab-btn.active {
            background: var(--primary);
            border-color: var(--primary);
            color: white;
            box-shadow: 0 0 10px var(--primary-glow);
        }

        /* Conceptual Pipeline Flow Styles */
        .pipeline-wrapper {
            position: relative;
            padding: 1rem 0;
        }

        .pipeline-flow {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1.2rem;
            position: relative;
            z-index: 2;
        }

        @media (max-width: 768px) {
            .pipeline-flow {
                grid-template-columns: 1fr;
            }
        }

        .pipeline-step {
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.04);
            border-radius: 12px;
            padding: 1.2rem;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
        }

        .pipeline-step:hover, .pipeline-step.active {
            background: rgba(59, 130, 246, 0.06);
            border-color: var(--primary);
            box-shadow: 0 4px 20px rgba(59, 130, 246, 0.15);
            transform: translateY(-3px);
        }

        .pipeline-step.active {
            border-color: var(--secondary);
            background: rgba(6, 182, 212, 0.08);
            box-shadow: 0 4px 20px rgba(6, 182, 212, 0.2);
        }

        .step-num {
            position: absolute;
            top: 10px;
            left: 10px;
            font-family: var(--font-numbers);
            font-size: 1.5rem;
            font-weight: 800;
            color: rgba(255, 255, 255, 0.05);
            line-height: 1;
            transition: color 0.3s;
        }

        .pipeline-step:hover .step-num, .pipeline-step.active .step-num {
            color: rgba(255, 255, 255, 0.12);
        }

        .step-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.04);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            color: var(--text-main);
            margin-bottom: 0.8rem;
            transition: all 0.3s;
        }

        .pipeline-step:hover .step-icon, .pipeline-step.active .step-icon {
            background: var(--primary);
            color: white;
            box-shadow: 0 0 10px var(--primary-glow);
        }

        .pipeline-step.active .step-icon {
            background: var(--secondary);
            box-shadow: 0 0 10px var(--secondary-glow);
        }

        .step-title {
            font-size: 0.95rem;
            font-weight: 700;
            margin-bottom: 0.4rem;
        }

        .step-desc {
            font-size: 0.8rem;
            color: var(--text-muted);
            line-height: 1.5;
        }

        /* Takeoff Simulator & Uploader Styles */
        .simulator-layout {
            display: grid;
            grid-template-columns: 1.2fr 1fr;
            gap: 1.5rem;
            margin-top: 0.5rem;
            width: 100%;
        }

        @media (max-width: 900px) {
            .simulator-layout {
                grid-template-columns: 1fr;
            }
        }

        .simulator-workspace {
            background: #090c15;
            border: 1px solid rgba(255, 255, 255, 0.04);
            border-radius: 12px;
            padding: 1rem;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            min-height: 350px;
            position: relative;
            overflow: hidden;
        }

        .simulator-sidebar {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            gap: 1.2rem;
        }

        .sim-meta {
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.04);
            border-radius: 10px;
            padding: 1rem;
        }

        .sim-meta h4 {
            font-size: 0.85rem;
            color: var(--text-muted);
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.4rem;
        }

        .sim-meta p {
            font-size: 0.85rem;
            line-height: 1.6;
        }

        /* Blueprint Scan Effect */
        .blueprint-container {
            width: 100%;
            max-width: 420px;
            height: auto;
            position: relative;
            border: 1px solid rgba(59, 130, 246, 0.15);
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.5);
        }

        /* Scanning laser bar */
        .scan-laser {
            position: absolute;
            left: 0;
            width: 100%;
            height: 3px;
            background: linear-gradient(90deg, transparent, var(--secondary), transparent);
            box-shadow: 0 0 12px 3px var(--secondary);
            z-index: 10;
            pointer-events: none;
            opacity: 0;
            top: 0;
        }

        .scan-active .scan-laser {
            animation: laser-sweep 2.5s infinite linear;
            opacity: 1;
        }

        @keyframes laser-sweep {
            0% { top: 0%; }
            50% { top: 100%; }
            100% { top: 0%; }
        }

        /* Terminal styling */
        .terminal-box {
            background: #03050a;
            border: 1px solid rgba(255, 255, 255, 0.06);
            border-radius: 10px;
            padding: 1rem;
            font-family: var(--font-numbers);
            font-size: 0.8rem;
            color: #34d399;
            min-height: 185px;
            max-height: 220px;
            overflow-y: auto;
            white-space: pre-wrap;
            direction: ltr;
            text-align: left;
            position: relative;
        }

        .terminal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            padding-bottom: 0.5rem;
            margin-bottom: 0.6rem;
            color: var(--text-muted);
            font-size: 0.75rem;
            font-weight: 600;
        }

        .terminal-dots {
            display: flex;
            gap: 5px;
        }

        .terminal-dot {
            width: 7px;
            height: 7px;
            border-radius: 50%;
        }

        .btn-sim {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            border: none;
            color: white;
            font-family: var(--font-arabic);
            font-weight: 700;
            font-size: 0.95rem;
            padding: 0.8rem 1.5rem;
            border-radius: 10px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.6rem;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
            width: 100%;
        }

        .btn-sim:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(59, 130, 246, 0.45);
        }

        .btn-sim:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            background: rgba(255, 255, 255, 0.05);
            color: var(--text-muted);
            box-shadow: none;
        }

        /* Real Blueprint Upload Pane Styles */
        .upload-area-container {
            background: rgba(255, 255, 255, 0.015);
            border: 1px solid rgba(255, 255, 255, 0.04);
            border-radius: 12px;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            min-height: 350px;
        }

        .drag-drop-zone {
            border: 2px dashed rgba(255, 255, 255, 0.15);
            border-radius: 12px;
            padding: 2.2rem 1.5rem;
            text-align: center;
            cursor: pointer;
            background: rgba(255, 255, 255, 0.005);
            transition: all 0.3s;
            margin-bottom: 1rem;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .drag-drop-zone:hover, .drag-drop-zone.dragover {
            border-color: var(--secondary);
            background: rgba(6, 182, 212, 0.03);
            box-shadow: 0 0 15px rgba(6, 182, 212, 0.1);
        }

        .cloud-upload-icon {
            font-size: 2.8rem;
            color: var(--text-muted);
            margin-bottom: 0.8rem;
            transition: color 0.3s;
        }

        .drag-drop-zone:hover .cloud-upload-icon {
            color: var(--secondary);
        }

        .upload-title {
            font-size: 0.95rem;
            font-weight: 700;
            margin-bottom: 0.3rem;
            color: var(--text-main);
        }

        .upload-sub {
            font-size: 0.8rem;
            color: var(--text-muted);
        }

        .api-key-row {
            display: flex;
            flex-direction: column;
            gap: 0.4rem;
            margin-bottom: 1rem;
        }

        .api-key-row label {
            font-size: 0.85rem;
            font-weight: 600;
            color: var(--text-muted);
        }

        .api-input-field {
            background: #090c15;
            border: 1px solid rgba(255, 255, 255, 0.08);
            padding: 0.6rem 0.9rem;
            border-radius: 8px;
            color: var(--text-main);
            font-family: var(--font-numbers);
            font-size: 0.85rem;
            width: 100%;
        }

        .api-input-field:focus {
            border-color: var(--primary);
            outline: none;
        }

        .selected-file-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.05);
            padding: 0.7rem 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }

        .selected-file-row .file-name {
            font-size: 0.85rem;
            color: var(--text-main);
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 80%;
            font-family: var(--font-numbers);
        }

        .btn-remove-file {
            background: none;
            border: none;
            color: var(--danger);
            cursor: pointer;
            font-size: 1rem;
            padding: 0 0.3rem;
        }

        /* Upload Progress Bar */
        .progress-container-upload {
            margin-bottom: 1.2rem;
            width: 100%;
        }

        .progress-bar-label {
            display: flex;
            justify-content: space-between;
            font-size: 0.8rem;
            color: var(--text-muted);
            margin-bottom: 0.4rem;
        }

        .progress-bar-track {
            width: 100%;
            height: 6px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 999px;
            overflow: hidden;
        }

        .progress-bar-fill-upload {
            height: 100%;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            width: 0%;
            transition: width 0.25s ease-out;
        }

        /* Real Quantity Results Grid */
        .real-results-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.8rem;
            margin-top: 0.6rem;
        }

        .result-item {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
            background: rgba(255,255,255,0.01);
            padding: 0.5rem 0.8rem;
            border-radius: 6px;
            border: 1px solid rgba(255,255,255,0.02);
        }

        .result-item span {
            font-size: 0.75rem;
            color: var(--text-muted);
        }

        .result-item strong {
            font-size: 0.95rem;
            font-weight: 700;
            color: var(--text-main);
            font-family: var(--font-numbers);
        }

        /* CPU/RAM Circular Progress Charts */
        .hardware-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.2rem;
            text-align: center;
        }

        .hw-circle-box {
            background: rgba(255, 255, 255, 0.015);
            border: 1px solid rgba(255, 255, 255, 0.04);
            border-radius: 12px;
            padding: 1.2rem 1rem;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .circle-svg {
            width: 90px;
            height: 90px;
            transform: rotate(-90deg);
            margin-bottom: 0.8rem;
        }

        .circle-bg {
            fill: none;
            stroke: rgba(255, 255, 255, 0.03);
            stroke-width: 7px;
        }

        .circle-fill-cpu {
            fill: none;
            stroke: var(--warning);
            stroke-width: 7px;
            stroke-dasharray: 251.2;
            stroke-dashoffset: 251.2;
            transition: stroke-dashoffset 1s ease-out;
            stroke-linecap: round;
        }

        .circle-fill-ram {
            fill: none;
            stroke: var(--success);
            stroke-width: 7px;
            stroke-dasharray: 251.2;
            stroke-dashoffset: 251.2;
            transition: stroke-dashoffset 1s ease-out;
            stroke-linecap: round;
        }

        .hw-value {
            position: absolute;
            font-size: 1.1rem;
            font-weight: 700;
            font-family: var(--font-numbers);
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .hw-circle-container {
            position: relative;
            width: 90px;
            height: 90px;
        }

        .hw-circle-box h4 {
            font-size: 0.85rem;
            color: var(--text-muted);
            font-weight: 600;
        }

        /* Chart Canvas Wrappers */
        .chart-wrap {
            position: relative;
            height: 220px;
            width: 100%;
        }

        /* Recent Logs Table */
        .table-panel {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            backdrop-filter: blur(20px);
            border-radius: 16px;
            padding: 1.5rem;
        }

        .table-responsive {
            width: 100%;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            text-align: right;
        }

        th {
            color: var(--text-muted);
            font-size: 0.85rem;
            font-weight: 600;
            padding: 1rem 0.8rem;
            border-bottom: 2px solid var(--border-color);
        }

        td {
            padding: 1rem 0.8rem;
            border-bottom: 1px solid var(--border-color);
            font-size: 0.9rem;
            font-weight: 500;
        }

        tr:hover td {
            background: rgba(255, 255, 255, 0.01);
        }

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 0.35rem;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .badge.success {
            background: rgba(16, 185, 129, 0.08);
            color: var(--success);
            border: 1px solid rgba(16, 185, 129, 0.2);
        }

        .badge.fail {
            background: rgba(239, 68, 68, 0.08);
            color: var(--danger);
            border: 1px solid rgba(239, 68, 68, 0.2);
        }

        .badge.file-pdf { background: rgba(59, 130, 246, 0.08); color: var(--primary); border: 1px solid rgba(59, 130, 246, 0.2); }
        .badge.file-dxf { background: rgba(245, 158, 11, 0.08); color: var(--warning); border: 1px solid rgba(245, 158, 11, 0.2); }
        .badge.file-dwg { background: rgba(6, 182, 212, 0.08); color: var(--secondary); border: 1px solid rgba(6, 182, 212, 0.2); }

        .no-data {
            text-align: center;
            color: var(--text-muted);
            padding: 2.5rem 0;
            font-style: italic;
        }

        /* SVG pulse animation on columns */
        @keyframes svg-pulse {
            0% { transform: scale(1); opacity: 0.4; }
            50% { transform: scale(1.4); opacity: 0.9; }
            100% { transform: scale(1); opacity: 0.4; }
        }
        .pulse-column {
            transform-origin: center;
            animation: svg-pulse 1.5s infinite ease-in-out;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <header>
            <div class="logo-section">
                <h1><i class="fa-solid fa-microchip-ai"></i> محرك سحب الكميات الرقمي (Takeoff Engine)</h1>
                <p>سيرفر التحليل البصري الهندسي | الإصدار v1.1.2 (150 DPI - متطور)</p>
            </div>
            <div style="display: flex; align-items: center; gap: 1rem;">
                <div class="server-status">
                    <div class="pulse"></div>
                    <span>خادم السحب نشط ومستعد</span>
                </div>
                
                <div class="user-menu-container">
                    <button onclick="toggleUserMenu(event)" class="user-menu-btn">
                        <i class="fa-solid fa-user-gear" style="color: var(--primary);"></i>
                        <span>أهلاً، {{USER_NAME}}</span>
                        <i class="fa-solid fa-chevron-down" style="font-size: 0.75rem; opacity: 0.7;"></i>
                    </button>
                    <div id="user-dropdown-menu" class="user-dropdown-menu">
                        {{ADMIN_ONLY_MENU}}
                        <a href="#" onclick="showEditAccountModal(event)">
                            <i class="fa-solid fa-key" style="color: var(--warning); width: 16px;"></i> تعديل الحساب
                        </a>
                        <div style="border-top: 1px solid var(--border-color); margin: 0.4rem 0;"></div>
                        <a href="/v1/logout" style="color: var(--danger); font-weight: bold;" onmouseover="this.style.background='rgba(239, 68, 68, 0.08)'" onmouseout="this.style.background='transparent'">
                            <i class="fa-solid fa-right-from-bracket" style="width: 16px;"></i> تسجيل الخروج
                        </a>
                    </div>
                </div>
            </div>
        </header>

        <!-- Stats summary row -->
        <div class="stats-summary">
            <div class="summary-card">
                <div>
                    <h3>إجمالي التحليلات</h3>
                    <div class="number" id="val-total">0</div>
                </div>
                <div class="icon-wrap"><i class="fa-solid fa-folder-open"></i></div>
            </div>
            <div class="summary-card" style="border-right: 3px solid var(--success);">
                <div>
                    <h3>عمليات ناجحة</h3>
                    <div class="number" id="val-success" style="color: var(--success);">0</div>
                </div>
                <div class="icon-wrap" style="color: var(--success);"><i class="fa-solid fa-square-check"></i></div>
            </div>
            <div class="summary-card" style="border-right: 3px solid var(--danger);">
                <div>
                    <h3>عمليات فاشلة</h3>
                    <div class="number" id="val-failed" style="color: var(--danger);">0</div>
                </div>
                <div class="icon-wrap" style="color: var(--danger);"><i class="fa-solid fa-circle-xmark"></i></div>
            </div>
            <div class="summary-card">
                <div>
                    <h3>متوسط سرعة المعالجة</h3>
                    <div class="number" id="val-avg-duration">0.0s</div>
                </div>
                <div class="icon-wrap"><i class="fa-solid fa-gauge-high"></i></div>
            </div>
        </div>

        <!-- Main Layout -->
        <div class="main-grid">
            
            <!-- RIGHT SIDE: FLOW & SIMULATOR -->
            <div class="right-pane">
                
                <!-- 1. The Conceptual flow pipeline -->
                <div class="panel">
                    <div class="panel-header">
                        <h2><i class="fa-solid fa-route"></i> المخطط المفاهيمي لمسار معالجة البيانات (Takeoff Pipeline)</h2>
                    </div>
                    <div class="pipeline-wrapper">
                        <div class="pipeline-flow">
                            <div class="pipeline-step active" id="step-1" onclick="showStepDetails(1)">
                                <div class="step-num">01</div>
                                <div class="step-icon"><i class="fa-solid fa-cloud-arrow-up"></i></div>
                                <div class="step-title">الاستقبال والتنقية</div>
                                <div class="step-desc">استلام الملفات الهندسيّة والتحقق الفوري من التوقيع الأمني عبر API Key.</div>
                            </div>
                            
                            <div class="pipeline-step" id="step-2" onclick="showStepDetails(2)">
                                <div class="step-num">02</div>
                                <div class="step-icon"><i class="fa-solid fa-compass-drafting"></i></div>
                                <div class="step-title">القراءة الهندسية</div>
                                <div class="step-desc">استخلاص المتجهات والأشكال من DXF ورندرة ملفات PDF بدقة عالية.</div>
                            </div>

                            <div class="pipeline-step" id="step-3" onclick="showStepDetails(3)">
                                <div class="step-num">03</div>
                                <div class="step-icon"><i class="fa-solid fa-brain"></i></div>
                                <div class="step-title">الرؤية والتعرف البصري</div>
                                <div class="step-desc">كشف النوافذ والأبواب عبر YOLOv11، وقراءة النصوص عبر PaddleOCR.</div>
                            </div>

                            <div class="pipeline-step" id="step-4" onclick="showStepDetails(4)">
                                <div class="step-num">04</div>
                                <div class="step-icon"><i class="fa-solid fa-layer-group"></i></div>
                                <div class="step-title">عزل وتصنيف الطبقات</div>
                                <div class="step-desc">تصنيف الطبقات المعمارية والإنشائية (حوائط، أعمدة، فراغات) وتنقيتها.</div>
                            </div>

                            <div class="pipeline-step" id="step-5" onclick="showStepDetails(5)">
                                <div class="step-num">05</div>
                                <div class="step-icon"><i class="fa-solid fa-calculator"></i></div>
                                <div class="step-title">حساب الكميات الصافية</div>
                                <div class="step-desc">احتساب المساحات الكلية والمغلقة، والأطوال بالمتر الطولي، والعدد الكلي للقطع.</div>
                            </div>

                            <div class="pipeline-step" id="step-6" onclick="showStepDetails(6)">
                                <div class="step-num">06</div>
                                <div class="step-icon"><i class="fa-solid fa-file-code"></i></div>
                                <div class="step-title">تصدير البنية الهيكلية</div>
                                <div class="step-desc">هيكلة البيانات وتحويلها لملف JSON متكامل جاهز للمزامنة الفورية.</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 2. The Interactive Workspace / Simulator -->
                <div class="panel">
                    <div class="panel-header">
                        <h2><i class="fa-solid fa-laptop-code"></i> بيئة العمل والتحليل التفاعلي</h2>
                        <div class="tabs-control">
                            <button class="tab-btn active" id="tab-btn-sim" onclick="switchWorkmode('simulate')"><i class="fa-solid fa-play"></i> محاكاة توضيحية</button>
                            <button class="tab-btn" id="tab-btn-upload" onclick="switchWorkmode('upload')"><i class="fa-solid fa-cloud-upload-alt"></i> رفع مخطط حقيقي</button>
                        </div>
                    </div>
                    
                    <!-- TAB 1: WORKMODE SIMULATE -->
                    <div class="simulator-layout" id="workmode-simulate">
                        <!-- Left Workspace: The Interactive Blueprint Drawing -->
                        <div class="simulator-workspace" id="sim-canvas-container">
                            <div class="blueprint-container" id="blueprint-box">
                                <div class="scan-laser" id="laser-bar"></div>
                                <svg id="blueprint-svg" viewBox="0 0 400 250" width="100%" height="100%" style="display: block;">
                                    <!-- Background grid structure -->
                                    <rect width="400" height="250" fill="#080c16" />
                                    <!-- Blueprint Grid lines -->
                                    <g stroke="rgba(59, 130, 246, 0.08)" stroke-width="0.5" id="vector-grid">
                                        <line x1="20" y1="0" x2="20" y2="250" />
                                        <line x1="40" y1="0" x2="40" y2="250" />
                                        <line x1="60" y1="0" x2="60" y2="250" />
                                        <line x1="80" y1="0" x2="80" y2="250" />
                                        <line x1="100" y1="0" x2="100" y2="250" />
                                        <line x1="120" y1="0" x2="120" y2="250" />
                                        <line x1="140" y1="0" x2="140" y2="250" />
                                        <line x1="160" y1="0" x2="160" y2="250" />
                                        <line x1="180" y1="0" x2="180" y2="250" />
                                        <line x1="200" y1="0" x2="200" y2="250" />
                                        <line x1="220" y1="0" x2="220" y2="250" />
                                        <line x1="240" y1="0" x2="240" y2="250" />
                                        <line x1="260" y1="0" x2="260" y2="250" />
                                        <line x1="280" y1="0" x2="280" y2="250" />
                                        <line x1="300" y1="0" x2="300" y2="250" />
                                        <line x1="320" y1="0" x2="320" y2="250" />
                                        <line x1="340" y1="0" x2="340" y2="250" />
                                        <line x1="360" y1="0" x2="360" y2="250" />
                                        <line x1="380" y1="0" x2="380" y2="250" />
                                        
                                        <line x1="0" y1="20" x2="400" y2="20" />
                                        <line x1="0" y1="40" x2="400" y2="40" />
                                        <line x1="0" y1="60" x2="400" y2="60" />
                                        <line x1="0" y1="80" x2="400" y2="80" />
                                        <line x1="0" y1="100" x2="400" y2="100" />
                                        <line x1="0" y1="120" x2="400" y2="120" />
                                        <line x1="0" y1="140" x2="400" y2="140" />
                                        <line x1="0" y1="160" x2="400" y2="160" />
                                        <line x1="0" y1="180" x2="400" y2="180" />
                                        <line x1="0" y1="200" x2="400" y2="200" />
                                        <line x1="0" y1="220" x2="400" y2="220" />
                                    </g>
                                    
                                    <!-- Drawing geometry elements (Drawn as a Blueprint) -->
                                    <g id="geometry-drawing" stroke="rgba(255, 255, 255, 0.35)" stroke-width="1.2" fill="none">
                                        <!-- Outer boundary -->
                                        <rect x="40" y="30" width="320" height="190" stroke-dasharray="1 0" />
                                        <!-- Partition walls -->
                                        <line x1="180" y1="30" x2="180" y2="220" />
                                        <line x1="40" y1="130" x2="180" y2="130" />
                                        <line x1="180" y1="110" x2="360" y2="110" />
                                    </g>

                                    <!-- Windows (Yellow symbols) -->
                                    <g id="windows-symbol" stroke="#eab308" stroke-width="1.5" fill="none">
                                        <line x1="90" y1="30" x2="130" y2="30" />
                                        <line x1="90" y1="27" x2="130" y2="27" />
                                        <line x1="250" y1="30" x2="290" y2="30" />
                                        <line x1="250" y1="27" x2="290" y2="27" />
                                        <line x1="360" y1="140" x2="360" y2="180" stroke-width="1.2" />
                                        <line x1="363" y1="140" x2="363" y2="180" stroke-width="1.2" />
                                    </g>

                                    <!-- Doors (Purple arcs) -->
                                    <g id="doors-symbol" stroke="#a855f7" stroke-width="1.2" fill="none">
                                        <!-- Door 1 -->
                                        <line x1="180" y1="85" x2="180" y2="110" />
                                        <path d="M 180,110 A 25,25 0 0,1 155,85" />
                                        <!-- Door 2 -->
                                        <line x1="140" y1="130" x2="115" y2="130" />
                                        <path d="M 115,130 A 25,25 0 0,1 140,105" />
                                    </g>

                                    <!-- Columns (White squares) -->
                                    <g id="columns-drawing" fill="#94a3b8" stroke="none">
                                        <rect x="38" y="28" width="5" height="5" />
                                        <rect x="178" y="28" width="5" height="5" />
                                        <rect x="358" y="28" width="5" height="5" />
                                        <rect x="38" y="128" width="5" height="5" />
                                        <rect x="178" y="128" width="5" height="5" />
                                        <rect x="358" y="108" width="5" height="5" />
                                        <rect x="38" y="218" width="5" height="5" />
                                        <rect x="178" y="218" width="5" height="5" />
                                        <rect x="358" y="218" width="5" height="5" />
                                    </g>

                                    <!-- Arabic Labels -->
                                    <g id="arabic-labels" fill="rgba(255, 255, 255, 0.4)" font-family="Cairo" font-size="8" text-anchor="middle" font-weight="300">
                                        <text x="110" y="80">غرفة النوم (1)</text>
                                        <text x="110" y="180">المطبخ</text>
                                        <text x="270" y="75">مجلس الاستقبال</text>
                                        <text x="270" y="170">صالة المعيشة</text>
                                    </g>

                                    <!-- ================= AI DETECTIONS (Initially hidden) ================= -->
                                    <!-- AI Columns Detection (Glowing Red Circles) -->
                                    <g id="ai-detect-columns" fill="rgba(239, 68, 68, 0.25)" stroke="#ef4444" stroke-width="1" style="display: none;">
                                        <circle cx="40.5" cy="30.5" r="7" class="pulse-column" />
                                        <circle cx="180.5" cy="30.5" r="7" class="pulse-column" />
                                        <circle cx="360.5" cy="30.5" r="7" class="pulse-column" />
                                        <circle cx="40.5" cy="130.5" r="7" class="pulse-column" />
                                        <circle cx="180.5" cy="130.5" r="7" class="pulse-column" />
                                        <circle cx="360.5" cy="110.5" r="7" class="pulse-column" />
                                        <circle cx="40.5" cy="220.5" r="7" class="pulse-column" />
                                        <circle cx="180.5" cy="220.5" r="7" class="pulse-column" />
                                        <circle cx="360.5" cy="220.5" r="7" class="pulse-column" />
                                    </g>

                                    <!-- AI Wall Segments (Glowing Blue vectors) -->
                                    <g id="ai-detect-walls" fill="none" stroke="#2563eb" stroke-width="3" stroke-linecap="round" style="display: none; filter: drop-shadow(0 0 3px var(--primary-glow));">
                                        <rect x="40.5" y="30.5" width="320" height="190" />
                                        <line x1="180.5" y1="30.5" x2="180.5" y2="220.5" />
                                        <line x1="40.5" y1="130.5" x2="180.5" y2="130.5" />
                                        <line x1="180.5" y1="110.5" x2="360.5" y2="110.5" />
                                    </g>

                                    <!-- AI Spaces & Closed loops (Emerald green shading) -->
                                    <g id="ai-detect-areas" fill="#10b981" fill-opacity="0.18" stroke="#10b981" stroke-width="0.8" style="display: none;">
                                        <!-- Room 1 -->
                                        <rect x="41.5" y="31.5" width="137" height="97" />
                                        <!-- Room 2 -->
                                        <rect x="41.5" y="131.5" width="137" height="87" />
                                        <!-- Reception -->
                                        <rect x="181.5" y="31.5" width="177" height="77" />
                                        <!-- Living room -->
                                        <rect x="181.5" y="111.5" width="177" height="107" />
                                    </g>
                                </svg>
                            </div>
                        </div>
                        
                        <!-- Right Workspace: Terminal Output & Controls -->
                        <div class="simulator-sidebar">
                            <div class="sim-meta">
                                <h4><i class="fa-solid fa-microchip"></i> تفاصيل محرك الرؤية</h4>
                                <p id="sim-details-text" style="color: var(--text-muted);">المحاكي جاهز للتشغيل. انقر فوق الزر أدناه لمشاهدة تفاعل الخوارزمية مع الرسم الهندسي في الوقت الفعلي واستخراج البيانات الهيكلية.</p>
                            </div>

                            <div class="terminal-container">
                                <div class="terminal-header">
                                    <div class="terminal-dots">
                                        <span class="terminal-dot" style="background-color: var(--danger);"></span>
                                        <span class="terminal-dot" style="background-color: var(--warning);"></span>
                                        <span class="terminal-dot" style="background-color: var(--success);"></span>
                                    </div>
                                    <span>takeoff-api-output.json</span>
                                </div>
                                <div class="terminal-box" id="terminal-out">
// بانتظار تشغيل المحاكاة...
// انقر على "بدء محاكاة عملية السحب" أدناه.</div>
                            </div>

                            <button class="btn-sim" id="btn-start-simulation" onclick="runTakeoffSimulation()">
                                <i class="fa-solid fa-play"></i> بدء محاكاة عملية السحب التلقائي
                            </button>
                        </div>
                    </div>
                    
                    <!-- TAB 2: WORKMODE UPLOAD (REAL FILE ANALYSIS) -->
                    <div class="simulator-layout" id="workmode-upload" style="display: none;">
                        
                        <!-- Right Workspace: File Drag & Drop -->
                        <div class="upload-area-container">
                            <div class="api-key-row">
                                <label for="upload-api-key">مفتاح الـ API لعملية السحب (API Key):</label>
                                <input type="text" id="upload-api-key" value="bonyan_takeoff_secret_token_123" placeholder="أدخل مفتاح API Key" class="api-input-field">
                            </div>
                            
                            <div class="drag-drop-zone" id="drop-zone" onclick="triggerFileInput()">
                                <i class="fa-solid fa-cloud-arrow-up cloud-upload-icon"></i>
                                <p class="upload-title">اسحب وأفلت ملف المخطط هنا أو انقر لتصفح جهازك</p>
                                <p class="upload-sub">يدعم صيغ PDF، DXF، DWG، والصور (PNG، JPG، JPEG) (الحد الأقصى لحجم الملف 50 ميجا بايت)</p>
                                <input type="file" id="blueprint-file-input" style="display: none;" accept=".pdf,.dxf,.dwg,.png,.jpg,.jpeg" onchange="handleFileSelected(this)">
                            </div>
                            
                            <!-- File metadata row -->
                            <div class="selected-file-row" id="selected-file-info" style="display: none;">
                                <div style="display: flex; align-items: center; gap: 0.6rem; max-width: 85%;">
                                    <span class="file-icon" style="color: var(--secondary); font-size: 1.1rem;"><i class="fa-solid fa-file-pdf"></i></span>
                                    <span class="file-name" id="selected-file-name">blueprint_file.pdf</span>
                                </div>
                                <button class="btn-remove-file" onclick="removeSelectedFile()" title="إزالة الملف"><i class="fa-solid fa-trash-can"></i></button>
                            </div>
                            
                            <!-- Processing progress bar -->
                            <div class="progress-container-upload" id="upload-progress-container" style="display: none;">
                                <div class="progress-bar-label">
                                    <span id="progress-status-text">جاري رفع الملف للمخدم...</span>
                                    <span id="upload-progress-percent">0%</span>
                                </div>
                                <div class="progress-bar-track">
                                    <div class="progress-bar-fill-upload" id="upload-progress-bar"></div>
                                </div>
                            </div>
                            
                            <button class="btn-sim" id="btn-start-upload-analysis" onclick="uploadAndAnalyzeBlueprint()" disabled>
                                <i class="fa-solid fa-calculator"></i> بدء التحليل الحسابي للملف
                            </button>
                        </div>
                        
                        <!-- Left Workspace: Dynamic Results Cards & API Response -->
                        <div class="simulator-sidebar">
                            
                            <!-- 1. Real Results card (shows dynamically after completion) -->
                            <div class="sim-meta" id="real-results-box" style="display: none; border-right: 3px solid var(--success); background: rgba(16, 185, 129, 0.02);">
                                <h4 style="color: var(--success); font-weight: 700;"><i class="fa-solid fa-chart-pie"></i> نتائج السحب الرقمي الفعلية</h4>
                                <div class="real-results-grid">
                                    <div class="result-item">
                                        <span>مقياس الرسم:</span>
                                        <strong id="res-scale">-</strong>
                                    </div>
                                    <div class="result-item">
                                        <span>إجمالي مسطح البناء (BUA):</span>
                                        <strong id="res-area">-</strong>
                                    </div>
                                    <div class="result-item">
                                        <span>إجمالي مساحة الأرضيات:</span>
                                        <strong id="res-net-area">-</strong>
                                    </div>
                                    <div class="result-item">
                                        <span>أطوال الجدران الإجمالية:</span>
                                        <strong id="res-wall-len">-</strong>
                                    </div>
                                    <div class="result-item">
                                        <span>عدد الأعمدة الخرسانية:</span>
                                        <strong id="res-columns">-</strong>
                                    </div>
                                    <div class="result-item">
                                        <span>العناصر الإنشائية:</span>
                                        <strong id="res-doors-windows">-</strong>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 2. Error Message box -->
                            <div class="sim-meta" id="real-error-box" style="display: none; border-right: 3px solid var(--danger); background: rgba(239, 68, 68, 0.04);">
                                <h4 style="color: var(--danger); font-weight: 700;"><i class="fa-solid fa-triangle-exclamation"></i> فشل تحليل المخطط</h4>
                                <p id="real-error-text" style="color: #fca5a5; font-size: 0.85rem; margin-top: 0.3rem;">نوع الملف غير مدعوم أو غير صالح.</p>
                            </div>

                            <div class="terminal-container">
                                <div class="terminal-header">
                                    <div class="terminal-dots">
                                        <span class="terminal-dot" style="background-color: var(--danger);"></span>
                                        <span class="terminal-dot" style="background-color: var(--warning);"></span>
                                        <span class="terminal-dot" style="background-color: var(--success);"></span>
                                    </div>
                                    <span>takeoff-real-response.json</span>
                                </div>
                                <div class="terminal-box" id="upload-terminal-out">
// النتائج الفعلية ستظهر هنا فور اكتمال معالجة المخطط المرفوع.
// اختر ملفاً واضغط على زر بدء التحليل.</div>
                            </div>
                        </div>
                        
                    </div>
                </div>

            </div>

            <!-- LEFT SIDE: CHARTS & HEALTH -->
            <div class="left-pane">
                <!-- 1. Server Health (CPU / RAM circular gauges) -->
                <div class="panel">
                    <div class="panel-header">
                        <h2><i class="fa-solid fa-server"></i> موارد الخادم في الوقت الفعلي</h2>
                    </div>
                    <div class="hardware-grid">
                        <div class="hw-circle-box">
                            <div class="hw-circle-container">
                                <svg class="circle-svg">
                                    <circle class="circle-bg" cx="45" cy="45" r="40" />
                                    <circle class="circle-fill-cpu" id="cpu-circle" cx="45" cy="45" r="40" />
                                </svg>
                                <span class="hw-value" id="cpu-text">0%</span>
                            </div>
                            <h4>استهلاك المعالج</h4>
                        </div>
                        <div class="hw-circle-box">
                            <div class="hw-circle-container">
                                <svg class="circle-svg">
                                    <circle class="circle-bg" cx="45" cy="45" r="40" />
                                    <circle class="circle-fill-ram" id="ram-circle" cx="45" cy="45" r="40" />
                                </svg>
                                <span class="hw-value" id="ram-text">0%</span>
                            </div>
                            <h4>استهلاك الذاكرة</h4>
                        </div>
                    </div>
                </div>

                <!-- 2. File Type breakdown (Chart.js donut) -->
                <div class="panel">
                    <div class="panel-header">
                        <h2><i class="fa-solid fa-chart-pie"></i> توزيع ملفات السحب</h2>
                    </div>
                    <div class="chart-wrap">
                        <canvas id="fileTypeChart"></canvas>
                    </div>
                </div>

                <!-- 3. Engine response times (Chart.js line) -->
                <div class="panel">
                    <div class="panel-header">
                        <h2><i class="fa-solid fa-chart-line"></i> سرعة استجابة المحرك (ثانية)</h2>
                    </div>
                    <div class="chart-wrap">
                        <canvas id="responseTimeChart"></canvas>
                    </div>
                </div>
            </div>

        </div>

        <!-- RECENT RUNS TABLE -->
        <div class="table-panel">
            <div class="panel-header">
                <h2><i class="fa-solid fa-list-check" style="color: var(--warning);"></i> سجل المعالجة التاريخي (آخر 10 عمليات)</h2>
            </div>
            <div class="table-responsive">
                <table id="runs-table">
                    <thead>
                        <tr>
                            <th>اسم ملف المخطط</th>
                            <th>نوع المخطط</th>
                            <th>حالة المعالجة</th>
                            <th>زمن المعالجة (ثانية)</th>
                            <th>توقيت العملية</th>
                        </tr>
                    </thead>
                    <tbody id="runs-table-body">
                        <tr>
                            <td colspan="5" class="no-data">جاري استدعاء البيانات من السيرفر...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Scripts and Logic -->
    <script>
        let fileTypeChartInstance = null;
        let responseTimeChartInstance = null;

        // Step Information Panel Data
        const stepDetails = {
            1: "مرحلة Ingestion: استلام ملف المخطط (PDF/DXF/DWG) عبر واجهة REST API. يقوم النظام بتوثيق هوية الطلب والتأكد من ملاءمته للشروط الفنية وسلامة بنية الملف قبل تمريره.",
            2: "مرحلة Vector Extraction: فك شفرة الملف الهندسي. لملفات أوتوكاد DXF يتم تفكيك الإحداثيات والمتجهات ثلاثية الأبعاد مباشرة. لملفات PDF يتم بناء صورة مسقط ثنائي الأبعاد بدقة 300 DPI.",
            3: "مرحلة AI Vision & OCR: قراءة الرموز البصرية وعلامات الرسم. نستخدم YOLOv11 المدرب خصيصاً على الرموز لتحديد الأبواب والنوافذ، ومحرك PaddleOCR لقراءة التسميات والأرقام والمقاييس المكتوبة.",
            4: "مرحلة Layer Classification: فرز العناصر الهندسية في طبقات منفصلة. عزل طبقة الجدران (الخطوط المستمرة)، وطبقة الأعمدة (الكيانات المصمتة)، والمساحات المعمارية الصافية.",
            5: "مرحلة Quantity Calculation: احتساب المقاييس بدقة متناهية. حساب المساحة الإجمالية للمبنى (Built-Up Area)، مجموع الجدران الطولية، وحساب أحجام وعينات العناصر المستهدفة للإنشاء.",
            6: "مرحلة Export & Structure: تحويل الأرقام المستخلصة لملف بيانات مهيكل بصيغة JSON متوافق مع نظام التسعير والحسابات في منصة بنيان بلس لإصدار الفواتير الفورية."
        };

        function showStepDetails(stepNum) {
            // Remove active classes
            document.querySelectorAll('.pipeline-step').forEach(step => {
                step.classList.remove('active');
            });
            // Set active
            document.getElementById(`step-${stepNum}`).classList.add('active');
            // Update details
            document.getElementById('sim-details-text').innerText = stepDetails[stepNum];
        }

        // Switch workspace modes
        function switchWorkmode(mode) {
            document.getElementById('tab-btn-sim').classList.remove('active');
            document.getElementById('tab-btn-upload').classList.remove('active');
            
            if (mode === 'simulate') {
                document.getElementById('tab-btn-sim').classList.add('active');
                document.getElementById('workmode-simulate').style.display = 'grid';
                document.getElementById('workmode-upload').style.display = 'none';
            } else {
                document.getElementById('tab-btn-upload').classList.add('active');
                document.getElementById('workmode-simulate').style.display = 'none';
                document.getElementById('workmode-upload').style.display = 'grid';
            }
        }

        // Real Blueprint Upload Logic
        const dropZone = document.getElementById('drop-zone');
        let selectedFile = null;

        if (dropZone) {
            ['dragenter', 'dragover'].forEach(eventName => {
                dropZone.addEventListener(eventName, (e) => {
                    e.preventDefault();
                    dropZone.classList.add('dragover');
                }, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, (e) => {
                    e.preventDefault();
                    dropZone.classList.remove('dragover');
                }, false);
            });

            dropZone.addEventListener('drop', (e) => {
                const dt = e.dataTransfer;
                const files = dt.files;
                if (files.length > 0) {
                    handleFile(files[0]);
                }
            });
        }

        function triggerFileInput() {
            document.getElementById('blueprint-file-input').click();
        }

        function handleFileSelected(input) {
            if (input.files.length > 0) {
                handleFile(input.files[0]);
            }
        }

        function handleFile(file) {
            const ext = file.name.split('.').pop().toLowerCase();
            if (!['pdf', 'dxf', 'dwg', 'png', 'jpg', 'jpeg'].includes(ext)) {
                alert('صيغة ملف غير مدعومة! الرجاء رفع ملف PDF، DXF، DWG، أو صور (PNG/JPG/JPEG) فقط.');
                return;
            }
            selectedFile = file;
            document.getElementById('selected-file-name').innerText = file.name;
            document.getElementById('selected-file-info').style.display = 'flex';
            document.getElementById('btn-start-upload-analysis').disabled = false;
            
            // Set file icon
            const fileIcon = document.querySelector('.file-icon i');
            fileIcon.className = 'fa-solid';
            if (ext === 'pdf') fileIcon.classList.add('fa-file-pdf');
            else if (ext === 'dxf') fileIcon.classList.add('fa-file-signature');
            else if (['png', 'jpg', 'jpeg'].includes(ext)) fileIcon.classList.add('fa-file-image');
            else fileIcon.classList.add('fa-file-invoice');
        }

        function removeSelectedFile() {
            selectedFile = null;
            document.getElementById('selected-file-info').style.display = 'none';
            document.getElementById('btn-start-upload-analysis').disabled = true;
            document.getElementById('blueprint-file-input').value = '';
            
            document.getElementById('real-results-box').style.display = 'none';
            document.getElementById('real-error-box').style.display = 'none';
            document.getElementById('upload-terminal-out').innerText = '// تم إزالة الملف. اختر ملفاً جديداً للبدء.';
        }

        function uploadAndAnalyzeBlueprint() {
            if (!selectedFile) return;
            
            const apiKey = document.getElementById('upload-api-key').value;
            const btn = document.getElementById('btn-start-upload-analysis');
            const progressContainer = document.getElementById('upload-progress-container');
            const progressBar = document.getElementById('upload-progress-bar');
            const progressPercent = document.getElementById('upload-progress-percent');
            const progressText = document.getElementById('progress-status-text');
            const terminal = document.getElementById('upload-terminal-out');
            
            const resultsBox = document.getElementById('real-results-box');
            const errorBox = document.getElementById('real-error-box');
            
            btn.disabled = true;
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> جاري الرفع والتحليل المباشر...';
            
            progressContainer.style.display = 'block';
            progressBar.style.width = '15%';
            progressPercent.innerText = '15%';
            progressText.innerText = 'جاري ضغط ورفع ملف المخطط...';
            
            resultsBox.style.display = 'none';
            errorBox.style.display = 'none';
            
            terminal.innerText = `// [UPLOADING]: جاري رفع الملف "${selectedFile.name}" إلى خادم معالجة الكميات...`;
            
            const formData = new FormData();
            formData.append('file', selectedFile);
            
            // Real progress tracking using XMLHttpRequest
            const xhr = new XMLHttpRequest();
            
            xhr.upload.addEventListener('progress', (e) => {
                if (e.lengthComputable) {
                    const percentComplete = Math.round((e.loaded / e.total) * 100);
                    // Map upload progress to 0% - 70% range of the bar
                    const visualPercent = Math.round(percentComplete * 0.7);
                    progressBar.style.width = visualPercent + '%';
                    progressPercent.innerText = visualPercent + '%';
                    progressText.innerText = `جاري رفع المخطط... (${percentComplete}%)`;
                }
            });
            
            xhr.addEventListener('load', () => {
                progressBar.style.width = '85%';
                progressPercent.innerText = '85%';
                progressText.innerText = 'تشغيل خوارزميات YOLOv11 والتحليل الهندسي...';
                terminal.innerText += `\n// [AI_ENGINE]: تم رفع الملف بنجاح. جاري البدء بالمعالجة والتعرف البصري...`;
                
                let json;
                try {
                    json = JSON.parse(xhr.responseText);
                } catch(e) {
                    handleError(xhr.responseText || 'استجابة السيرفر غير صالحة.');
                    return;
                }
                
                if (xhr.status >= 200 && xhr.status < 300) {
                    handleSuccess(json);
                } else {
                    handleError(json.detail || 'فشلت معالجة المخطط الهندسي.');
                }
            });
            
            xhr.addEventListener('error', () => {
                handleError('حدث خطأ أثناء الاتصال بالخادم.');
            });
            
            xhr.open('POST', `/v1/analyze-blueprint?cb=${Date.now()}`);
            xhr.setRequestHeader('X-API-KEY', apiKey);
            xhr.send(formData);
            
            function handleSuccess(data) {
                progressBar.style.width = '100%';
                progressPercent.innerText = '100%';
                progressText.innerText = 'اكتمل التحليل الهندسي!';
                terminal.innerText += `\n\n// [SUCCESS]: تم إتمام السحب التلقائي وتخريج ملف البيانات:\n` + JSON.stringify(data, null, 2);
                
                resultsBox.style.display = 'block';
                const takeoff = data.data;
                document.getElementById('res-scale').innerText = takeoff.scale || 'غير محدد';
                document.getElementById('res-area').innerText = (takeoff.total_built_up_area_m2 || 0) + ' م2';
                document.getElementById('res-net-area').innerText = (takeoff.net_floor_ceiling_area_m2 || 0) + ' م2';
                document.getElementById('res-wall-len').innerText = (takeoff.linear_wall_meters || 0) + ' م.ط';
                document.getElementById('res-columns').innerText = (takeoff.columns_detected || 0) + ' عمود خرساني';
                document.getElementById('res-doors-windows').innerText = `أبواب: ${takeoff.doors_count || 0} | نوافذ: ${takeoff.windows_count || 0}`;
                
                fetchServerData();
                finalizeUI();
            }
            
            function handleError(msg) {
                progressBar.style.width = '100%';
                progressPercent.innerText = 'خطأ';
                progressBar.style.background = 'var(--danger)';
                progressText.innerText = 'فشلت عملية التحليل.';
                
                terminal.innerText += `\n\n// [FAILED_ERROR]: حدثت مشكلة أثناء المعالجة!\n` + msg;
                
                errorBox.style.display = 'block';
                document.getElementById('real-error-text').innerText = msg;
                finalizeUI();
            }
            
            function finalizeUI() {
                btn.disabled = false;
                btn.innerHTML = '<i class="fa-solid fa-calculator"></i> بدء التحليل الحسابي للملف';
                setTimeout(() => {
                    progressContainer.style.display = 'none';
                    progressBar.style.background = 'linear-gradient(90deg, var(--primary), var(--secondary))';
                }, 6000);
            }
        }

        // Takeoff Simulation Animation (Tab 1)
        function runTakeoffSimulation() {
            const btn = document.getElementById('btn-start-simulation');
            const laser = document.getElementById('laser-bar');
            const detailsText = document.getElementById('sim-details-text');
            const statusLabel = document.getElementById('sim-status-label');
            const terminal = document.getElementById('terminal-out');
            
            // Elements
            const aiCols = document.getElementById('ai-detect-columns');
            const aiWalls = document.getElementById('ai-detect-walls');
            const aiAreas = document.getElementById('ai-detect-areas');
            const normalGeometry = document.getElementById('geometry-drawing');
            const normalLabels = document.getElementById('arabic-labels');
            
            // Disable button
            btn.disabled = true;
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> جاري محاكاة التحليل...';
            statusLabel.innerText = "جاري الفحص الرقمي...";
            statusLabel.style.color = "var(--secondary)";
            
            // Reset layers
            aiCols.style.display = "none";
            aiWalls.style.display = "none";
            aiAreas.style.display = "none";
            normalGeometry.style.stroke = "rgba(255, 255, 255, 0.35)";
            normalLabels.style.display = "block";
            terminal.innerText = "// جاري تهيئة بيئة التحليل الهندسي...";

            // Stage 1: File Ingestion (0.8s)
            showStepDetails(1);
            
            setTimeout(() => {
                // Stage 2: Preprocessing and scanning (2s)
                showStepDetails(2);
                document.getElementById('blueprint-box').classList.add('scan-active');
                terminal.innerText += "\\n[SYSTEM]: تم استقبال الملف بنجاح. نوع الملف المكتشف: PDF (مسقط ثنائي الأبعاد).";
                terminal.innerText += "\\n[ENGINE]: جاري تحليل شبكة المتجهات وتدريج مقياس الرسم (1:100)...";
                terminal.scrollTop = terminal.scrollHeight;
            }, 1000);

            setTimeout(() => {
                // Stage 3: AI Vision & Symbol Detection (2.5s)
                showStepDetails(3);
                aiCols.style.display = "block";
                terminal.innerText += "\\n[YOLOv11]: جاري تشغيل نموذج الكشف البصري على العناصر الهيكلية...";
                terminal.innerText += "\\n[YOLOv11]: تم الكشف عن عدد (9) أعمدة خرسانية (الثقة 96%).";
                terminal.innerText += "\\n[OCR]: تم تحديد مقياس الرسم الفعلي: 1:100 من نص الرسم.";
                terminal.scrollTop = terminal.scrollHeight;
            }, 3000);

            setTimeout(() => {
                // Stage 4: Layer Separation (2s)
                showStepDetails(4);
                aiWalls.style.display = "block";
                normalGeometry.style.stroke = "rgba(255, 255, 255, 0.08)";
                terminal.innerText += "\\n[LAYERS]: فصل وعزل الجدران الإنشائية وتصنيف الحواجز الداخلية...";
                terminal.innerText += "\\n[LAYERS]: إكمال مسارات الجدران وإلغاء التداخلات الهندسية الكاذبة.";
                terminal.scrollTop = terminal.scrollHeight;
            }, 5000);

            setTimeout(() => {
                // Stage 5: Net Area Calculations (2s)
                showStepDetails(5);
                aiAreas.style.display = "block";
                terminal.innerText += "\\n[CALCULATOR]: جاري قياس الفراغات وحساب المسافات الطولية والمساحات الصافية...";
                terminal.innerText += "\\n[CALCULATOR]: مساحة الغرفة (1): 13.29 م2 | مساحة المطبخ: 11.91 م2 | مساحة الصالة: 18.93 م2";
                terminal.scrollTop = terminal.scrollHeight;
            }, 7000);

            setTimeout(() => {
                // Stage 6: Export Structure & Result JSON (2s)
                showStepDetails(6);
                document.getElementById('blueprint-box').classList.remove('scan-active');
                statusLabel.innerText = "اكتمل السحب بنجاح";
                statusLabel.style.color = "var(--success)";
                
                const finalJson = {
                    "status": "success",
                    "data": {
                        "scale": "1:100",
                        "total_built_up_area_m2": 320.45,
                        "net_floor_ceiling_area_m2": 265.10,
                        "linear_wall_meters": 114.80,
                        "columns_detected": 9,
                        "doors_count": 2,
                        "windows_count": 3
                    }
                };
                
                terminal.innerText += "\\n\\n[SUCCESS]: تم سحب الكميات وتجهيز جدول البيانات الفوري:\\n" + JSON.stringify(finalJson, null, 2);
                terminal.scrollTop = terminal.scrollHeight;
                
                // Re-enable button
                btn.disabled = false;
                btn.innerHTML = '<i class="fa-solid fa-rotate-right"></i> إعادة المحاكاة التفاعلية';
            }, 9000);
        }

        // AJAX update of stats, hardware and logs
        function fetchServerData() {
            fetch('/v1/analytics-data')
                .then(res => {
                    if (res.status === 401) {
                        window.location.href = '/?logged_out=1';
                        return null;
                    }
                    return res.json();
                })
                .then(data => {
                    if (!data) return;
                    // Summary counts
                    document.getElementById('val-total').innerText = data.total_requests;
                    document.getElementById('val-success').innerText = data.success_requests;
                    document.getElementById('val-failed').innerText = data.failed_requests;
                    
                    // Avg duration calculate
                    let avg = 0;
                    if (data.durations && data.durations.length > 0) {
                        const sum = data.durations.reduce((a, b) => a + b, 0);
                        avg = (sum / data.durations.length).toFixed(2);
                    }
                    document.getElementById('val-avg-duration').innerText = avg + 's';

                    // Update Hardware Circular Gauges
                    updateHardwareGauge('cpu', data.cpu_percent || 0);
                    updateHardwareGauge('ram', data.ram_percent || 0);

                    // Update Recent Logs table
                    const tbody = document.getElementById('runs-table-body');
                    if (data.recent_runs && data.recent_runs.length > 0) {
                        tbody.innerHTML = '';
                        data.recent_runs.forEach(run => {
                            const statusBadge = run.status === 'success' ? 
                                '<span class="badge success"><i class="fa-solid fa-circle-check"></i> ناجح</span>' : 
                                '<span class="badge fail"><i class="fa-solid fa-circle-xmark"></i> فشل</span>';
                            const fileBadge = `<span class="badge file-${run.file_type}">${run.file_type.toUpperCase()}</span>`;
                            
                            tbody.innerHTML += `
                                <tr>
                                    <td>${run.filename}</td>
                                    <td>${fileBadge}</td>
                                    <td>${statusBadge}</td>
                                    <td style="font-family: var(--font-numbers); font-weight:600;">${run.duration}s</td>
                                    <td style="color: var(--text-muted); font-size: 0.8rem; font-family: var(--font-numbers);">${run.timestamp}</td>
                                </tr>
                            `;
                        });
                    } else {
                        tbody.innerHTML = '<tr><td colspan="5" class="no-data">لا توجد عمليات سحب سابقة مسجلة حالياً.</td></tr>';
                    }

                    // Update Charts
                    updateChartsData(data);
                })
                .catch(err => console.error("Error loading takeoff live data: ", err));
        }

        // Circular Gauge update utility
        function updateHardwareGauge(type, val) {
            document.getElementById(`${type}-text`).innerText = Math.round(val) + '%';
            const circle = document.getElementById(`${type}-circle`);
            const offset = 251.2 - (val / 100) * 251.2;
            circle.style.strokeDashoffset = offset;
        }

        // Chart.js initialization and updates
        function updateChartsData(data) {
            const typeCounts = [
                data.file_types.pdf || 0,
                data.file_types.dxf || 0,
                data.file_types.dwg || 0
            ];

            if (fileTypeChartInstance) {
                fileTypeChartInstance.data.datasets[0].data = typeCounts;
                fileTypeChartInstance.update();
            } else {
                const ctx = document.getElementById('fileTypeChart').getContext('2d');
                fileTypeChartInstance = new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: ['PDF', 'DXF', 'DWG'],
                        datasets: [{
                            data: typeCounts,
                            backgroundColor: ['#2563eb', '#f59e0b', '#06b6d4'],
                            borderWidth: 1,
                            borderColor: 'rgba(255, 255, 255, 0.08)'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        cutout: '70%',
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: { color: '#f3f4f6', font: { family: 'Cairo', size: 10 } }
                            }
                        }
                    }
                });
            }

            const durations = data.durations || [];
            const labels = durations.map((_, idx) => idx + 1);

            if (responseTimeChartInstance) {
                responseTimeChartInstance.data.labels = labels;
                responseTimeChartInstance.data.datasets[0].data = durations;
                responseTimeChartInstance.update();
            } else {
                const ctx = document.getElementById('responseTimeChart').getContext('2d');
                const gradient = ctx.createLinearGradient(0, 0, 0, 200);
                gradient.addColorStop(0, 'rgba(6, 182, 212, 0.3)');
                gradient.addColorStop(1, 'rgba(6, 182, 212, 0.01)');

                responseTimeChartInstance = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: durations,
                            borderColor: '#06b6d4',
                            backgroundColor: gradient,
                            fill: true,
                            tension: 0.35,
                            borderWidth: 2.5,
                            pointRadius: 1.5,
                            pointHoverRadius: 5
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: {
                            y: {
                                grid: { color: 'rgba(255, 255, 255, 0.04)' },
                                ticks: { color: '#9ca3af', font: { family: 'Outfit', size: 10 } }
                            },
                            x: {
                                grid: { display: false },
                                ticks: { color: '#9ca3af', font: { family: 'Outfit', size: 9 } }
                            }
                        }
                    }
                });
            }
        }

        // Run updates on start and every 6 seconds
        fetchServerData();
        setInterval(fetchServerData, 6000);
        // Dropdown User Menu Toggle
        function toggleUserMenu(event) {
            event.stopPropagation();
            const menu = document.getElementById('user-dropdown-menu');
            if (menu.style.display === 'block') {
                menu.style.display = 'none';
            } else {
                menu.style.display = 'block';
            }
        }

        // Close dropdown when clicking outside
        window.addEventListener('click', function() {
            const menu = document.getElementById('user-dropdown-menu');
            if (menu) menu.style.display = 'none';
        });

        // Edit Account Modal Controls
        function showEditAccountModal(event) {
            if (event) event.preventDefault();
            document.getElementById('edit-fullname').value = "{{USER_NAME}}";
            document.getElementById('edit-password').value = "";
            document.getElementById('edit-confirm-password').value = "";
            document.getElementById('edit-account-alert').style.display = 'none';
            document.getElementById('edit-account-modal').classList.add('active');
        }

        // Close modal helper
        function closeEditAccountModal(event) {
            if (event && event.target !== document.getElementById('edit-account-modal') && event.type === 'click') return;
            document.getElementById('edit-account-modal').classList.remove('active');
        }

        function submitEditAccount(e) {
            e.preventDefault();
            const name = document.getElementById('edit-fullname').value;
            const pass = document.getElementById('edit-password').value;
            const confirmPass = document.getElementById('edit-confirm-password').value;
            const alertBox = document.getElementById('edit-account-alert');
            const btn = document.getElementById('btn-save-account');

            if (pass !== confirmPass) {
                alertBox.style.display = 'block';
                alertBox.innerText = 'كلمات المرور غير متطابقة!';
                return;
            }

            btn.disabled = true;
            btn.innerText = 'جاري الحفظ...';
            alertBox.style.display = 'none';

            const formData = new URLSearchParams();
            formData.append('name', name);
            if (pass) {
                formData.append('password', pass);
            }

            fetch('/v1/edit-account', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: formData
            })
            .then(async res => {
                const data = await res.json();
                if (!res.ok) {
                    throw new Error(data.detail || 'فشل تعديل الحساب.');
                }
                return data;
            })
            .then(() => {
                alert('تم تعديل الحساب بنجاح!');
                window.location.href = '/?v=' + Date.now();
            })
            .catch(err => {
                alertBox.style.display = 'block';
                alertBox.style.background = 'rgba(239, 68, 68, 0.08)';
                alertBox.style.borderColor = 'rgba(239, 68, 68, 0.2)';
                alertBox.style.color = '#fca5a5';
                alertBox.innerText = err.message;
                btn.disabled = false;
                btn.innerText = 'حفظ التغييرات';
            });
        }

        // Add Employee Modal Controls
        function showAddEmployeeModal(event) {
            if (event) event.preventDefault();
            document.getElementById('add-username').value = "";
            document.getElementById('add-fullname').value = "";
            document.getElementById('add-password').value = "";
            document.getElementById('add-role').value = "employee";
            document.getElementById('add-employee-alert').style.display = 'none';
            document.getElementById('add-employee-modal').classList.add('active');
        }

        // Close modal helper
        function closeAddEmployeeModal(event) {
            if (event && event.target !== document.getElementById('add-employee-modal') && event.type === 'click') return;
            document.getElementById('add-employee-modal').classList.remove('active');
        }

        function submitAddEmployee(e) {
            e.preventDefault();
            const u = document.getElementById('add-username').value;
            const name = document.getElementById('add-fullname').value;
            const pass = document.getElementById('add-password').value;
            const role = document.getElementById('add-role').value;
            const alertBox = document.getElementById('add-employee-alert');
            const btn = document.getElementById('btn-save-employee');

            btn.disabled = true;
            btn.innerText = 'جاري الإضافة...';
            alertBox.style.display = 'none';

            const formData = new URLSearchParams();
            formData.append('username', u);
            formData.append('name', name);
            formData.append('password', pass);
            formData.append('role', role);

            fetch('/v1/add-employee', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: formData
            })
            .then(async res => {
                const data = await res.json();
                if (!res.ok) {
                    throw new Error(data.detail || 'فشل إضافة الموظف.');
                }
                return data;
            })
            .then(() => {
                alertBox.style.display = 'block';
                alertBox.style.background = 'rgba(16, 185, 129, 0.08)';
                alertBox.style.borderColor = 'rgba(16, 185, 129, 0.2)';
                alertBox.style.color = '#a7f3d0';
                alertBox.innerText = 'تم إضافة الموظف بنجاح!';
                setTimeout(() => {
                    closeAddEmployeeModal();
                }, 1000);
            })
            .catch(err => {
                alertBox.style.display = 'block';
                alertBox.style.background = 'rgba(239, 68, 68, 0.08)';
                alertBox.style.borderColor = 'rgba(239, 68, 68, 0.2)';
                alertBox.style.color = '#fca5a5';
                alertBox.innerText = err.message;
            })
            .finally(() => {
                btn.disabled = false;
                btn.innerText = 'إضافة الحساب';
            });
        }
    </script>

    <!-- Edit Account Modal -->
    <div id="edit-account-modal" class="modal-overlay" onclick="closeEditAccountModal(event)">
        <div class="modal-content" onclick="event.stopPropagation()">
            <div class="modal-header">
                <h3>تعديل الحساب</h3>
                <button class="close-btn" onclick="closeEditAccountModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="modal-alert" id="edit-account-alert"></div>
                <form id="edit-account-form" onsubmit="submitEditAccount(event)">
                    <div class="form-group">
                        <label>الاسم الكامل</label>
                        <input type="text" id="edit-fullname" required class="input-field" placeholder="مثال: محمد أحمد">
                    </div>
                    <div class="form-group">
                        <label>كلمة المرور الجديدة (اختياري)</label>
                        <input type="password" id="edit-password" class="input-field" placeholder="اتركها فارغة لعدم التغيير">
                    </div>
                    <div class="form-group">
                        <label>تأكيد كلمة المرور الجديدة</label>
                        <input type="password" id="edit-confirm-password" class="input-field" placeholder="أعد كتابة كلمة المرور">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn-cancel" onclick="closeEditAccountModal()">إلغاء</button>
                        <button type="submit" class="btn-save" id="btn-save-account">حفظ التغييرات</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Employee Modal -->
    <div id="add-employee-modal" class="modal-overlay" onclick="closeAddEmployeeModal(event)">
        <div class="modal-content" onclick="event.stopPropagation()">
            <div class="modal-header">
                <h3>إضافة موظف جديد</h3>
                <button class="close-btn" onclick="closeAddEmployeeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="modal-alert" id="add-employee-alert"></div>
                <form id="add-employee-form" onsubmit="submitAddEmployee(event)">
                    <div class="form-group">
                        <label>اسم المستخدم (لا يحتوي على مسافات)</label>
                        <input type="text" id="add-username" required class="input-field" placeholder="username" pattern="^[a-zA-Z0-9_]+$">
                    </div>
                    <div class="form-group">
                        <label>الاسم الكامل</label>
                        <input type="text" id="add-fullname" required class="input-field" placeholder="الاسم الكامل">
                    </div>
                    <div class="form-group">
                        <label>كلمة المرور</label>
                        <input type="password" id="add-password" required class="input-field" placeholder="••••••••">
                    </div>
                    <div class="form-group">
                        <label>دور المستخدم</label>
                        <select id="add-role" required class="input-field" style="background-image: none;">
                            <option value="employee">موظف (Employee)</option>
                            <option value="admin">مدير (Admin)</option>
                        </select>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn-cancel" onclick="closeAddEmployeeModal()">إلغاء</button>
                        <button type="submit" class="btn-save" id="btn-save-employee">إضافة الحساب</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
"""
    
    admin_menu = ""
    if role == "admin":
        admin_menu = """
        <a href="#" onclick="showAddEmployeeModal(event)" style="display: flex; align-items: center; gap: 0.5rem; padding: 0.7rem 1rem; color: var(--text-main); text-decoration: none; font-size: 0.85rem; transition: background 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.05)'" onmouseout="this.style.background='transparent'">
            <i class="fa-solid fa-user-plus" style="color: var(--success); width: 16px;"></i> إضافة موظف
        </a>
        """
    
    html_content = html_content.replace("{{USER_NAME}}", name)
    html_content = html_content.replace("{{ADMIN_ONLY_MENU}}", admin_menu)
    return html_content

@app.get("/index.php", response_class=HTMLResponse)
@app.get("/index.html", response_class=HTMLResponse)
@app.get("/", response_class=HTMLResponse)
def serve_dashboard(request: Request, response: Response):
    """Serves the login page or the interactive premium dashboard depending on session"""
    user = get_current_user(request)
    
    # Set cache-control headers to prevent browser caching of the login state
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"
    
    if not user:
        response.headers["Clear-Site-Data"] = '"cache"'
        return serve_login_page()
    return serve_dashboard_html(user["username"], user["name"], user["role"])
