<?php
if (!file_exists(__DIR__ . '/config.php')) {
    header('Location: install.php');
    exit;
}
require_once __DIR__ . '/config.php';
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>محرر الصور Fouad AI</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      darkMode: 'class',
      theme: {
        extend: {
          fontFamily: { sans: ['Tajawal', 'Cairo', 'system-ui', 'sans-serif'] },
          colors: {
            primary: '#34d399',
            destructive: '#ef4444',
            muted: '#1e1e2e',
            card: '#111118',
            border: 'rgba(255,255,255,0.08)',
          }
        }
      }
    }
  </script>
  <style>
    * { box-sizing: border-box; }
    body { font-family: 'Tajawal', 'Cairo', system-ui, sans-serif; }
    .glass {
      background: rgba(255,255,255,0.03);
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
      border-bottom: 1px solid rgba(255,255,255,0.08);
    }
    .glass-card {
      background: rgba(255,255,255,0.03);
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
      border: 1px solid rgba(255,255,255,0.08);
      border-radius: 1rem;
    }
    .gradient-text {
      background: linear-gradient(to right, #34d399, #22d3ee);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 3px; }
    ::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.2); }
    .modal-backdrop {
      background: rgba(0,0,0,0.6);
      backdrop-filter: blur(4px);
      -webkit-backdrop-filter: blur(4px);
    }
    .toggle-switch {
      position: relative;
      width: 44px;
      height: 24px;
      background: rgba(255,255,255,0.1);
      border-radius: 12px;
      cursor: pointer;
      transition: background 0.3s;
    }
    .toggle-switch.active {
      background: #34d399;
    }
    .toggle-switch::after {
      content: '';
      position: absolute;
      top: 2px;
      right: 2px;
      width: 20px;
      height: 20px;
      background: white;
      border-radius: 50%;
      transition: transform 0.3s;
    }
    .toggle-switch.active::after {
      transform: translateX(-20px);
    }
    .comparison-container { position: relative; overflow: hidden; user-select: none; touch-action: none; }
    .comparison-slider-line {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 3px;
      background: white;
      transform: translateX(-50%);
      z-index: 10;
      pointer-events: none;
    }
    .comparison-slider-handle {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: white;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 8px rgba(0,0,0,0.4);
      pointer-events: auto;
      cursor: ew-resize;
    }
    .fade-in {
      animation: fadeIn 0.3s ease forwards;
    }
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }
    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    .animate-spin { animation: spin 1s linear infinite; }
    @keyframes pulse {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.5; }
    }
    .animate-pulse { animation: pulse 2s ease-in-out infinite; }
    .upload-area-active {
      background: rgba(52, 211, 153, 0.08) !important;
      border-color: #34d399 !important;
    }
    .btn-primary {
      background: linear-gradient(135deg, #34d399, #22d3ee);
      color: #0a0a0f;
      font-weight: 600;
      padding: 0.5rem 1rem;
      border-radius: 0.5rem;
      transition: all 0.2s;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 0.5rem;
      border: none;
      cursor: pointer;
      font-family: inherit;
      font-size: 0.875rem;
    }
    .btn-primary:hover { opacity: 0.9; transform: translateY(-1px); }
    .btn-primary:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
    .btn-ghost {
      background: transparent;
      color: rgba(255,255,255,0.7);
      padding: 0.5rem 0.75rem;
      border-radius: 0.5rem;
      transition: all 0.2s;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 0.5rem;
      border: none;
      cursor: pointer;
      font-family: inherit;
      font-size: 0.875rem;
    }
    .btn-ghost:hover { background: rgba(255,255,255,0.05); color: white; }
    .btn-ghost.active { background: rgba(52,211,153,0.15); color: #34d399; }
    .btn-outline {
      background: transparent;
      color: rgba(255,255,255,0.8);
      padding: 0.5rem 1rem;
      border-radius: 0.5rem;
      border: 1px solid rgba(255,255,255,0.15);
      transition: all 0.2s;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 0.5rem;
      cursor: pointer;
      font-family: inherit;
      font-size: 0.875rem;
    }
    .btn-outline:hover { border-color: rgba(255,255,255,0.3); background: rgba(255,255,255,0.03); }
    .btn-outline:disabled { opacity: 0.5; cursor: not-allowed; }
    .input-field {
      width: 100%;
      background: rgba(255,255,255,0.05);
      border: 1px solid rgba(255,255,255,0.1);
      border-radius: 0.5rem;
      padding: 0.625rem 0.875rem;
      color: white;
      font-family: inherit;
      font-size: 0.875rem;
      outline: none;
      transition: border-color 0.2s;
    }
    .input-field:focus { border-color: #34d399; }
    .input-field::placeholder { color: rgba(255,255,255,0.3); }
    textarea.input-field { resize: none; }
    .progress-bar {
      width: 100%;
      height: 8px;
      background: rgba(255,255,255,0.1);
      border-radius: 4px;
      overflow: hidden;
    }
    .progress-bar-fill {
      height: 100%;
      background: linear-gradient(to right, #34d399, #22d3ee);
      border-radius: 4px;
      transition: width 0.3s ease;
    }
    .tools-scroll {
      display: flex;
      gap: 0.5rem;
      overflow-x: auto;
      padding-bottom: 0.5rem;
      -webkit-overflow-scrolling: touch;
      scrollbar-width: none;
    }
    .tools-scroll::-webkit-scrollbar { display: none; }
    @media (min-width: 1024px) {
      .tools-scroll {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        overflow-x: visible;
      }
    }
  </style>
  <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
</head>
<body class="bg-gray-950 text-white min-h-screen">
  <div id="app" class="min-h-screen flex flex-col"></div>

  <script>
  // ===== SVG ICONS =====
  const icons = {
    Upload: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>',
    Image: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>',
    Sparkles: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/><path d="M5 3v4"/><path d="M19 17v4"/><path d="M3 5h4"/><path d="M17 19h4"/></svg>',
    Download: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',
    ArrowRight: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>',
    Palette: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="13.5" cy="6.5" r=".5" fill="currentColor"/><circle cx="17.5" cy="10.5" r=".5" fill="currentColor"/><circle cx="8.5" cy="7.5" r=".5" fill="currentColor"/><circle cx="6.5" cy="12.5" r=".5" fill="currentColor"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"/></svg>',
    Camera: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>',
    Layers: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/><path d="m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65"/><path d="m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65"/></svg>',
    SlidersHorizontal: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" x2="4" y1="21" y2="14"/><line x1="4" x2="4" y1="10" y2="3"/><line x1="12" x2="12" y1="21" y2="12"/><line x1="12" x2="12" y1="8" y2="3"/><line x1="20" x2="20" y1="21" y2="16"/><line x1="20" x2="20" y1="12" y2="3"/><line x1="2" x2="6" y1="14" y2="14"/><line x1="10" x2="14" y1="8" y2="8"/><line x1="18" x2="22" y1="16" y2="16"/></svg>',
    Loader2: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',
    Check: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>',
    Trash2: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>',
    RotateCcw: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>',
    Eye: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>',
    Wand2: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72Z"/><path d="m14 7 3 3"/><path d="M5 6v4"/><path d="M19 14v4"/><path d="M10 2v2"/><path d="M7 8H3"/><path d="M21 16h-4"/><path d="M11 3H9"/></svg>',
    Sun: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>',
    Paintbrush: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18.37 2.63-1 .98a2 2 0 0 0 0 2.83l6.19 6.19a2 2 0 0 0 2.83 0l.98-1A2.57 2.57 0 0 0 26.05 8l-4.05-4.05a2.57 2.57 0 0 0-3.63 0Z" transform="scale(0.75) translate(4,4)"/><path d="M9.5 13.5 3 20l1.5 1.5L11 15"/><path d="M14.5 8.5l-5 5"/></svg>',
    Film: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="20" x="2" y="2" rx="2.18" ry="2.18"/><line x1="7" x2="7" y1="2" y2="22"/><line x1="17" x2="17" y1="2" y2="22"/><line x1="2" x2="22" y1="12" y2="12"/><line x1="2" x2="7" y1="7" y2="7"/><line x1="2" x2="7" y1="17" y2="17"/><line x1="17" x2="22" y1="17" y2="17"/><line x1="17" x2="22" y1="7" y2="7"/></svg>',
    Pencil: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/></svg>',
    History: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/></svg>',
    ChevronLeft: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 18-6-6 6-6"/></svg>',
    X: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>',
    Settings: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>',
    Megaphone: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m3 11 18-5v12L3 14v-3z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg>',
    Code: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>',
    LogIn: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" x2="3" y1="12" y2="12"/></svg>',
    LogOut: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" x2="9" y1="12" y2="12"/></svg>',
    Shield: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/></svg>',
    WandSparkles: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72Z"/><path d="m14 7 3 3"/><path d="M5 6v4"/><path d="M19 14v4"/><path d="M10 2v2"/><path d="M7 8H3"/><path d="M21 16h-4"/><path d="M11 3H9"/></svg>',
    Square: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2"/></svg>',
    RectangleVertical: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="10" height="20" x="7" y="2" rx="2"/></svg>',
    Monitor: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/></svg>',
    GripVertical: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="12" r="1"/><circle cx="9" cy="5" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="15" cy="19" r="1"/></svg>'
  };

  function icon(name, size) {
    const s = size || 16;
    const svg = icons[name] || icons.Image;
    return svg.replace(/width="24"/g, 'width="'+s+'"').replace(/height="24"/g, 'height="'+s+'"');
  }

  // ===== EDIT TOOLS =====
  const EDIT_TOOLS = [
    { id: 'oil-painting', label: 'لوحة زيتية', iconName: 'Paintbrush', prompt: 'Transform this image into an oil painting style, with visible brushstrokes and rich, vibrant colors, maintain the composition and subject', color: 'from-amber-500/20 to-orange-600/20' },
    { id: 'cartoon', label: 'رسم كرتوني', iconName: 'Pencil', prompt: 'Transform this image into a cartoon illustration style, with bold outlines, flat colors, and simplified shapes, keep the main subject recognizable', color: 'from-pink-500/20 to-rose-600/20' },
    { id: 'bw', label: 'أبيض وأسود', iconName: 'Camera', prompt: 'Convert this image to a stunning black and white photograph with high contrast and dramatic lighting, professional photography style', color: 'from-gray-500/20 to-gray-700/20' },
    { id: 'golden-hour', label: 'إضاءة ذهبية', iconName: 'Sun', prompt: 'Apply warm golden hour lighting to this image, with beautiful warm tones, soft shadows, and a magical sunset glow, maintain all subjects', color: 'from-yellow-500/20 to-amber-600/20' },
    { id: 'enhance', label: 'تحسين الجودة', iconName: 'Sparkles', prompt: 'Enhance the quality and sharpness of this image, improve colors, add more detail and clarity, make it look professional and high-resolution', color: 'from-emerald-500/20 to-teal-600/20' },
    { id: 'bg-remove', label: 'خلفية احترافية', iconName: 'Layers', prompt: 'Enhance this photo with a clean neutral studio background while preserving the main subject naturally', color: 'from-cyan-500/20 to-blue-600/20' },
    { id: 'cinematic', label: 'تأثير سينمائي', iconName: 'Film', prompt: 'Apply a cinematic color grading to this image, with deep shadows, teal and orange tones, letterbox style, dramatic and moody atmosphere', color: 'from-violet-500/20 to-purple-600/20' },
    { id: 'illustration', label: 'أسلوب رسومي', iconName: 'Palette', prompt: 'Transform this image into a digital illustration style, clean lines, artistic rendering, vibrant but harmonious colors, maintain the scene composition', color: 'from-fuchsia-500/20 to-pink-600/20' },
  ];

  const SIZE_OPTIONS = [
    { id: 'square', label: 'مربع', iconName: 'Square', desc: '1024×1024', color: 'from-emerald-500/20 to-emerald-600/5' },
    { id: 'portrait', label: 'عمودي', iconName: 'RectangleVertical', desc: '864×1152', color: 'from-amber-500/20 to-amber-600/5' },
    { id: 'landscape', label: 'أفقي', iconName: 'Monitor', desc: '1344×768', color: 'from-emerald-500/20 to-emerald-600/5' },
    { id: 'wide', label: 'عريض', iconName: 'Monitor', desc: '1440×720', color: 'from-violet-500/20 to-violet-600/5' },
  ];

  const POSITION_OPTIONS = [
    { value: 'top', label: 'أعلى الصفحة' },
    { value: 'above-upload', label: 'فوق منطقة الرفع' },
    { value: 'below-features', label: 'أسفل المميزات' },
  ];

  const EXAMPLE_PROMPTS = [
    'غروب على شاطئ بصخور ملساء',
    'مدينة مستقبلية بالليل',
    'طائر فيلمنق زاهي الألوان',
    'قرية جبلية وسط الضباب',
  ];

  // ===== APPLICATION STATE =====
  const App = {
    state: {
      view: 'home',
      isAdmin: false,
      isAdminLoading: true,
      showLoginDialog: false,
      showBannerDialog: false,
      originalImage: null,
      originalFileName: null,
      editedImage: null,
      isEditing: false,
      editProgress: 0,
      editError: null,
      analysis: null,
      customPrompt: '',
      selectedTool: null,
      editCount: 0,
      isAnalyzing: false,
      lastEditArgs: null,
      isUploading: false,
      isDragOver: false,
      projects: [],
      isGalleryLoading: true,
      // Generate view
      genPrompt: '',
      genSelectedSize: 'square',
      genIsGenerating: false,
      genImage: null,
      genError: null,
      genProgress: 0,
      genProgressMsg: '',
      genPollInterval: null,
      // Banner state
      banners: { top: null, 'above-upload': null, 'below-features': null },
      bannerDismissed: {},
      // Banner admin
      bannerAdType: 'image',
      bannerImageUrl: '',
      bannerAdCode: '',
      bannerLinkUrl: '',
      bannerText: '',
      bannerActive: false,
      bannerPosition: 'top',
      bannerSaving: false,
      bannerUploading: false,
      bannerMessage: null,
      // Login
      loginUsername: '',
      loginPassword: '',
      loginLoading: false,
      loginError: null,
      // Toast
      toast: null,
      toastTimer: null,
    },

    init() {
      this.checkSession();
      this.fetchBanner('top');
      this.fetchBanner('above-upload');
      this.fetchBanner('below-features');
      this.render();

      // Global event delegation
      document.getElementById('app').addEventListener('click', (e) => {
        this.handleClick(e);
      });
      document.getElementById('app').addEventListener('input', (e) => {
        this.handleInput(e);
      });
      document.getElementById('app').addEventListener('submit', (e) => {
        this.handleSubmit(e);
      });
      document.getElementById('app').addEventListener('dragover', (e) => {
        this.handleDragOver(e);
      });
      document.getElementById('app').addEventListener('dragleave', (e) => {
        this.handleDragLeave(e);
      });
      document.getElementById('app').addEventListener('drop', (e) => {
        this.handleDrop(e);
      });
      document.getElementById('app').addEventListener('change', (e) => {
        this.handleChange(e);
      });
      document.getElementById('app').addEventListener('pointerdown', (e) => {
        this.handlePointerDown(e);
      });
      document.getElementById('app').addEventListener('pointermove', (e) => {
        this.handlePointerMove(e);
      });
      document.getElementById('app').addEventListener('pointerup', (e) => {
        this.handlePointerUp(e);
      });
    },

    setState(partial) {
      Object.assign(this.state, partial);
    },

    showToast(message, type) {
      if (this.state.toastTimer) clearTimeout(this.state.toastTimer);
      this.setState({ toast: { message, type: type || 'success' } });
      this.state.toastTimer = setTimeout(() => {
        this.setState({ toast: null });
        this.render();
      }, 5000);
      this.render();
    },

    async checkSession() {
      try {
        const res = await fetch('/api/auth');
        if (!res.ok) {
          this.setState({ isAdmin: false, isAdminLoading: false });
          this.render();
          return;
        }
        const session = await res.json();
        this.setState({ isAdmin: session.user && session.user.role === 'admin', isAdminLoading: false });
      } catch {
        this.setState({ isAdmin: false, isAdminLoading: false });
      }
      this.render();
    },

    async fetchBanner(position) {
      try {
        const res = await fetch('/api/banner');
        if (!res.ok) return;
        const data = await res.json();
        if (data.banner && data.banner.position === position) {
          const banners = Object.assign({}, this.state.banners);
          banners[position] = data.banner;
          this.setState({ banners });
          this.render();
        }
      } catch {}
    },

    // ===== RENDERING =====
    render() {
      const app = document.getElementById('app');
      let html = this.renderHeader();
      html += '<div class="w-full px-4 sm:px-6 lg:px-8">' + this.renderBanner('top') + '</div>';

      if (this.state.view === 'home') {
        html += this.renderHomeView();
      } else if (this.state.view === 'editor') {
        html += this.renderEditorView();
      } else if (this.state.view === 'gallery') {
        html += this.renderGalleryView();
      } else if (this.state.view === 'generate') {
        html += this.renderGenerateView();
      }

      html += this.renderFooter();

      if (this.state.showLoginDialog) {
        html += this.renderLoginDialog();
      }
      if (this.state.showBannerDialog) {
        html += this.renderBannerAdminDialog();
      }
      if (this.state.toast) {
        html += this.renderToast();
      }

      app.innerHTML = html;

      // Restore input values that may be lost on re-render
      this.restoreInputValues();

      // Initialize comparison slider if in editor with edited image
      if (this.state.view === 'editor' && this.state.editedImage) {
        this.initComparisonSlider();
      }
    },

    restoreInputValues() {
      if (this.state.view === 'editor') {
        const ta = document.getElementById('custom-prompt-area');
        if (ta && document.activeElement !== ta) ta.value = this.state.customPrompt;
      }
      if (this.state.view === 'generate') {
        const ta = document.getElementById('gen-prompt-area');
        if (ta && document.activeElement !== ta) ta.value = this.state.genPrompt;
      }
      if (this.state.showLoginDialog) {
        const u = document.getElementById('login-username');
        const p = document.getElementById('login-password');
        if (u && document.activeElement !== u) u.value = this.state.loginUsername;
        if (p && document.activeElement !== p) p.value = this.state.loginPassword;
      }
      if (this.state.showBannerDialog) {
        if (this.state.bannerAdType === 'image') {
          const link = document.getElementById('banner-link-url');
          const text = document.getElementById('banner-text-overlay');
          if (link && document.activeElement !== link) link.value = this.state.bannerLinkUrl;
          if (text && document.activeElement !== text) text.value = this.state.bannerText;
        } else {
          const code = document.getElementById('banner-ad-code');
          if (code && document.activeElement !== code) code.value = this.state.bannerAdCode;
        }
      }
    },

    // ===== HEADER =====
    renderHeader() {
      const s = this.state;
      const navBtn = (view, label, iconName) => {
        const active = s.view === view;
        return '<button data-action="nav" data-view="' + view + '" class="btn-ghost gap-2 ' + (active ? 'active' : '') + '">' +
          icon(iconName, 16) +
          '<span class="hidden sm:inline">' + label + '</span>' +
          '</button>';
      };

      let adminBtns = '';
      if (!s.isAdminLoading) {
        if (s.isAdmin) {
          adminBtns =
            '<button data-action="open-banner-admin" class="btn-ghost mr-1" title="إدارة البانر">' + icon('Settings', 16) + '</button>' +
            '<button data-action="logout" class="btn-ghost text-red-400 hover:text-red-300 hover:bg-red-500/10" title="تسجيل الخروج">' + icon('LogOut', 16) + '</button>';
        } else {
          adminBtns =
            '<button data-action="open-login" class="btn-ghost mr-1" title="دخول المدير">' + icon('LogIn', 16) + '</button>';
        }
      }

      return '<header class="glass sticky top-0 z-50">' +
        '<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">' +
          '<button data-action="nav" data-view="home" class="flex items-center gap-3 group">' +
            '<div class="w-9 h-9 rounded-lg bg-emerald-500/20 flex items-center justify-center">' +
              icon('Wand2', 20) +
            '</div>' +
            '<span class="text-lg font-bold gradient-text">محرر الصور Fouad AI</span>' +
          '</button>' +
          '<nav class="flex items-center gap-1">' +
            navBtn('home', 'الرئيسية', 'Image') +
            navBtn('gallery', 'المعرض', 'History') +
            navBtn('generate', 'توليد الصور', 'WandSparkles') +
            adminBtns +
          '</nav>' +
        '</div>' +
      '</header>';
    },

    // ===== BANNER DISPLAY =====
    renderBanner(position) {
      const banner = this.state.banners[position];
      if (!banner || !banner.active || this.state.bannerDismissed[position]) return '';

      if (banner.adType === 'external' && banner.adCode) {
        return '<div class="relative w-full max-w-4xl mx-auto my-3 fade-in">' +
          '<div class="rounded-xl overflow-hidden bg-white/[0.02] border border-white/[0.08] p-1">' +
            '<div class="w-full min-h-[60px] flex items-center justify-center">' + banner.adCode + '</div>' +
          '</div>' +
          '<button data-action="dismiss-banner" data-position="' + position + '" class="absolute -top-2 -left-2 w-6 h-6 rounded-full bg-white/10 text-white/60 flex items-center justify-center hover:bg-white/20 hover:text-white transition-colors border border-white/10">' +
            icon('X', 12) +
          '</button>' +
        '</div>';
      }

      if (!banner.imageUrl) return '';

      let wrapper = '<div class="block relative rounded-xl overflow-hidden">';
      let closeBtn = '';
      if (banner.text) {
        wrapper = '<a href="' + this.escHtml(banner.linkUrl || '#') + '" target="_blank" rel="noopener noreferrer" class="block relative rounded-xl overflow-hidden">';
      }

      closeBtn = '<button data-action="dismiss-banner" data-position="' + position + '" class="absolute top-2 left-2 w-6 h-6 rounded-full bg-black/50 text-white flex items-center justify-center hover:bg-black/70 transition-colors z-10">' + icon('X', 12) + '</button>';

      return '<div class="relative w-full max-w-4xl mx-auto my-3 fade-in">' +
        wrapper +
          '<img src="' + banner.imageUrl + '" alt="' + (banner.text || 'إعلان') + '" class="w-full h-auto object-cover max-h-48 rounded-xl" />' +
          (banner.text ? '<div class="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent flex items-end p-4"><p class="text-white text-sm sm:text-base font-medium">' + banner.text + '</p></div>' : '') +
        (banner.linkUrl ? '</a>' : '</div>') +
        closeBtn +
      '</div>';
    },

    // ===== LOGIN DIALOG =====
    renderLoginDialog() {
      const s = this.state;
      const canSubmit = s.loginUsername.trim() && s.loginPassword.trim() && !s.loginLoading;

      return '<div class="fixed inset-0 z-[100] flex items-center justify-center modal-backdrop fade-in" data-action="close-login-backdrop">' +
        '<div class="bg-gray-900 border border-white/10 rounded-xl p-6 max-w-sm w-full mx-4 shadow-2xl fade-in" onclick="event.stopPropagation()">' +
          '<div class="flex items-center justify-between mb-4">' +
            '<h2 class="flex items-center gap-2 text-lg font-semibold">' +
              icon('Shield', 20) + ' تسجيل دخول المدير' +
            '</h2>' +
            '<button data-action="close-login" class="btn-ghost p-1">' + icon('X', 18) + '</button>' +
          '</div>' +
          '<form id="login-form" class="space-y-4">' +
            '<div class="space-y-2">' +
              '<label class="text-sm text-white/70">اسم المستخدم</label>' +
              '<input id="login-username" type="text" value="' + this.escHtml(s.loginUsername) + '" placeholder="admin" autocomplete="username" autofocus class="input-field" />' +
            '</div>' +
            '<div class="space-y-2">' +
              '<label class="text-sm text-white/70">كلمة المرور</label>' +
              '<input id="login-password" type="password" value="' + this.escHtml(s.loginPassword) + '" placeholder="••••••••" autocomplete="current-password" class="input-field" />' +
            '</div>' +
            (s.loginError ? '<p class="text-sm text-red-400 bg-red-500/10 p-2 rounded-lg text-center">' + this.escHtml(s.loginError) + '</p>' : '') +
            '<button type="submit" class="btn-primary w-full gap-2" ' + (canSubmit ? '' : 'disabled') + '>' +
              (s.loginLoading ? '<span class="animate-spin inline-block">' + icon('Loader2', 16) + '</span> جارٍ التحقق...' : icon('LogIn', 16) + ' تسجيل الدخول') +
            '</button>' +
          '</form>' +
        '</div>' +
      '</div>';
    },

    // ===== BANNER ADMIN DIALOG =====
    renderBannerAdminDialog() {
      const s = this.state;
      const isImage = s.bannerAdType === 'image';

      let imageSection = '';
      if (isImage) {
        let uploadContent = '';
        if (s.bannerUploading) {
          uploadContent = '<div class="flex items-center justify-center gap-2 py-2"><span class="animate-spin inline-block text-emerald-400">' + icon('Loader2', 20) + '</span><span class="text-sm text-white/50">جارٍ الرفع...</span></div>';
        } else if (s.bannerImageUrl) {
          uploadContent = '<div class="space-y-2"><img src="' + this.escHtml(s.bannerImageUrl) + '" alt="بانر" class="w-full h-24 object-cover rounded-md" /><p class="text-xs text-white/50">انقر لتغيير الصورة</p></div>';
        } else {
          uploadContent = '<div class="py-2"><div class="mx-auto text-white/20 mb-2">' + icon('Upload', 32) + '</div><p class="text-sm text-white/50">انقر لاختيار صورة البانر</p><p class="text-xs text-white/30 mt-1">PNG, JPG, WEBP — حتى 2 ميجا</p></div>';
        }

        imageSection = '<div class="space-y-2">' +
          '<label class="text-sm text-white/70">صورة البانر</label>' +
          '<div data-action="banner-upload-click" class="relative rounded-lg border-2 border-dashed p-4 text-center cursor-pointer transition-all ' + (s.bannerImageUrl ? 'border-emerald-500/30' : 'border-white/20 hover:border-emerald-500/50') + '">' +
            '<input id="banner-file-input" type="file" accept="image/*" class="hidden" />' +
            uploadContent +
          '</div>' +
          '<div class="space-y-2 mt-3">' +
            '<label class="text-sm text-white/70">رابط الإعلان (اختياري)</label>' +
            '<input id="banner-link-url" type="text" value="' + this.escHtml(s.bannerLinkUrl) + '" placeholder="https://example.com" dir="ltr" class="input-field" />' +
          '</div>' +
          '<div class="space-y-2 mt-3">' +
            '<label class="text-sm text-white/70">نص على البانر (اختياري)</label>' +
            '<input id="banner-text-overlay" type="text" value="' + this.escHtml(s.bannerText) + '" placeholder="عنوان الإعلان..." class="input-field" />' +
          '</div>' +
        '</div>';
      }

      let externalSection = '';
      if (!isImage) {
        externalSection = '<div class="space-y-2">' +
          '<label class="text-sm text-white/70">كود الإعلان الخارجي</label>' +
          '<p class="text-xs text-white/40">الصق كود الإعلان من جوجل أدسنس أو أي شبكة إعلانية أخرى</p>' +
          '<textarea id="banner-ad-code" class="input-field min-h-[120px] font-mono text-xs" dir="ltr" placeholder="&lt;script async src=&quot;https://pagead2.googlesyndication.com/...&quot;&gt;&lt;/script&gt;">' + this.escHtml(s.bannerAdCode) + '</textarea>' +
        '</div>';
      }

      let messageHtml = '';
      if (s.bannerMessage) {
        const msgColor = s.bannerMessage.type === 'success' ? 'bg-emerald-500/10 text-emerald-400' : 'bg-red-500/10 text-red-400';
        messageHtml = '<div class="text-sm p-3 rounded-lg ' + msgColor + '">' + this.escHtml(s.bannerMessage.text) + '</div>';
      }

      const positionBtns = POSITION_OPTIONS.map(opt => {
        const active = s.bannerPosition === opt.value;
        return '<button data-action="banner-position" data-value="' + opt.value + '" class="p-2 rounded-lg border text-xs font-medium transition-all ' +
          (active ? 'border-emerald-500 bg-emerald-500/10 text-emerald-400' : 'border-white/10 hover:border-emerald-500/30 text-white/50') + '">' + opt.label + '</button>';
      }).join('');

      const canSave = isImage ? !!s.bannerImageUrl : !!s.bannerAdCode.trim();

      return '<div class="fixed inset-0 z-[100] flex items-center justify-center modal-backdrop fade-in" data-action="close-banner-backdrop">' +
        '<div class="bg-gray-900 border border-white/10 rounded-xl p-6 max-w-md w-full mx-4 shadow-2xl max-h-[90vh] overflow-y-auto fade-in" onclick="event.stopPropagation()">' +
          '<div class="flex items-center justify-between mb-4">' +
            '<h2 class="flex items-center gap-2 text-lg font-semibold">' + icon('Megaphone', 20) + ' إدارة البانر الإعلاني</h2>' +
            '<button data-action="close-banner" class="btn-ghost p-1">' + icon('X', 18) + '</button>' +
          '</div>' +
          '<div class="space-y-4">' +
            // Ad type
            '<div class="space-y-2">' +
              '<label class="text-sm text-white/70">نوع الإعلان</label>' +
              '<div class="grid grid-cols-2 gap-2">' +
                '<button data-action="banner-type" data-type="image" class="p-3 rounded-lg border text-sm font-medium transition-all flex flex-col items-center gap-1.5 ' +
                  (isImage ? 'border-emerald-500 bg-emerald-500/10 text-emerald-400' : 'border-white/10 hover:border-emerald-500/30 text-white/50') + '">' +
                  icon('Image', 20) + ' صورة مرفوعة</button>' +
                '<button data-action="banner-type" data-type="external" class="p-3 rounded-lg border text-sm font-medium transition-all flex flex-col items-center gap-1.5 ' +
                  (!isImage ? 'border-emerald-500 bg-emerald-500/10 text-emerald-400' : 'border-white/10 hover:border-emerald-500/30 text-white/50') + '">' +
                  icon('Code', 20) + ' كود خارجي</button>' +
              '</div>' +
            '</div>' +
            imageSection +
            externalSection +
            // Position
            '<div class="space-y-2">' +
              '<label class="text-sm text-white/70">موضع البانر</label>' +
              '<div class="grid grid-cols-3 gap-2">' + positionBtns + '</div>' +
            '</div>' +
            // Active toggle
            '<div class="flex items-center justify-between p-3 rounded-lg border border-white/10">' +
              '<label class="cursor-pointer text-sm">عرض البانر</label>' +
              '<div data-action="toggle-banner-active" class="toggle-switch ' + (s.bannerActive ? 'active' : '') + '"></div>' +
            '</div>' +
            messageHtml +
            // Save
            '<button data-action="save-banner" class="btn-primary w-full gap-2" ' + (s.bannerSaving || !canSave ? 'disabled' : '') + '>' +
              (s.bannerSaving ? '<span class="animate-spin inline-block">' + icon('Loader2', 16) + '</span> جارٍ الحفظ...' : icon('Check', 16) + ' حفظ البانر') +
            '</button>' +
          '</div>' +
        '</div>' +
      '</div>';
    },

    // ===== HOME VIEW =====
    renderHomeView() {
      return '<main class="flex-1 flex flex-col items-center px-4 py-12">' +
        '<div class="my-6 w-full max-w-4xl mx-auto">' + this.renderBanner('above-upload') + '</div>' +
        '<div class="text-center mb-10 fade-in">' +
          '<h1 class="text-4xl sm:text-5xl lg:text-6xl font-bold mb-4">' +
            '<span class="gradient-text">محرر الصور Fouad AI</span>' +
          '</h1>' +
          '<p class="text-lg sm:text-xl text-white/50 max-w-xl mx-auto">ارفع صورتك واختر التأثير المطلوب — وشاهد الذكاء الاصطناعي يُبدع</p>' +
        '</div>' +
        this.renderUploadArea() +
        this.renderFeatureCards() +
        '<div class="my-6 w-full max-w-4xl mx-auto">' + this.renderBanner('below-features') + '</div>' +
      '</main>';
    },

    // ===== UPLOAD AREA =====
    renderUploadArea() {
      const s = this.state;
      if (s.isUploading) {
        return '<div class="w-full max-w-2xl mx-auto fade-in">' +
          '<div class="rounded-2xl border-2 border-dashed border-emerald-500/30 p-12 sm:p-16 text-center">' +
            '<div class="flex flex-col items-center gap-4">' +
              '<span class="animate-spin inline-block text-emerald-400">' + icon('Loader2', 48) + '</span>' +
              '<p class="text-lg text-white/50">جارٍ رفع الصورة...</p>' +
            '</div>' +
          '</div>' +
        '</div>';
      }

      return '<div class="w-full max-w-2xl mx-auto fade-in">' +
        '<div data-action="upload-click" class="relative cursor-pointer rounded-2xl border-2 border-dashed p-12 sm:p-16 transition-all duration-300 text-center ' +
          (s.isDragOver ? 'upload-area-active border-emerald-500' : 'border-white/20 hover:border-emerald-500/50 hover:bg-emerald-500/5') + '">' +
          '<input id="upload-file-input" type="file" accept="image/*" class="hidden" />' +
          '<div class="flex flex-col items-center gap-4">' +
            '<div class="w-20 h-20 rounded-full bg-emerald-500/10 flex items-center justify-center">' +
              '<span class="text-emerald-400">' + icon('Upload', 40) + '</span>' +
            '</div>' +
            '<div>' +
              '<p class="text-xl font-semibold mb-2">اسحب الصورة هنا أو انقر للاختيار</p>' +
              '<p class="text-white/40 text-sm">يدعم: PNG, JPG, WEBP — حتى 10 ميجا</p>' +
            '</div>' +
          '</div>' +
        '</div>' +
      '</div>';
    },

    // ===== FEATURE CARDS =====
    renderFeatureCards() {
      const features = [
        { iconName: 'Sparkles', title: 'تحرير بالذكاء', desc: 'أدوات تعديل ذكية تفهم صورتك وتحسّنها' },
        { iconName: 'Palette', title: 'أنماط فنية', desc: 'حوّل صورك إلى لوحات زيتية أو رسوم كرتونية' },
        { iconName: 'SlidersHorizontal', title: 'مقارنة فورية', desc: 'قارن بين الأصل والنسخة المحرّرة بسهولة' },
        { iconName: 'Download', title: 'تحميل مباشر', desc: 'حمّل الصور المحرّرة بجودة عالية' },
      ];

      const cards = features.map((f, i) => {
        return '<div class="glass-card h-full text-center p-4 sm:p-6 fade-in" style="animation-delay:' + (0.2 + i * 0.1) + 's">' +
          '<div class="flex flex-col items-center gap-3">' +
            '<div class="w-12 h-12 rounded-xl bg-emerald-500/15 flex items-center justify-center">' +
              '<span class="text-emerald-400">' + icon(f.iconName, 24) + '</span>' +
            '</div>' +
            '<h3 class="font-semibold text-sm sm:text-base">' + f.title + '</h3>' +
            '<p class="text-xs sm:text-sm text-white/50">' + f.desc + '</p>' +
          '</div>' +
        '</div>';
      }).join('');

      return '<div class="grid grid-cols-2 lg:grid-cols-4 gap-4 max-w-5xl mx-auto mt-16">' + cards + '</div>';
    },

    // ===== EDITOR VIEW =====
    renderEditorView() {
      const s = this.state;
      const hasEdited = !!s.editedImage;

      let topBar = '<div class="flex items-center justify-between mb-6 fade-in">' +
        '<div class="flex items-center gap-2">' +
          '<button data-action="new-image" class="btn-ghost gap-2">' + icon('ChevronLeft', 16) + ' صورة جديدة</button>' +
          (hasEdited ? '<button data-action="reset-original" class="btn-outline gap-1.5 text-xs">' + icon('RotateCcw', 14) + ' العودة للأصل</button>' : '') +
          (s.editCount > 0 ? '<span class="text-xs text-white/50 bg-white/5 px-2 py-1 rounded-full">' + s.editCount + ' تعديل' + (s.editCount > 1 ? 'ات' : '') + '</span>' : '') +
        '</div>' +
        (hasEdited ? '<button data-action="download-edited" class="btn-primary gap-2">' + icon('Download', 16) + ' تحميل الصورة</button>' : '') +
      '</div>';

      // Image preview
      let imageContent = '';
      if (s.isEditing) {
        imageContent = '<div class="absolute inset-0 z-20 flex flex-col items-center justify-center bg-black/50 backdrop-blur-sm">' +
          '<span class="animate-spin inline-block text-emerald-400 mb-4">' + icon('Loader2', 48) + '</span>' +
          '<p class="text-lg font-semibold mb-2">جارٍ التعديل بالذكاء الاصطناعي...</p>' +
          '<div class="progress-bar w-48"><div class="progress-bar-fill" style="width:' + s.editProgress + '%"></div></div>' +
          '<p class="text-sm text-white/50 mt-2">' + s.editProgress + '%</p>' +
        '</div>';
      }

      let imageDisplay = '';
      if (hasEdited) {
        imageDisplay = '<div id="comparison-container" class="comparison-container rounded-xl overflow-hidden bg-black/50 relative w-full">' +
          '<img src="' + this.escHtml(s.editedImage) + '" alt="بعد" class="w-full h-auto block" draggable="false" />' +
          '<div id="comparison-original-clip" class="absolute inset-0 overflow-hidden" style="width:50%">' +
            '<img src="' + this.escHtml(s.originalImage) + '" alt="قبل" class="w-full h-auto block" id="comparison-original-img" draggable="false" />' +
          '</div>' +
          '<div id="comparison-line" class="comparison-slider-line" style="left:50%">' +
            '<div class="comparison-slider-handle">' + icon('GripVertical', 20) + '</div>' +
          '</div>' +
          '<div class="absolute top-3 right-3 bg-black/60 text-white text-xs px-2 py-1 rounded-md">الأصلي</div>' +
          '<div class="absolute top-3 left-3 bg-emerald-500/80 text-white text-xs px-2 py-1 rounded-md">المحرّر</div>' +
        '</div>';
      } else if (s.originalImage) {
        imageDisplay = '<img src="' + this.escHtml(s.originalImage) + '" alt="Original" class="max-w-full max-h-[70vh] object-contain mx-auto" />';
      }

      // Info bar
      let infoBar = '<div class="p-3 border-t border-white/10 flex items-center justify-between text-sm text-white/50">' +
        '<span class="truncate max-w-[60%]">' + (s.originalFileName || 'صورة') + '</span>' +
        '<button data-action="reupload" class="btn-ghost gap-1 text-xs h-8">' + icon('RotateCcw', 12) + ' تغيير الصورة</button>' +
        '<input id="reupload-file-input" type="file" accept="image/*" class="hidden" />' +
      '</div>';

      // Analysis section
      let analysisSection = '<div class="mt-4">' +
        '<button data-action="analyze-image" class="btn-outline w-full gap-2 mb-3" ' + (s.isAnalyzing || !s.originalImage ? 'disabled' : '') + '>' +
          (s.isAnalyzing ? '<span class="animate-spin inline-block">' + icon('Loader2', 16) + '</span>' : icon('Eye', 16)) +
          ' تحليل الصورة بالذكاء الاصطناعي</button>';

      if (s.analysis) {
        analysisSection += '<div class="glass-card p-4 fade-in">' +
          '<h3 class="text-sm font-semibold mb-2 flex items-center gap-2">' + icon('Eye', 16) + ' <span class="text-emerald-400">نتيجة التحليل</span></h3>' +
          '<p class="text-sm text-white/50 leading-relaxed whitespace-pre-wrap">' + this.escHtml(s.analysis) + '</p>' +
        '</div>';
      }
      analysisSection += '</div>';

      // Edit tools
      const toolCards = EDIT_TOOLS.map(tool => {
        const isLoading = s.isEditing && s.selectedTool === tool.id;
        return '<button data-action="use-tool" data-tool-id="' + tool.id + '" class="tool-card relative flex flex-col items-center gap-2 p-3 rounded-xl border border-white/10 text-center transition-all ' +
          (isLoading ? 'ring-2 ring-emerald-500' : 'hover:border-emerald-500/40') + ' ' +
          (s.isEditing ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer') + '" ' + (s.isEditing ? 'disabled' : '') + '>' +
          '<div class="w-10 h-10 rounded-lg bg-gradient-to-br ' + tool.color + ' flex items-center justify-center">' +
            (isLoading ? '<span class="animate-spin inline-block text-emerald-400">' + icon('Loader2', 20) + '</span>' : icon(tool.iconName, 20)) +
          '</div>' +
          '<span class="text-xs font-medium">' + tool.label + '</span>' +
        '</button>';
      }).join('');

      const toolsPanel = '<div class="glass-card p-4">' +
        '<h3 class="font-semibold mb-3 flex items-center gap-2">' + icon('Wand2', 16) + ' <span class="text-emerald-400">أدوات التحرير السريعة</span></h3>' +
        '<div class="tools-scroll">' + toolCards + '</div>' +
      '</div>';

      // Custom prompt
      const customPromptPanel = '<div class="glass-card p-4">' +
        '<h3 class="font-semibold mb-3 flex items-center gap-2">' + icon('Pencil', 16) + ' <span class="text-emerald-400">تعديل مخصص</span></h3>' +
        '<textarea id="custom-prompt-area" class="input-field min-h-[100px] resize-none mb-3" placeholder="صِف التعديل الذي تريده... مثال: غيّر الخلفية إلى شاطئ عند الغروب" ' + (s.isEditing ? 'disabled' : '') + '>' + this.escHtml(s.customPrompt) + '</textarea>' +
        '<button data-action="custom-edit" class="btn-primary w-full gap-2" ' + (s.isEditing || !s.customPrompt.trim() ? 'disabled' : '') + '>' +
          (s.isEditing ? '<span class="animate-spin inline-block">' + icon('Loader2', 16) + '</span>' : icon('Sparkles', 16)) +
          ' تطبيق التعديل</button>' +
      '</div>';

      // Error
      let errorSection = '';
      if (s.editError) {
        let retryBtn = '';
        if (s.lastEditArgs) {
          retryBtn = '<button data-action="retry-edit" class="btn-outline shrink-0 gap-1 text-xs">' + icon('RotateCcw', 12) + ' إعادة المحاولة</button>';
        }
        errorSection = '<div class="border-red-500/50 bg-red-500/10 rounded-xl p-4 flex items-start gap-3 fade-in">' +
          '<span class="text-red-400 mt-0.5 shrink-0">' + icon('X', 20) + '</span>' +
          '<div class="flex-1">' +
            '<p class="text-sm font-medium text-red-400">حدث خطأ</p>' +
            '<p class="text-xs text-white/50 mt-1">' + this.escHtml(s.editError) + '</p>' +
          '</div>' +
          retryBtn +
        '</div>';
      }

      return '<main class="flex-1 px-4 py-6 max-w-7xl mx-auto w-full">' +
        topBar +
        '<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">' +
          '<div class="lg:col-span-2">' +
            '<div class="glass-card overflow-hidden">' +
              '<div class="relative min-h-[300px] sm:min-h-[400px] flex items-center justify-center bg-black/30">' +
                imageContent +
                imageDisplay +
              '</div>' +
              infoBar +
            '</div>' +
            analysisSection +
          '</div>' +
          '<div class="lg:col-span-1 space-y-4">' +
            toolsPanel +
            customPromptPanel +
            errorSection +
          '</div>' +
        '</div>' +
      '</main>';
    },

    // ===== GALLERY VIEW =====
    renderGalleryView() {
      const s = this.state;

      if (s.isGalleryLoading) {
        return '<main class="flex-1 flex items-center justify-center">' +
          '<span class="animate-spin inline-block text-emerald-400">' + icon('Loader2', 32) + '</span>' +
        '</main>';
      }

      let content = '';
      if (s.projects.length === 0) {
        content = '<div class="text-center py-20 fade-in">' +
          '<div class="w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mx-auto mb-4">' +
            '<span class="text-white/30">' + icon('Image', 40) + '</span>' +
          '</div>' +
          '<p class="text-lg text-white/50 mb-4">لا توجد مشاريع بعد</p>' +
          '<button data-action="nav" data-view="home" class="btn-primary gap-2">' + icon('Upload', 16) + ' ابدأ بتعديل صورة</button>' +
        '</div>';
      } else {
        const cards = s.projects.map((project, i) => {
          const lastEdit = project.edits && project.edits.length > 0 ? project.edits[project.edits.length - 1] : null;
          const thumbnail = lastEdit ? (lastEdit.editedPath || lastEdit.originalPath || '') : '';
          const dateStr = new Date(project.createdAt).toLocaleDateString('ar-EG');
          const editCountStr = (project.edits && project.edits.length) ? (' — ' + project.edits.length + ' تعديل') : '';

          let thumbContent = '';
          if (thumbnail) {
            thumbContent = '<img src="' + this.escHtml(thumbnail) + '" alt="' + this.escHtml(project.title) + '" class="w-full h-full object-cover" />';
          } else {
            thumbContent = '<div class="w-full h-full flex items-center justify-center"><span class="text-white/30">' + icon('Image', 32) + '</span></div>';
          }

          return '<div class="glass-card overflow-hidden group cursor-pointer hover:border-emerald-500/40 transition-all fade-in" style="animation-delay:' + (i * 0.05) + 's" data-action="open-project" data-project-index="' + i + '">' +
            '<div class="aspect-video bg-black/30 relative overflow-hidden">' +
              thumbContent +
              '<div class="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center">' +
                '<span class="opacity-0 group-hover:opacity-100 transition-opacity bg-white/20 backdrop-blur-sm px-3 py-1.5 rounded-lg text-sm font-medium">فتح المشروع</span>' +
              '</div>' +
            '</div>' +
            '<div class="p-3 flex items-center justify-between">' +
              '<div>' +
                '<p class="font-medium text-sm truncate">' + this.escHtml(project.title) + '</p>' +
                '<p class="text-xs text-white/50">' + dateStr + editCountStr + '</p>' +
              '</div>' +
              '<button data-action="delete-project" data-project-index="' + i + '" class="btn-ghost h-8 w-8 text-white/50 hover:text-red-400 shrink-0 p-0">' + icon('Trash2', 16) + '</button>' +
            '</div>' +
          '</div>';
        }).join('');

        content = '<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">' + cards + '</div>';
      }

      return '<main class="flex-1 px-4 py-8 max-w-6xl mx-auto w-full">' +
        '<div class="text-center mb-8 fade-in">' +
          '<h2 class="text-3xl font-bold mb-2"><span class="gradient-text">المعرض</span></h2>' +
          '<p class="text-white/50">جميع مشاريع تعديل الصور السابقة</p>' +
        '</div>' +
        content +
      '</main>';
    },

    // ===== GENERATE VIEW =====
    renderGenerateView() {
      const s = this.state;
      const hasImage = !!s.genImage;

      const sizeBtns = SIZE_OPTIONS.map(opt => {
        const active = s.genSelectedSize === opt.id;
        return '<button data-action="gen-size" data-size-id="' + opt.id + '" class="flex flex-col items-center gap-1.5 p-2.5 rounded-xl border text-center transition-all ' +
          (active ? 'border-emerald-500 bg-emerald-500/10 ring-1 ring-emerald-500/30' : 'border-white/10 hover:border-emerald-500/30') + ' ' +
          (s.genIsGenerating ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer') + '" ' + (s.genIsGenerating ? 'disabled' : '') + '>' +
          icon(opt.iconName, 16) +
          '<span class="text-xs font-medium">' + opt.label + '</span>' +
          '<span class="text-[10px] text-white/50">' + opt.desc + '</span>' +
        '</button>';
      }).join('');

      // Result section
      let resultContent = '';
      if (s.genIsGenerating) {
        resultContent = '<div class="absolute inset-0 z-10 flex flex-col items-center justify-center bg-black/50 backdrop-blur-sm gap-4 px-8">' +
          '<span class="animate-spin inline-block text-emerald-400">' + icon('Loader2', 64) + '</span>' +
          '<p class="text-sm font-medium animate-pulse">' + this.escHtml(s.genProgressMsg || 'جارٍ رسم الصورة بالذكاء الاصطناعي...') + '</p>' +
          '<div class="progress-bar w-64"><div class="progress-bar-fill" style="width:' + s.genProgress + '%"></div></div>' +
          '<p class="text-xs text-white/50">' + s.genProgress + '%</p>' +
        '</div>';
      }

      let imageArea = '';
      if (hasImage) {
        imageArea = '<img src="' + this.escHtml(s.genImage) + '" alt="Generated" class="w-full h-auto block" />';
      } else if (!s.genIsGenerating) {
        imageArea = '<div class="flex flex-col items-center gap-4 py-16">' +
          '<div class="w-20 h-20 rounded-full bg-white/5 flex items-center justify-center">' +
            '<span class="text-white/20">' + icon('WandSparkles', 40) + '</span>' +
          '</div>' +
          '<p class="text-white/50 text-center px-4">الصورة المرسومة ستظهر هنا</p>' +
        '</div>';
      }

      let actionBtns = '';
      if (hasImage) {
        actionBtns = '<div class="p-3 border-t border-white/10 flex items-center gap-2">' +
          '<button data-action="send-to-editor" class="btn-primary flex-1 gap-2">' + icon('ArrowRight', 16) + ' تعديل الصورة</button>' +
          '<button data-action="download-generated" class="btn-outline gap-2">' + icon('Download', 16) + ' تحميل</button>' +
        '</div>';
      }

      // Suggestion prompts
      let suggestions = '';
      if (!hasImage && !s.genIsGenerating) {
        const sugBtns = EXAMPLE_PROMPTS.map(ex => {
          return '<button data-action="gen-example" data-prompt="' + this.escHtml(ex) + '" class="text-xs px-3 py-1.5 rounded-full border border-white/10 hover:border-emerald-500/40 hover:bg-emerald-500/5 transition-all cursor-pointer">' + ex + '</button>';
        }).join('');

        suggestions = '<div class="glass-card mt-4 p-4">' +
          '<h4 class="text-sm font-medium mb-3 flex items-center gap-2">' + icon('Sparkles', 16) + ' <span class="text-emerald-400">أفكار للتجربة</span></h4>' +
          '<div class="flex flex-wrap gap-2">' + sugBtns + '</div>' +
        '</div>';
      }

      // Error
      let errorHtml = '';
      if (s.genError) {
        errorHtml = '<div class="border-red-500/50 bg-red-500/10 rounded-xl p-4 flex items-start gap-3 fade-in">' +
          '<span class="text-red-400 mt-0.5 shrink-0">' + icon('X', 20) + '</span>' +
          '<div class="flex-1">' +
            '<p class="text-sm font-medium text-red-400">خطأ</p>' +
            '<p class="text-xs text-white/50 mt-1">' + this.escHtml(s.genError) + '</p>' +
          '</div>' +
          '<button data-action="retry-generate" class="btn-outline shrink-0 gap-1 text-xs">' + icon('RotateCcw', 12) + ' إعادة المحاولة</button>' +
        '</div>';
      }

      return '<main class="flex-1 px-4 py-6 max-w-5xl mx-auto w-full">' +
        '<div class="text-center mb-8 fade-in">' +
          '<h2 class="text-3xl font-bold mb-2"><span class="gradient-text">رسم الصور بالذكاء</span></h2>' +
          '<p class="text-white/50">صِف الصورة التي تريدها وسنرسمها لك</p>' +
        '</div>' +
        '<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">' +
          '<div class="space-y-4">' +
            '<div class="glass-card p-4">' +
              '<h3 class="font-semibold mb-3 flex items-center gap-2">' + icon('Pencil', 16) + ' <span class="text-emerald-400">وصف الصورة</span></h3>' +
              '<textarea id="gen-prompt-area" class="input-field min-h-[120px] resize-none mb-3" placeholder="مثال: قطة جميلة تجلس في حديقة مليئة بالزهور عند الغروب..." ' + (s.genIsGenerating ? 'disabled' : '') + '>' + this.escHtml(s.genPrompt) + '</textarea>' +
              '<p class="text-xs text-white/40 mb-3">يمكنك الكتابة بالعربية أو الإنجليزية</p>' +
              '<h4 class="text-sm font-medium mb-2">حجم الصورة</h4>' +
              '<div class="grid grid-cols-4 gap-2">' + sizeBtns + '</div>' +
              '<button data-action="generate-image" class="btn-primary w-full gap-2 mt-4 text-base py-3" ' + (s.genIsGenerating || !s.genPrompt.trim() ? 'disabled' : '') + '>' +
                (s.genIsGenerating ? '<span class="animate-spin inline-block">' + icon('Loader2', 20) + '</span> جارٍ الرسم...' : icon('WandSparkles', 20) + ' ارسم الصورة') +
              '</button>' +
            '</div>' +
            errorHtml +
          '</div>' +
          '<div>' +
            '<div class="glass-card overflow-hidden">' +
              '<div class="relative min-h-[400px] flex items-center justify-center bg-black/30">' +
                resultContent +
                imageArea +
              '</div>' +
              actionBtns +
            '</div>' +
            suggestions +
          '</div>' +
        '</div>' +
      '</main>';
    },

    // ===== FOOTER =====
    renderFooter() {
      return '<footer class="glass mt-auto">' +
        '<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex flex-col sm:flex-row items-center justify-between gap-2 text-sm text-white/50">' +
          '<p>محرر الصور Fouad AI — قوّة الذكاء الاصطناعي بين يديك</p>' +
          '<p>© ' + new Date().getFullYear() + ' جميع الحقوق محفوظة</p>' +
        '</div>' +
      '</footer>';
    },

    // ===== TOAST =====
    renderToast() {
      const t = this.state.toast;
      if (!t) return '';
      const bgColor = t.type === 'success' ? 'bg-emerald-500/90' : 'bg-red-500/90';
      return '<div class="fixed bottom-4 left-4 z-[200] ' + bgColor + ' text-white px-4 py-3 rounded-xl shadow-lg backdrop-blur-sm text-sm font-medium fade-in max-w-xs">' +
        this.escHtml(t.message) +
      '</div>';
    },

    // ===== COMPARISON SLIDER =====
    initComparisonSlider() {
      const container = document.getElementById('comparison-container');
      if (!container) return;
      this._compDragging = false;
      this._compContainer = container;

      const updateWidth = () => {
        const img = document.getElementById('comparison-original-img');
        if (img && container) {
          img.style.width = container.offsetWidth + 'px';
        }
      };
      updateWidth();

      const ro = new ResizeObserver(updateWidth);
      ro.observe(container);
      this._compRO = ro;
    },

    _updateComparisonPosition(clientX) {
      const container = this._compContainer;
      if (!container) return;
      const rect = container.getBoundingClientRect();
      const x = clientX - rect.left;
      const pct = Math.min(100, Math.max(0, (x / rect.width) * 100));
      const clip = document.getElementById('comparison-original-clip');
      const line = document.getElementById('comparison-line');
      if (clip) clip.style.width = pct + '%';
      if (line) line.style.left = pct + '%';
    },

    // ===== EVENT HANDLERS =====
    handleClick(e) {
      const btn = e.target.closest('[data-action]');
      if (!btn) return;
      const action = btn.dataset.action;

      switch (action) {
        case 'nav':
          this.setState({ view: btn.dataset.view });
          if (btn.dataset.view === 'gallery') this.loadGallery();
          this.render();
          break;

        case 'open-login':
          this.setState({ showLoginDialog: true, loginError: null });
          this.render();
          break;

        case 'close-login':
        case 'close-login-backdrop':
          if (action === 'close-login-backdrop' && e.target !== btn) return;
          this.setState({ showLoginDialog: false, loginError: null, loginUsername: '', loginPassword: '' });
          this.render();
          break;

        case 'close-banner':
        case 'close-banner-backdrop':
          if (action === 'close-banner-backdrop' && e.target !== btn) return;
          this.setState({ showBannerDialog: false });
          this.render();
          break;

        case 'open-banner-admin':
          if (this.state.isAdmin) {
            this.loadBannerAdmin();
            this.setState({ showBannerDialog: true });
          } else {
            this.setState({ showLoginDialog: true, loginError: null });
          }
          this.render();
          break;

        case 'dismiss-banner':
          e.stopPropagation();
          const pos = btn.dataset.position;
          const dismissed = Object.assign({}, this.state.bannerDismissed);
          dismissed[pos] = true;
          this.setState({ bannerDismissed: dismissed });
          this.render();
          break;

        case 'upload-click':
          document.getElementById('upload-file-input').click();
          break;

        case 'new-image':
          this.setState({ originalImage: null, originalFileName: null, editedImage: null, isEditing: false, editProgress: 0, editError: null, analysis: null, customPrompt: '', selectedTool: null, editCount: 0, lastEditArgs: null });
          this.render();
          break;

        case 'reset-original':
          this.setState({ editedImage: null, editCount: 0, editError: null });
          this.render();
          break;

        case 'download-edited':
          this.downloadImage(this.state.editedImage, this.state.originalFileName);
          break;

        case 'download-generated':
          this.downloadImage(this.state.genImage, 'Fouad-AI-generated.png');
          break;

        case 'reupload':
          document.getElementById('reupload-file-input').click();
          break;

        case 'analyze-image':
          this.analyzeImage();
          break;

        case 'use-tool':
          if (this.state.isEditing) return;
          const toolId = btn.dataset.toolId;
          const tool = EDIT_TOOLS.find(t => t.id === toolId);
          if (tool) {
            this.setState({ selectedTool: toolId });
            this.startEdit(tool.prompt, tool.label, 'quick-tool');
          }
          break;

        case 'custom-edit':
          if (this.state.isEditing || !this.state.customPrompt.trim()) return;
          this.startEdit(this.state.customPrompt.trim(), 'تعديل مخصص', 'custom');
          break;

        case 'retry-edit':
          if (this.state.lastEditArgs) {
            this.setState({ editError: null });
            this.startEdit(this.state.lastEditArgs.prompt, this.state.lastEditArgs.label, this.state.lastEditArgs.toolType);
          }
          break;

        case 'send-to-editor':
          if (!this.state.genImage) return;
          this.setState({
            originalImage: this.state.genImage,
            originalFileName: 'Fouad-AI-generated.png',
            editedImage: null,
            analysis: null,
            view: 'editor',
            editCount: 0,
            editError: null,
            customPrompt: '',
            selectedTool: null,
            lastEditArgs: null,
          });
          this.render();
          break;

        case 'generate-image':
          this.handleGenerate();
          break;

        case 'gen-size':
          this.setState({ genSelectedSize: btn.dataset.sizeId });
          this.render();
          break;

        case 'gen-example':
          this.setState({ genPrompt: btn.dataset.prompt });
          this.render();
          const ta = document.getElementById('gen-prompt-area');
          if (ta) ta.focus();
          break;

        case 'retry-generate':
          this.handleGenerate();
          break;

        case 'banner-type':
          this.setState({ bannerAdType: btn.dataset.type });
          this.render();
          break;

        case 'banner-position':
          this.setState({ bannerPosition: btn.dataset.value });
          this.render();
          break;

        case 'toggle-banner-active':
          this.setState({ bannerActive: !this.state.bannerActive });
          this.render();
          break;

        case 'banner-upload-click':
          if (!this.state.bannerUploading) {
            document.getElementById('banner-file-input').click();
          }
          break;

        case 'save-banner':
          this.saveBanner();
          break;

        case 'open-project':
          const idx = parseInt(btn.dataset.projectIndex);
          this.openProject(idx);
          break;

        case 'delete-project':
          e.stopPropagation();
          const delIdx = parseInt(btn.dataset.projectIndex);
          this.deleteProject(delIdx);
          break;

        case 'logout':
          this.handleLogout();
          break;
      }
    },

    handleInput(e) {
      const el = e.target;
      if (el.id === 'custom-prompt-area') {
        this.state.customPrompt = el.value;
      } else if (el.id === 'gen-prompt-area') {
        this.state.genPrompt = el.value;
      } else if (el.id === 'login-username') {
        this.state.loginUsername = el.value;
      } else if (el.id === 'login-password') {
        this.state.loginPassword = el.value;
      } else if (el.id === 'banner-link-url') {
        this.state.bannerLinkUrl = el.value;
      } else if (el.id === 'banner-text-overlay') {
        this.state.bannerText = el.value;
      } else if (el.id === 'banner-ad-code') {
        this.state.bannerAdCode = el.value;
      }
    },

    async handleSubmit(e) {
      if (e.target.id === 'login-form') {
        e.preventDefault();
        await this.handleLogin();
      }
    },

    handleDragOver(e) {
      const uploadArea = e.target.closest('[data-action="upload-click"]');
      if (uploadArea) {
        e.preventDefault();
        if (!this.state.isDragOver) {
          this.setState({ isDragOver: true });
          this.render();
        }
      }
    },

    handleDragLeave(e) {
      const uploadArea = e.target.closest('[data-action="upload-click"]');
      if (uploadArea) {
        const rect = uploadArea.getBoundingClientRect();
        const x = e.clientX;
        const y = e.clientY;
        if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
          this.setState({ isDragOver: false });
          this.render();
        }
      }
    },

    handleDrop(e) {
      const uploadArea = e.target.closest('[data-action="upload-click"]');
      if (uploadArea) {
        e.preventDefault();
        this.setState({ isDragOver: false });
        const file = e.dataTransfer.files[0];
        if (file && file.type.startsWith('image/')) {
          this.uploadFile(file);
        }
      }
    },

    async handleChange(e) {
      const el = e.target;
      if (el.id === 'upload-file-input') {
        const file = el.files[0];
        if (file && file.type.startsWith('image/')) {
          await this.uploadFile(file);
        }
        el.value = '';
      } else if (el.id === 'reupload-file-input') {
        const file = el.files[0];
        if (file && file.type.startsWith('image/')) {
          await this.uploadFile(file, true);
        }
        el.value = '';
      } else if (el.id === 'banner-file-input') {
        const file = el.files[0];
        if (file && file.type.startsWith('image/')) {
          await this.uploadBannerImage(file);
        }
        el.value = '';
      }
    },

    handlePointerDown(e) {
      const container = e.target.closest('#comparison-container') || e.target.closest('.comparison-slider-handle');
      if (container) {
        this._compDragging = true;
        this._updateComparisonPosition(e.clientX);
        e.preventDefault();
      }
    },

    handlePointerMove(e) {
      if (this._compDragging) {
        this._updateComparisonPosition(e.clientX);
        e.preventDefault();
      }
    },

    handlePointerUp(e) {
      if (this._compDragging) {
        this._compDragging = false;
      }
    },

    // ===== ACTIONS =====
    async uploadFile(file, isReupload) {
      this.setState({ isUploading: true, editError: null });
      if (!isReupload) {
        this.setState({ editedImage: null, analysis: null });
      }
      this.render();

      try {
        const formData = new FormData();
        formData.append('image', file);
        const res = await fetch('/api/upload', { method: 'POST', body: formData });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'فشل رفع الصورة');

        this.setState({
          originalImage: data.imageUrl,
          originalFileName: file.name,
          isUploading: false,
          view: 'editor',
          editCount: 0,
          editError: null,
          analysis: null,
          customPrompt: '',
          selectedTool: null,
          lastEditArgs: null,
        });
        if (isReupload) {
          this.setState({ editedImage: null, analysis: null });
        }
        this.render();
      } catch (err) {
        this.setState({
          isUploading: false,
          editError: err.message || 'حدث خطأ',
        });
        this.render();
      }
    },

    async startEdit(prompt, label, toolType) {
      const baseImage = this.state.editedImage || this.state.originalImage;
      if (!baseImage) return;

      this.setState({
        lastEditArgs: { prompt, label, toolType },
        isEditing: true,
        editError: null,
        editedImage: null,
        editProgress: 0,
      });
      this.render();

      try {
        const res = await fetch('/api/edit', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ imageUrl: baseImage, prompt, label, toolType }),
        });

        if (!res.ok) {
          const data = await res.json();
          throw new Error(data.error || 'فشل التعديل');
        }

        const reader = res.body ? res.body.getReader() : null;
        if (!reader) throw new Error('لا يمكن قراءة الاستجابة');

        const decoder = new TextDecoder();
        let buffer = '';

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          buffer = lines.pop() || '';

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6);
              let parsed;
              try { parsed = JSON.parse(data); } catch { continue; }

              if (parsed.type === 'progress') {
                this.setState({ editProgress: parsed.value });
                this.render();
              } else if (parsed.type === 'done') {
                this.setState({
                  editedImage: parsed.editedImageUrl,
                  editProgress: 100,
                  editCount: this.state.editCount + 1,
                });
                this.render();
                // Refresh gallery
                try {
                  const projectsRes = await fetch('/api/projects');
                  if (projectsRes.ok) {
                    const projectsData = await projectsRes.json();
                    this.setState({ projects: projectsData });
                  }
                } catch {}
              } else if (parsed.type === 'error') {
                throw new Error(parsed.message);
              }
            }
          }
        }
      } catch (err) {
        this.setState({ editError: err.message || 'حدث خطأ أثناء التعديل' });
        this.render();
      } finally {
        this.setState({ isEditing: false, selectedTool: null });
        this.render();
      }
    },

    async analyzeImage() {
      if (!this.state.originalImage) return;
      this.setState({ isAnalyzing: true, editError: null });
      this.render();

      try {
        const res = await fetch('/api/analyze', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ imageUrl: this.state.originalImage }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'فشل التحليل');
        this.setState({ analysis: data.analysis });
        this.render();
      } catch (err) {
        this.setState({ editError: err.message || 'حدث خطأ' });
        this.render();
      } finally {
        this.setState({ isAnalyzing: false });
        this.render();
      }
    },

    async handleGenerate() {
      if (!this.state.genPrompt.trim() || this.state.genIsGenerating) return;

      this.setState({
        genIsGenerating: true,
        genError: null,
        genImage: null,
        genProgress: 0,
        genProgressMsg: 'جارٍ البدء...',
      });
      this.render();

      try {
        const startRes = await fetch('/api/generate', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ prompt: this.state.genPrompt.trim(), sizeId: this.state.genSelectedSize }),
        });
        const startData = await startRes.json();

        if (!startRes.ok || startData.error) {
          throw new Error(startData.error || 'حدث خطأ غير متوقع');
        }

        const { jobId } = startData;
        if (!jobId) throw new Error('لم يتم إنشاء العملية');

        const result = await new Promise((resolve, reject) => {
          let attempts = 0;
          const maxAttempts = 120;

          const pollInterval = setInterval(async () => {
            attempts++;
            if (attempts > maxAttempts) {
              clearInterval(pollInterval);
              reject(new Error('انتهت المهلة. حاول مرة أخرى.'));
              return;
            }

            try {
              const pollRes = await fetch('/api/generate?jobId=' + jobId);
              const pollData = await pollRes.json();

              if (pollData.error && !pollData.status) {
                clearInterval(pollInterval);
                reject(new Error(pollData.error));
                return;
              }

              if (pollData.progress !== undefined) {
                this.setState({ genProgress: Math.max(this.state.genProgress, pollData.progress) });
              }
              if (pollData.message) {
                this.setState({ genProgressMsg: pollData.message });
              }

              if (pollData.status === 'done' && pollData.imageUrl) {
                clearInterval(pollInterval);
                resolve({ imageUrl: pollData.imageUrl });
              } else if (pollData.status === 'error') {
                clearInterval(pollInterval);
                reject(new Error(pollData.error || 'فشل توليد الصورة'));
              }
            } catch (pollErr) {
              console.error('[GEN] Poll error, retrying...', pollErr);
            }
          }, 3000);

          this.state.genPollInterval = pollInterval;
        });

        this.setState({ genImage: result.imageUrl });
        this.render();
      } catch (err) {
        this.setState({ genError: err.message || 'حدث خطأ' });
        this.render();
      } finally {
        if (this.state.genPollInterval) {
          clearInterval(this.state.genPollInterval);
          this.state.genPollInterval = null;
        }
        this.setState({ genIsGenerating: false });
        this.render();
      }
    },

    async handleLogin() {
      const s = this.state;
      if (!s.loginUsername.trim() || !s.loginPassword.trim() || s.loginLoading) return;

      this.setState({ loginLoading: true, loginError: null });
      this.render();

      try {
        const res = await fetch('/api/auth', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username: s.loginUsername, password: s.loginPassword }),
        });
        const data = await res.json();

        if (!res.ok) {
          this.setState({ loginError: data.error || 'اسم المستخدم أو كلمة المرور غير صحيحة', loginLoading: false });
          this.render();
          return;
        }

        this.setState({
          isAdmin: true,
          loginLoading: false,
          loginUsername: '',
          loginPassword: '',
          showLoginDialog: false,
        });
        this.showToast('تم تسجيل الدخول بنجاح', 'success');
        this.loadBannerAdmin();
        this.setState({ showBannerDialog: true });
        this.render();
      } catch {
        this.setState({ loginError: 'حدث خطأ أثناء تسجيل الدخول', loginLoading: false });
        this.render();
      }
    },

    async handleLogout() {
      try {
        await fetch('/api/auth', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ action: 'logout' }),
        });
      } catch {}
      this.setState({ isAdmin: false });
      this.showToast('تم تسجيل الخروج', 'success');
      this.render();
    },

    async loadBannerAdmin() {
      try {
        const res = await fetch('/api/banner');
        if (!res.ok) return;
        const data = await res.json();
        if (data.banner) {
          this.setState({
            bannerAdType: data.banner.adType || 'image',
            bannerImageUrl: data.banner.imageUrl || '',
            bannerAdCode: data.banner.adCode || '',
            bannerLinkUrl: data.banner.linkUrl || '',
            bannerText: data.banner.text || '',
            bannerActive: data.banner.active,
            bannerPosition: data.banner.position || 'top',
            bannerMessage: null,
          });
        } else {
          this.setState({
            bannerAdType: 'image',
            bannerImageUrl: '',
            bannerAdCode: '',
            bannerLinkUrl: '',
            bannerText: '',
            bannerActive: false,
            bannerPosition: 'top',
            bannerMessage: null,
          });
        }
      } catch {}
    },

    async uploadBannerImage(file) {
      this.setState({ bannerUploading: true, bannerMessage: null });
      this.render();

      try {
        const formData = new FormData();
        formData.append('image', file);
        const res = await fetch('/api/banner', { method: 'POST', body: formData });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'فشل رفع الصورة');
        this.setState({ bannerImageUrl: data.imageUrl });
        this.render();
      } catch (err) {
        this.setState({ bannerMessage: { type: 'error', text: err.message || 'خطأ' } });
        this.render();
      } finally {
        this.setState({ bannerUploading: false });
        this.render();
      }
    },

    async saveBanner() {
      const s = this.state;
      if (s.bannerAdType === 'image' && !s.bannerImageUrl) {
        this.setState({ bannerMessage: { type: 'error', text: 'يرجى رفع صورة البانر أولاً' } });
        this.render();
        return;
      }
      if (s.bannerAdType === 'external' && !s.bannerAdCode.trim()) {
        this.setState({ bannerMessage: { type: 'error', text: 'يرجى لصق كود الإعلان الخارجي' } });
        this.render();
        return;
      }

      this.setState({ bannerSaving: true, bannerMessage: null });
      this.render();

      try {
        const res = await fetch('/api/banner', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            adType: s.bannerAdType,
            imageUrl: s.bannerImageUrl,
            adCode: s.bannerAdCode,
            linkUrl: s.bannerLinkUrl,
            text: s.bannerText,
            active: s.bannerActive,
            position: s.bannerPosition,
          }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'فشل الحفظ');

        this.setState({ bannerMessage: { type: 'success', text: 'تم حفظ البانر بنجاح' } });
        // Refresh banner displays
        this.fetchBanner(s.bannerPosition);
        this.render();
      } catch (err) {
        this.setState({ bannerMessage: { type: 'error', text: err.message || 'خطأ' } });
        this.render();
      } finally {
        this.setState({ bannerSaving: false });
        this.render();
      }
    },

    async loadGallery() {
      this.setState({ isGalleryLoading: true });
      this.render();

      try {
        const res = await fetch('/api/projects');
        if (res.ok) {
          const data = await res.json();
          this.setState({ projects: data });
        }
      } catch {}
      this.setState({ isGalleryLoading: false });
      this.render();
    },

    async deleteProject(index) {
      const project = this.state.projects[index];
      if (!project) return;

      try {
        const res = await fetch('/api/project?id=' + project.id, { method: 'DELETE' });
        if (res.ok) {
          const projects = this.state.projects.filter(p => p.id !== project.id);
          this.setState({ projects });
          this.render();
          this.showToast('تم حذف المشروع', 'success');
        }
      } catch {}
    },

    openProject(index) {
      const project = this.state.projects[index];
      if (!project) return;

      const lastEdit = project.edits && project.edits.length > 0 ? project.edits[project.edits.length - 1] : null;

      let editedImage = null;
      let originalImage = null;

      if (lastEdit) {
        originalImage = lastEdit.originalPath;
        editedImage = lastEdit.editedPath || null;
      }

      if (!originalImage) return;

      this.setState({
        originalImage,
        editedImage,
        originalFileName: project.title,
        analysis: null,
        view: 'editor',
        editCount: project.edits ? project.edits.length : 0,
        editError: null,
        customPrompt: '',
        selectedTool: null,
        lastEditArgs: null,
      });
      this.render();
    },

    downloadImage(url, fileName) {
      if (!url) return;
      const a = document.createElement('a');
      a.href = url;
      let ext = 'png';
      let baseName = 'image';
      if (fileName) {
        const parts = fileName.split('.');
        if (parts.length > 1) ext = parts.pop();
        baseName = parts.join('.');
      }
      a.download = 'Fouad-AI-' + baseName + '.' + ext;
      a.click();
    },

    escHtml(str) {
      if (!str) return '';
      const div = document.createElement('div');
      div.textContent = str;
      return div.innerHTML;
    },
  };

  // ===== INIT =====
  document.addEventListener('DOMContentLoaded', () => {
    App.init();
  });
  </script>
</body>
</html>