'use client';

import { useState, useCallback, useRef, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Upload, Image as ImageIcon, Sparkles, Download, ArrowRight,
  Palette, Camera, Layers, SlidersHorizontal, Loader2, Check,
  Trash2, RotateCcw, Eye, Wand2, Sun, Paintbrush, Film,
  Pencil, History, ChevronLeft, X, GripVertical, WandSparkles,
  Square, RectangleVertical, Monitor, Settings, Megaphone, Code,
  LogIn, LogOut, Shield
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Progress } from '@/components/ui/progress';
import { Card, CardContent } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { useAppStore, type PhotoProject } from '@/store/photo-store';
import { signIn, signOut } from 'next-auth/react';

/* ─── Session Types ─── */
interface SessionUser {
  id: string;
  name?: string | null;
  email?: string | null;
  image?: string | null;
  role?: string;
}

/* ─── useAdminSession Hook ─── */
function useAdminSession() {
  const [isAdmin, setIsAdmin] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [userName, setUserName] = useState<string | null>(null);

  const checkSession = useCallback(async () => {
    try {
      const res = await fetch('/api/auth/session');
      if (!res.ok) { setIsAdmin(false); setIsLoading(false); return; }
      const session = await res.json();
      const role = (session?.user as SessionUser | undefined)?.role;
      setIsAdmin(role === 'admin');
      setUserName(session?.user?.name || null);
    } catch {
      setIsAdmin(false);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => { checkSession(); }, [checkSession]);

  return { isAdmin, isLoading, userName, refresh: checkSession };
}

/* ─── Types ─── */
interface BannerData {
  id: string;
  adType: string;
  imageUrl: string;
  adCode: string;
  linkUrl: string;
  text: string;
  active: boolean;
  position: string;
}

/* ─── Banner Display Component ─── */
function BannerDisplay({ position }: { position: 'top' | 'above-upload' | 'below-features' }) {
  const [banner, setBanner] = useState<BannerData | null>(null);
  const [dismissed, setDismissed] = useState(false);

  useEffect(() => {
    fetch('/api/banner')
      .then((r) => r.json())
      .then((data) => {
        if (data.banner && data.banner.position === position) {
          setBanner(data.banner);
        }
      })
      .catch(() => {});
  }, [position]);

  if (!banner || !banner.active || dismissed) return null;

  // External ad code (Google AdSense, etc.)
  if (banner.adType === 'external' && banner.adCode) {
    return (
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative w-full max-w-4xl mx-auto"
      >
        <div className="rounded-xl overflow-hidden bg-card/50 border border-border/30 p-1">
          <div
            className="w-full min-h-[60px] flex items-center justify-center"
            dangerouslySetInnerHTML={{ __html: banner.adCode }}
          />
        </div>
        <button
          onClick={() => setDismissed(true)}
          className="absolute -top-2 -left-2 w-6 h-6 rounded-full bg-muted text-muted-foreground flex items-center justify-center hover:bg-muted-foreground hover:text-background transition-colors border border-border/50"
          aria-label="إغلاق الإعلان"
        >
          <X className="w-3 h-3" />
        </button>
      </motion.div>
    );
  }

  // Image banner
  if (!banner.imageUrl) return null;

  const Wrapper = banner.linkUrl ? 'a' : 'div';
  const wrapperProps = banner.linkUrl
    ? { href: banner.linkUrl, target: '_blank' as const, rel: 'noopener noreferrer' }
    : {};

  return (
    <motion.div
      initial={{ opacity: 0, y: -10 }}
      animate={{ opacity: 1, y: 0 }}
      className="relative w-full max-w-4xl mx-auto"
    >
      <Wrapper
        {...wrapperProps}
        className="block relative rounded-xl overflow-hidden"
      >
        <img
          src={banner.imageUrl}
          alt={banner.text || 'إعلان'}
          className="w-full h-auto object-cover max-h-48 rounded-xl"
        />
        {banner.text && (
          <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent flex items-end p-4">
            <p className="text-white text-sm sm:text-base font-medium">{banner.text}</p>
          </div>
        )}
      </Wrapper>
      <button
        onClick={() => setDismissed(true)}
        className="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"
        aria-label="إغلاق الإعلان"
      >
        <X className="w-3 h-3" />
      </button>
    </motion.div>
  );
}

/* ─── Login Dialog ─── */
function LoginDialog({ open, onOpenChange, onLoginSuccess }: { open: boolean; onOpenChange: (v: boolean) => void; onLoginSuccess: () => void }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = useCallback(async (e: React.FormEvent) => {
    e.preventDefault();
    if (!username.trim() || !password.trim()) return;
    setLoading(true);
    setError(null);
    try {
      const res = await signIn('credentials', {
        username,
        password,
        redirect: false,
      });
      if (res?.error) {
        setError('اسم المستخدم أو كلمة المرور غير صحيحة');
      } else {
        setUsername('');
        setPassword('');
        onOpenChange(false);
        onLoginSuccess();
      }
    } catch {
      setError('حدث خطأ أثناء تسجيل الدخول');
    } finally {
      setLoading(false);
    }
  }, [username, password, onOpenChange, onLoginSuccess]);

  return (
    <Dialog open={open} onOpenChange={(v) => { if (!v) setError(null); onOpenChange(v); }}>
      <DialogContent className="max-w-sm" dir="rtl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Shield className="w-5 h-5 text-primary" />
            تسجيل دخول المدير
          </DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 mt-2">
          <div className="space-y-2">
            <Label htmlFor="admin-user">اسم المستخدم</Label>
            <Input
              id="admin-user"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="admin"
              autoComplete="username"
              autoFocus
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="admin-pass">كلمة المرور</Label>
            <Input
              id="admin-pass"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              autoComplete="current-password"
            />
          </div>
          {error && (
            <p className="text-sm text-red-500 bg-red-500/10 p-2 rounded-lg text-center">{error}</p>
          )}
          <Button type="submit" disabled={loading || !username.trim() || !password.trim()} className="w-full gap-2">
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <LogIn className="w-4 h-4" />}
            {loading ? 'جارٍ التحقق...' : 'تسجيل الدخول'}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}

/* ─── Banner Admin Panel ─── */
function BannerAdmin({ open, onOpenChange }: { open: boolean; onOpenChange: (v: boolean) => void }) {
  const [adType, setAdType] = useState<'image' | 'external'>('image');
  const [imageUrl, setImageUrl] = useState('');
  const [adCode, setAdCode] = useState('');
  const [linkUrl, setLinkUrl] = useState('');
  const [text, setText] = useState('');
  const [active, setActive] = useState(false);
  const [position, setPosition] = useState('top');
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Load existing banner on open
  useEffect(() => {
    if (!open) return;
    fetch('/api/banner')
      .then((r) => r.json())
      .then((data) => {
        if (data.banner) {
          setAdType((data.banner.adType as 'image' | 'external') || 'image');
          setImageUrl(data.banner.imageUrl || '');
          setAdCode(data.banner.adCode || '');
          setLinkUrl(data.banner.linkUrl);
          setText(data.banner.text);
          setActive(data.banner.active);
          setPosition(data.banner.position);
        } else {
          setAdType('image');
          setImageUrl('');
          setAdCode('');
          setLinkUrl('');
          setText('');
          setActive(false);
          setPosition('top');
        }
        setMessage(null);
      })
      .catch(() => {});
  }, [open]);

  const handleUpload = useCallback(async (file: File) => {
    if (!file.type.startsWith('image/')) return;
    setUploading(true);
    setMessage(null);
    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 || 'فشل رفع الصورة');
      setImageUrl(data.imageUrl);
    } catch (err: unknown) {
      setMessage({ type: 'error', text: err instanceof Error ? err.message : 'خطأ' });
    } finally {
      setUploading(false);
    }
  }, []);

  const handleSave = useCallback(async () => {
    if (adType === 'image' && !imageUrl) {
      setMessage({ type: 'error', text: 'يرجى رفع صورة البانر أولاً' });
      return;
    }
    if (adType === 'external' && !adCode.trim()) {
      setMessage({ type: 'error', text: 'يرجى لصق كود الإعلان الخارجي' });
      return;
    }
    setSaving(true);
    setMessage(null);
    try {
      const res = await fetch('/api/banner', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ adType, imageUrl, adCode, linkUrl, text, active, position }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'فشل الحفظ');
      setMessage({ type: 'success', text: 'تم حفظ البانر بنجاح' });
    } catch (err: unknown) {
      setMessage({ type: 'error', text: err instanceof Error ? err.message : 'خطأ' });
    } finally {
      setSaving(false);
    }
  }, [adType, imageUrl, adCode, linkUrl, text, active, position]);

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md max-h-[90vh] overflow-y-auto" dir="rtl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Megaphone className="w-5 h-5" />
            إدارة البانر الإعلاني
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4 mt-2">
          {/* Ad Type Selector */}
          <div className="space-y-2">
            <Label>نوع الإعلان</Label>
            <div className="grid grid-cols-2 gap-2">
              <button
                onClick={() => setAdType('image')}
                className={`p-3 rounded-lg border text-sm font-medium transition-all flex flex-col items-center gap-1.5 ${
                  adType === 'image'
                    ? 'border-primary bg-primary/10 text-primary'
                    : 'border-border/50 hover:border-primary/30 text-muted-foreground'
                }`}
              >
                <ImageIcon className="w-5 h-5" />
                صورة مرفوعة
              </button>
              <button
                onClick={() => setAdType('external')}
                className={`p-3 rounded-lg border text-sm font-medium transition-all flex flex-col items-center gap-1.5 ${
                  adType === 'external'
                    ? 'border-primary bg-primary/10 text-primary'
                    : 'border-border/50 hover:border-primary/30 text-muted-foreground'
                }`}
              >
                <Code className="w-5 h-5" />
                كود خارجي
              </button>
            </div>
          </div>

          {/* Image Upload (only for image type) */}
          {adType === 'image' && (
            <div className="space-y-2">
              <Label>صورة البانر</Label>
              <div
                onClick={() => !uploading && fileInputRef.current?.click()}
                className={`relative rounded-lg border-2 border-dashed p-4 text-center cursor-pointer transition-all
                  ${imageUrl ? 'border-primary/30' : 'border-muted-foreground/30 hover:border-primary/50'}`}
              >
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={(e) => {
                    const f = e.target.files?.[0];
                    if (f) handleUpload(f);
                    e.target.value = '';
                  }}
                />
                {uploading ? (
                  <div className="flex items-center justify-center gap-2 py-2">
                    <Loader2 className="w-5 h-5 animate-spin text-primary" />
                    <span className="text-sm text-muted-foreground">جارٍ الرفع...</span>
                  </div>
                ) : imageUrl ? (
                  <div className="space-y-2">
                    <img src={imageUrl} alt="بانر" className="w-full h-24 object-cover rounded-md" />
                    <p className="text-xs text-muted-foreground">انقر لتغيير الصورة</p>
                  </div>
                ) : (
                  <div className="py-2">
                    <Upload className="w-8 h-8 mx-auto text-muted-foreground/50 mb-2" />
                    <p className="text-sm text-muted-foreground">انقر لاختيار صورة البانر</p>
                    <p className="text-xs text-muted-foreground mt-1">PNG, JPG, WEBP — حتى 2 ميجا</p>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* External Ad Code (only for external type) */}
          {adType === 'external' && (
            <div className="space-y-2">
              <Label>كود الإعلان الخارجي</Label>
              <p className="text-xs text-muted-foreground">
                الصق كود الإعلان من جوجل أدسنس أو أي شبكة إعلانية أخرى
              </p>
              <Textarea
                value={adCode}
                onChange={(e) => setAdCode(e.target.value)}
                placeholder={'<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXX"></script>\n<ins class="adsbygoogle" ...></ins>'}
                className="min-h-[120px] font-mono text-xs"
                dir="ltr"
              />
            </div>
          )}

          {/* Link URL (only for image type) */}
          {adType === 'image' && (
            <div className="space-y-2">
              <Label>رابط الإعلان (اختياري)</Label>
              <Input
                value={linkUrl}
                onChange={(e) => setLinkUrl(e.target.value)}
                placeholder="https://example.com"
                dir="ltr"
              />
            </div>
          )}

          {/* Text Overlay (only for image type) */}
          {adType === 'image' && (
            <div className="space-y-2">
              <Label>نص على البانر (اختياري)</Label>
              <Input
                value={text}
                onChange={(e) => setText(e.target.value)}
                placeholder="عنوان الإعلان..."
              />
            </div>
          )}

          {/* Position */}
          <div className="space-y-2">
            <Label>موضع البانر</Label>
            <div className="grid grid-cols-3 gap-2">
              {POSITION_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => setPosition(opt.value)}
                  className={`p-2 rounded-lg border text-xs font-medium transition-all
                    ${position === opt.value
                      ? 'border-primary bg-primary/10 text-primary'
                      : 'border-border/50 hover:border-primary/30 text-muted-foreground'}`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {/* Active Toggle */}
          <div className="flex items-center justify-between p-3 rounded-lg border border-border/50">
            <Label className="cursor-pointer">عرض البانر</Label>
            <Switch checked={active} onCheckedChange={setActive} />
          </div>

          {/* Message */}
          <AnimatePresence>
            {message && (
              <motion.div
                initial={{ opacity: 0, y: -5 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0 }}
                className={`text-sm p-3 rounded-lg ${message.type === 'success' ? 'bg-emerald-500/10 text-emerald-600' : 'bg-red-500/10 text-red-600'}`}
              >
                {message.text}
              </motion.div>
            )}
          </AnimatePresence>

          {/* Save Button */}
          <Button
            onClick={handleSave}
            disabled={saving || (adType === 'image' ? !imageUrl : !adCode.trim())}
            className="w-full gap-2"
          >
            {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
            {saving ? 'جارٍ الحفظ...' : 'حفظ البانر'}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}

/* ─── Edit Tool Definitions ─── */
const EDIT_TOOLS = [
  { id: 'oil-painting', label: 'لوحة زيتية', icon: 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: 'رسم كرتوني', icon: 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: 'أبيض وأسود', icon: 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: 'إضاءة ذهبية', icon: 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: 'تحسين الجودة', icon: 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: 'خلفية احترافية', icon: 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: 'تأثير سينمائي', icon: 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: 'أسلوب رسومي', icon: 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' },
];

/* ─── Header Component ─── */
function Header({
  isAdmin,
  isLoading,
  onOpenBannerAdmin,
  onOpenLogin,
  onLogout,
}: {
  isAdmin: boolean;
  isLoading: boolean;
  onOpenBannerAdmin: () => void;
  onOpenLogin: () => void;
  onLogout: () => void;
}) {
  const { currentView, setView } = useAppStore();
  return (
    <header className="glass sticky top-0 z-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
        <button
          onClick={() => setView('home')}
          className="flex items-center gap-3 group"
        >
          <div className="w-9 h-9 rounded-lg bg-primary/20 flex items-center justify-center">
            <Wand2 className="w-5 h-5 text-primary" />
          </div>
          <span className="text-lg font-bold gradient-text">محرر الصور Fouad AI</span>
        </button>
        <nav className="flex items-center gap-1">
          <Button
            variant={currentView === 'home' ? 'default' : 'ghost'}
            size="sm"
            onClick={() => setView('home')}
            className="gap-2"
          >
            <ImageIcon className="w-4 h-4" />
            <span className="hidden sm:inline">الرئيسية</span>
          </Button>
          <Button
            variant={currentView === 'gallery' ? 'default' : 'ghost'}
            size="sm"
            onClick={() => setView('gallery')}
            className="gap-2"
          >
            <History className="w-4 h-4" />
            <span className="hidden sm:inline">المعرض</span>
          </Button>
          <Button
            variant={currentView === 'generate' ? 'default' : 'ghost'}
            size="sm"
            onClick={() => setView('generate')}
            className="gap-2"
          >
            <WandSparkles className="w-4 h-4" />
            <span className="hidden sm:inline">توليد الصور</span>
          </Button>
          {!isLoading && (
            isAdmin ? (
              <>
                <Button
                  variant="ghost"
                  size="icon"
                  className="mr-1"
                  onClick={onOpenBannerAdmin}
                  title="إدارة البانر"
                >
                  <Settings className="w-4 h-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={onLogout}
                  title="تسجيل الخروج"
                  className="text-red-400 hover:text-red-300 hover:bg-red-500/10"
                >
                  <LogOut className="w-4 h-4" />
                </Button>
              </>
            ) : (
              <Button
                variant="ghost"
                size="icon"
                className="mr-1"
                onClick={onOpenLogin}
                title="دخول المدير"
              >
                <LogIn className="w-4 h-4" />
              </Button>
            )
          )}
        </nav>
      </div>
    </header>
  );
}

/* ─── Footer Component ─── */
function Footer() {
  return (
    <footer className="glass mt-auto">
      <div className="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-muted-foreground">
        <p>محرر الصور Fouad AI — قوّة الذكاء الاصطناعي بين يديك</p>
        <p>© {new Date().getFullYear()} جميع الحقوق محفوظة</p>
      </div>
    </footer>
  );
}

/* ─── Upload Area Component ─── */
function UploadArea() {
  const { setOriginalImage, setOriginalFileName, setView, setAnalysis, setEditedImage, setEditError } = useAppStore();
  const [isDragOver, setIsDragOver] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFile = useCallback(async (file: File) => {
    if (!file.type.startsWith('image/')) return;
    setIsUploading(true);
    setEditError(null);
    setEditedImage(null);
    setAnalysis(null);
    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 || 'فشل رفع الصورة');

      setOriginalImage(data.imageUrl);
      setOriginalFileName(file.name);
      setView('editor');
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'حدث خطأ';
      setEditError(message);
    } finally {
      setIsUploading(false);
    }
  }, [setOriginalImage, setOriginalFileName, setView, setEditedImage, setAnalysis, setEditError]);

  const onDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  }, [handleFile]);

  const onDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(true);
  }, []);

  const onDragLeave = useCallback(() => setIsDragOver(false), []);

  return (
    <motion.div
      initial={{ opacity: 0, y: 30 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.6 }}
      className="w-full max-w-2xl mx-auto"
    >
      <div
        onDrop={onDrop}
        onDragOver={onDragOver}
        onDragLeave={onDragLeave}
        onClick={() => fileInputRef.current?.click()}
        className={`
          relative cursor-pointer rounded-2xl border-2 border-dashed p-12 sm:p-16
          transition-all duration-300 text-center
          ${isDragOver
            ? 'upload-area-active border-primary'
            : 'border-muted-foreground/30 hover:border-primary/50 hover:bg-primary/5'
          }
        `}
      >
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          className="hidden"
          onChange={(e) => {
            const file = e.target.files?.[0];
            if (file) handleFile(file);
            e.target.value = '';
          }}
        />
        {isUploading ? (
          <div className="flex flex-col items-center gap-4">
            <Loader2 className="w-12 h-12 text-primary animate-spin" />
            <p className="text-lg text-muted-foreground">جارٍ رفع الصورة...</p>
          </div>
        ) : (
          <div className="flex flex-col items-center gap-4">
            <div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center">
              <Upload className="w-10 h-10 text-primary" />
            </div>
            <div>
              <p className="text-xl font-semibold mb-2">اسحب الصورة هنا أو انقر للاختيار</p>
              <p className="text-muted-foreground text-sm">يدعم: PNG, JPG, WEBP — حتى 10 ميجا</p>
            </div>
          </div>
        )}
      </div>
    </motion.div>
  );
}

/* ─── Feature Cards ─── */
function FeatureCards() {
  const features = [
    { icon: Sparkles, title: 'تحرير بالذكاء', desc: 'أدوات تعديل ذكية تفهم صورتك وتحسّنها' },
    { icon: Palette, title: 'أنماط فنية', desc: 'حوّل صورك إلى لوحات زيتية أو رسوم كرتونية' },
    { icon: SlidersHorizontal, title: 'مقارنة فورية', desc: 'قارن بين الأصل والنسخة المحرّرة بسهولة' },
    { icon: Download, title: 'تحميل مباشر', desc: 'حمّل الصور المحرّرة بجودة عالية' },
  ];
  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 max-w-5xl mx-auto mt-16">
      {features.map((f, i) => (
        <motion.div
          key={f.title}
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.2 + i * 0.1 }}
        >
          <Card className="glass h-full text-center p-4 sm:p-6">
            <CardContent className="p-0 flex flex-col items-center gap-3">
              <div className="w-12 h-12 rounded-xl bg-primary/15 flex items-center justify-center">
                <f.icon className="w-6 h-6 text-primary" />
              </div>
              <h3 className="font-semibold text-sm sm:text-base">{f.title}</h3>
              <p className="text-xs sm:text-sm text-muted-foreground">{f.desc}</p>
            </CardContent>
          </Card>
        </motion.div>
      ))}
    </div>
  );
}

/* ─── Home View ─── */
function HomeView() {
  return (
    <main className="flex-1 flex flex-col items-center px-4 py-12">
      <div className="my-6">
        <BannerDisplay position="above-upload" />
      </div>
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="text-center mb-10"
      >
        <h1 className="text-4xl sm:text-5xl lg:text-6xl font-bold mb-4">
          <span className="gradient-text">محرر الصور Fouad AI</span>
        </h1>
        <p className="text-lg sm:text-xl text-muted-foreground max-w-xl mx-auto">
          ارفع صورتك واختر التأثير المطلوب — وشاهد الذكاء الاصطناعي يُبدع
        </p>
      </motion.div>
      <UploadArea />
      <FeatureCards />
      <div className="my-6">
        <BannerDisplay position="below-features" />
      </div>
    </main>
  );
}

/* ─── Before/After Comparison Slider ─── */
function ComparisonSlider({ original, edited }: { original: string; edited: string }) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [position, setPosition] = useState(50);
  const [containerWidth, setContainerWidth] = useState(0);
  const isDragging = useRef(false);

  useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    const observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        setContainerWidth(entry.contentRect.width);
      }
    });
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  const updatePosition = useCallback((clientX: number) => {
    if (!containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();
    // RTL: position is measured from the right edge
    const x = clientX - rect.left;
    const pct = Math.min(100, Math.max(0, (x / rect.width) * 100));
    setPosition(pct);
  }, []);

  const handlePointerDown = useCallback((e: React.PointerEvent) => {
    isDragging.current = true;
    (e.target as HTMLElement).setPointerCapture(e.pointerId);
    updatePosition(e.clientX);
  }, [updatePosition]);

  const handlePointerMove = useCallback((e: React.PointerEvent) => {
    if (!isDragging.current) return;
    updatePosition(e.clientX);
  }, [updatePosition]);

  const handlePointerUp = useCallback(() => {
    isDragging.current = false;
  }, []);

  return (
    <div
      ref={containerRef}
      className="comparison-container rounded-xl overflow-hidden bg-black/50 relative w-full"
      style={{ aspectRatio: 'auto' }}
      onPointerDown={handlePointerDown}
      onPointerMove={handlePointerMove}
      onPointerUp={handlePointerUp}
    >
      {/* Edited image (full width, behind) */}
      <img
        src={edited}
        alt="After"
        className="w-full h-auto block"
        draggable={false}
      />

      {/* Original image (clipped from right in RTL) */}
      <div
        className="absolute inset-0 overflow-hidden"
        style={{ width: `${position}%` }}
      >
        <img
          src={original}
          alt="Before"
          className="w-full h-auto block"
          style={{ width: containerWidth > 0 ? `${containerWidth}px` : '100%' }}
          draggable={false}
        />
      </div>

      {/* Slider line */}
      <div
        className="comparison-slider-line"
        style={{ left: `${position}%` }}
      >
        <div className="comparison-slider-handle">
          <GripVertical className="w-5 h-5 text-gray-700" />
        </div>
      </div>

      {/* Labels */}
      <div className="absolute top-3 right-3 bg-black/60 text-white text-xs px-2 py-1 rounded-md">الأصلي</div>
      <div className="absolute top-3 left-3 bg-primary/80 text-white text-xs px-2 py-1 rounded-md">المحرّر</div>
    </div>
  );
}

/* ─── Editor View ─── */
function EditorView() {
  const {
    originalImage, editedImage, isEditing, editProgress, editError,
    analysis, customPrompt, setCustomPrompt, setEditedImage,
    setEditProgress, setIsEditing, setEditError, setAnalysis,
    setView, resetEditor, projects, setProjects, originalFileName,
  } = useAppStore();
  const [selectedTool, setSelectedTool] = useState<string | null>(null);
  const [lastEditArgs, setLastEditArgs] = useState<{ prompt: string; label: string; toolType: string } | null>(null);
  const [editCount, setEditCount] = useState(0);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleAnalyze = useCallback(async () => {
    if (!originalImage) return;
    setIsAnalyzing(true);
    try {
      const res = await fetch('/api/analyze', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ imageUrl: originalImage }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'فشل التحليل');
      setAnalysis(data.analysis);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'حدث خطأ';
      setEditError(message);
    } finally {
      setIsAnalyzing(false);
    }
  }, [originalImage, setAnalysis, setEditError]);

  const handleEdit = useCallback(async (prompt: string, label: string, toolType: string) => {
    // Use the last edited image as base for stacking edits
    const baseImage = editedImage || originalImage;
    if (!baseImage) return;
    setLastEditArgs({ prompt, label, toolType });
    setIsEditing(true);
    setEditError(null);
    setEditedImage(null);
    setEditProgress(0);

    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?.getReader();
      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: Record<string, unknown>;
            try {
              parsed = JSON.parse(data);
            } catch {
              continue; // Skip malformed JSON lines
            }

            if (parsed.type === 'progress') {
              setEditProgress(parsed.value as number);
            } else if (parsed.type === 'done') {
              setEditedImage(parsed.editedImageUrl as string);
              setEditProgress(100);
              setEditCount((c) => c + 1);
              // Refresh gallery
              try {
                const projectsRes = await fetch('/api/projects');
                if (projectsRes.ok) {
                  const projectsData = await projectsRes.json();
                  setProjects(projectsData);
                }
              } catch { /* ignore gallery refresh failure */ }
            } else if (parsed.type === 'error') {
              throw new Error(parsed.message as string);
            }
          }
        }
      }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'حدث خطأ أثناء التعديل';
      setEditError(message);
    } finally {
      setIsEditing(false);
      setSelectedTool(null);
    }
  }, [originalImage, editedImage, setIsEditing, setEditError, setEditedImage, setEditProgress, setProjects]);

  const handleCustomEdit = useCallback(() => {
    if (!customPrompt.trim()) return;
    handleEdit(customPrompt.trim(), 'تعديل مخصص', 'custom');
  }, [customPrompt, handleEdit]);

  const handleNewImage = useCallback(() => {
    resetEditor();
    setView('home');
  }, [resetEditor, setView]);

  const handleResetToOriginal = useCallback(() => {
    setEditedImage(null);
    setEditCount(0);
    setEditError(null);
  }, [setEditedImage, setEditError]);

  const handleReupload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !file.type.startsWith('image/')) return;
    const formData = new FormData();
    formData.append('image', file);
    try {
      const res = await fetch('/api/upload', { method: 'POST', body: formData });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      useAppStore.getState().setOriginalImage(data.imageUrl);
      useAppStore.getState().setOriginalFileName(file.name);
      useAppStore.getState().setEditedImage(null);
      useAppStore.getState().setAnalysis(null);
    } catch {}
    e.target.value = '';
  }, []);

  const handleDownload = useCallback(() => {
    if (!editedImage) return;
    const a = document.createElement('a');
    a.href = editedImage;
    const ext = originalFileName?.split('.').pop() || 'png';
    const baseName = originalFileName ? originalFileName.replace(/\.[^.]+$/, '') : 'image';
    a.download = `Fouad-AI-${baseName}.${ext}`;
    a.click();
  }, [editedImage, originalFileName]);

  return (
    <main className="flex-1 px-4 py-6 max-w-7xl mx-auto w-full">
      {/* Top bar */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2">
          <Button variant="ghost" onClick={handleNewImage} className="gap-2">
            <ChevronLeft className="w-4 h-4" />
            صورة جديدة
          </Button>
          {editedImage && (
            <Button variant="outline" size="sm" onClick={handleResetToOriginal} className="gap-1.5 text-xs">
              <RotateCcw className="w-3.5 h-3.5" />
              العودة للأصل
            </Button>
          )}
          {editCount > 0 && (
            <span className="text-xs text-muted-foreground bg-muted/50 px-2 py-1 rounded-full">
              {editCount} تعديل{editCount > 1 ? 'ات' : ''}
            </span>
          )}
        </div>
        {editedImage && (
          <Button onClick={handleDownload} className="gap-2">
            <Download className="w-4 h-4" />
            تحميل الصورة
          </Button>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Image Preview (2/3 width on desktop) */}
        <div className="lg:col-span-2">
          <Card className="glass overflow-hidden">
            <CardContent className="p-0 relative">
              {/* Image display */}
              <div className="relative min-h-[300px] sm:min-h-[400px] flex items-center justify-center bg-black/30">
                {isEditing && (
                  <div className="absolute inset-0 z-20 flex flex-col items-center justify-center bg-black/50 backdrop-blur-sm">
                    <Loader2 className="w-12 h-12 text-primary animate-spin mb-4" />
                    <p className="text-lg font-semibold mb-2">جارٍ التعديل بالذكاء الاصطناعي...</p>
                    <Progress value={editProgress} className="w-48 h-2" />
                    <p className="text-sm text-muted-foreground mt-2">{editProgress}%</p>
                  </div>
                )}

                {editedImage ? (
                  <ComparisonSlider original={originalImage!} edited={editedImage} />
                ) : (
                  <img
                    src={originalImage!}
                    alt="Original"
                    className="max-w-full max-h-[70vh] object-contain mx-auto"
                  />
                )}
              </div>

              {/* Image info bar */}
              <div className="p-3 border-t border-border/50 flex items-center justify-between text-sm text-muted-foreground">
                <span className="truncate max-w-[60%]">{originalFileName || 'صورة'}</span>
                <Button variant="ghost" size="sm" className="gap-1 text-xs h-8" onClick={() => fileInputRef.current?.click()}>
                  <RotateCcw className="w-3 h-3" />
                  تغيير الصورة
                </Button>
                <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={handleReupload} />
              </div>
            </CardContent>
          </Card>

          {/* Analysis section */}
          <div className="mt-4">
            <Button
              variant="outline"
              onClick={handleAnalyze}
              disabled={isAnalyzing || !originalImage}
              className="w-full gap-2 mb-3"
            >
              {isAnalyzing ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Eye className="w-4 h-4" />
              )}
              تحليل الصورة بالذكاء الاصطناعي
            </Button>
            <AnimatePresence>
              {analysis && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  exit={{ opacity: 0, height: 0 }}
                >
                  <Card className="glass">
                    <CardContent className="p-4">
                      <h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
                        <Eye className="w-4 h-4 text-primary" />
                        نتيجة التحليل
                      </h3>
                      <p className="text-sm text-muted-foreground leading-relaxed whitespace-pre-wrap">{analysis}</p>
                    </CardContent>
                  </Card>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </div>

        {/* Tools Panel (1/3 width on desktop) */}
        <div className="lg:col-span-1 space-y-4">
          {/* Quick Tools */}
          <Card className="glass">
            <CardContent className="p-4">
              <h3 className="font-semibold mb-3 flex items-center gap-2">
                <Wand2 className="w-4 h-4 text-primary" />
                أدوات التحرير السريعة
              </h3>
              <div className="grid grid-cols-2 gap-2">
                {EDIT_TOOLS.map((tool) => {
                  const Icon = tool.icon;
                  const isLoading = isEditing && selectedTool === tool.id;
                  return (
                    <button
                      key={tool.id}
                      onClick={() => {
                        if (isEditing) return;
                        setSelectedTool(tool.id);
                        handleEdit(tool.prompt, tool.label, 'quick-tool');
                      }}
                      disabled={isEditing}
                      className={`
                        tool-card relative flex flex-col items-center gap-2 p-3 rounded-xl
                        border border-border/50 text-center transition-all
                        ${isLoading ? 'ring-2 ring-primary' : 'hover:border-primary/40'}
                        ${isEditing ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
                      `}
                    >
                      <div className={`w-10 h-10 rounded-lg bg-gradient-to-br ${tool.color} flex items-center justify-center`}>
                        {isLoading ? (
                          <Loader2 className="w-5 h-5 text-primary animate-spin" />
                        ) : (
                          <Icon className="w-5 h-5 text-foreground" />
                        )}
                      </div>
                      <span className="text-xs font-medium">{tool.label}</span>
                    </button>
                  );
                })}
              </div>
            </CardContent>
          </Card>

          {/* Custom Prompt */}
          <Card className="glass">
            <CardContent className="p-4">
              <h3 className="font-semibold mb-3 flex items-center gap-2">
                <Pencil className="w-4 h-4 text-primary" />
                تعديل مخصص
              </h3>
              <Textarea
                value={customPrompt}
                onChange={(e) => setCustomPrompt(e.target.value)}
                placeholder="صِف التعديل الذي تريده... مثال: غيّر الخلفية إلى شاطئ عند الغروب"
                className="min-h-[100px] resize-none mb-3"
                disabled={isEditing}
              />
              <Button
                onClick={handleCustomEdit}
                disabled={isEditing || !customPrompt.trim()}
                className="w-full gap-2"
              >
                {isEditing ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Sparkles className="w-4 h-4" />
                )}
                تطبيق التعديل
              </Button>
            </CardContent>
          </Card>

          {/* Error display */}
          <AnimatePresence>
            {editError && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
              >
                <Card className="border-destructive/50 bg-destructive/10">
                  <CardContent className="p-4 flex items-start gap-3">
                    <X className="w-5 h-5 text-destructive mt-0.5 shrink-0" />
                    <div className="flex-1">
                      <p className="text-sm font-medium text-destructive">حدث خطأ</p>
                      <p className="text-xs text-muted-foreground mt-1">{editError}</p>
                    </div>
                    {lastEditArgs && (
                      <Button
                        variant="outline"
                        size="sm"
                        className="shrink-0 gap-1 text-xs h-8"
                        onClick={() => {
                          setEditError(null);
                          handleEdit(lastEditArgs.prompt, lastEditArgs.label, lastEditArgs.toolType);
                        }}
                      >
                        <RotateCcw className="w-3 h-3" />
                        إعادة المحاولة
                      </Button>
                    )}
                  </CardContent>
                </Card>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
    </main>
  );
}

/* ─── Gallery View ─── */
function GalleryView() {
  const { projects, setProjects, setView, setOriginalImage, setOriginalFileName, setEditedImage, setAnalysis } = useAppStore();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const loadProjects = async () => {
      try {
        const res = await fetch('/api/projects');
        if (res.ok) {
          const data = await res.json();
          setProjects(data);
        }
      } catch {}
      setIsLoading(false);
    };
    loadProjects();
  }, [setProjects]);

  const handleDelete = useCallback(async (id: string) => {
    try {
      const res = await fetch(`/api/projects/${id}`, { method: 'DELETE' });
      if (res.ok) {
        setProjects(projects.filter((p) => p.id !== id));
      }
    } catch {}
  }, [projects, setProjects]);

  const handleOpen = useCallback((project: PhotoProject) => {
    const lastEdit = project.edits?.[project.edits.length - 1];
    if (lastEdit?.editedPath) {
      setOriginalImage(lastEdit.originalPath);
      setEditedImage(lastEdit.editedPath);
      setOriginalFileName(project.title);
      setAnalysis(null);
      setView('editor');
    } else if (lastEdit) {
      setOriginalImage(lastEdit.originalPath);
      setEditedImage(null);
      setOriginalFileName(project.title);
      setAnalysis(null);
      setView('editor');
    }
  }, [setOriginalImage, setEditedImage, setOriginalFileName, setAnalysis, setView]);

  if (isLoading) {
    return (
      <main className="flex-1 flex items-center justify-center">
        <Loader2 className="w-8 h-8 text-primary animate-spin" />
      </main>
    );
  }

  return (
    <main className="flex-1 px-4 py-8 max-w-6xl mx-auto w-full">
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="text-center mb-8"
      >
        <h2 className="text-3xl font-bold mb-2">
          <span className="gradient-text">المعرض</span>
        </h2>
        <p className="text-muted-foreground">جميع مشاريع تعديل الصور السابقة</p>
      </motion.div>

      {projects.length === 0 ? (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="text-center py-20"
        >
          <div className="w-20 h-20 rounded-full bg-muted/30 flex items-center justify-center mx-auto mb-4">
            <ImageIcon className="w-10 h-10 text-muted-foreground" />
          </div>
          <p className="text-lg text-muted-foreground mb-4">لا توجد مشاريع بعد</p>
          <Button onClick={() => setView('home')} className="gap-2">
            <Upload className="w-4 h-4" />
            ابدأ بتعديل صورة
          </Button>
        </motion.div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {projects.map((project, i) => {
            const lastEdit = project.edits?.[project.edits.length - 1];
            const thumbnail = lastEdit?.editedPath || lastEdit?.originalPath || '';
            return (
              <motion.div
                key={project.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.05 }}
              >
                <Card className="glass overflow-hidden group cursor-pointer hover:border-primary/40 transition-all" onClick={() => handleOpen(project)}>
                  <div className="aspect-video bg-black/30 relative overflow-hidden">
                    {thumbnail ? (
                      <img src={thumbnail} alt={project.title} className="w-full h-full object-cover" />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center">
                        <ImageIcon className="w-8 h-8 text-muted-foreground" />
                      </div>
                    )}
                    <div className="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center">
                      <span className="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>
                  <CardContent className="p-3 flex items-center justify-between">
                    <div>
                      <p className="font-medium text-sm truncate">{project.title}</p>
                      <p className="text-xs text-muted-foreground">
                        {new Date(project.createdAt).toLocaleDateString('ar-EG')}
                        {project.edits?.length ? ` — ${project.edits.length} تعديل` : ''}
                      </p>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8 text-muted-foreground hover:text-destructive shrink-0"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDelete(project.id);
                      }}
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </CardContent>
                </Card>
              </motion.div>
            );
          })}
        </div>
      )}
    </main>
  );
}

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

function GenerateView() {
  const { setOriginalImage, setOriginalFileName, setView, setEditedImage, setAnalysis } = useAppStore();
  const [prompt, setPrompt] = useState('');
  const [selectedSize, setSelectedSize] = useState('square');
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedImage, setGeneratedImage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [progress, setProgress] = useState(0);
  const [progressMsg, setProgressMsg] = useState('');

  const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const handleGenerate = useCallback(async () => {
    if (!prompt.trim() || isGenerating) return;
    setIsGenerating(true);
    setError(null);
    setGeneratedImage(null);
    setProgress(0);
    setProgressMsg('جارٍ البدء...');

    try {
      // Step 1: Start the job (returns immediately)
      const startRes = await fetch('/api/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt: prompt.trim(), sizeId: selectedSize }),
      });

      const startData = await startRes.json();

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

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

      // Step 2: Poll every 3 seconds until done or error
      const result = await new Promise<{ imageUrl: string }>((resolve, reject) => {
        let attempts = 0;
        const maxAttempts = 120; // 6 minutes max

        pollIntervalRef.current = setInterval(async () => {
          attempts++;

          if (attempts > maxAttempts) {
            if (pollIntervalRef.current) clearInterval(pollIntervalRef.current);
            pollIntervalRef.current = null;
            reject(new Error('انتهت المهلة. حاول مرة أخرى.'));
            return;
          }

          try {
            const pollRes = await fetch(`/api/generate?jobId=${jobId}`);
            const pollData = await pollRes.json();

            if (pollData.error && !pollData.status) {
              if (pollIntervalRef.current) clearInterval(pollIntervalRef.current);
              pollIntervalRef.current = null;
              reject(new Error(pollData.error));
              return;
            }

            // Update progress
            if (pollData.progress !== undefined) {
              setProgress((prev) => Math.max(prev, pollData.progress));
            }
            if (pollData.message) {
              setProgressMsg(pollData.message);
            }

            // Check terminal states
            if (pollData.status === 'done' && pollData.imageUrl) {
              if (pollIntervalRef.current) clearInterval(pollIntervalRef.current);
              pollIntervalRef.current = null;
              resolve({ imageUrl: pollData.imageUrl });
            } else if (pollData.status === 'error') {
              if (pollIntervalRef.current) clearInterval(pollIntervalRef.current);
              pollIntervalRef.current = null;
              reject(new Error(pollData.error || 'فشل توليد الصورة'));
            }
          } catch (pollErr: unknown) {
            // Network error on a single poll — don't abort, just retry
            console.error('[GEN] Poll error, retrying...', pollErr);
          }
        }, 3000);
      });

      setGeneratedImage(result.imageUrl);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'حدث خطأ');
    } finally {
      if (pollIntervalRef.current) {
        clearInterval(pollIntervalRef.current);
        pollIntervalRef.current = null;
      }
      setIsGenerating(false);
    }
  }, [prompt, selectedSize, isGenerating]);

  // Cleanup polling on unmount
  useEffect(() => {
    return () => {
      if (pollIntervalRef.current) {
        clearInterval(pollIntervalRef.current);
        pollIntervalRef.current = null;
      }
    };
  }, []);

  const handleSendToEditor = useCallback(() => {
    if (!generatedImage) return;
    setOriginalImage(generatedImage);
    setOriginalFileName('Fouad-AI-generated.png');
    setEditedImage(null);
    setAnalysis(null);
    setView('editor');
  }, [generatedImage, setOriginalImage, setOriginalFileName, setEditedImage, setAnalysis, setView]);

  const handleDownload = useCallback(() => {
    if (!generatedImage) return;
    const a = document.createElement('a');
    a.href = generatedImage;
    a.download = 'Fouad-AI-generated.png';
    a.click();
  }, [generatedImage]);

  return (
    <main className="flex-1 px-4 py-6 max-w-5xl mx-auto w-full">
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="text-center mb-8"
      >
        <h2 className="text-3xl font-bold mb-2">
          <span className="gradient-text">رسم الصور بالذكاء</span>
        </h2>
        <p className="text-muted-foreground">صِف الصورة التي تريدها وسنرسمها لك</p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Left: Input */}
        <div className="space-y-4">
          {/* Prompt */}
          <Card className="glass">
            <CardContent className="p-4">
              <h3 className="font-semibold mb-3 flex items-center gap-2">
                <Pencil className="w-4 h-4 text-primary" />
                وصف الصورة
              </h3>
              <Textarea
                value={prompt}
                onChange={(e) => setPrompt(e.target.value)}
                placeholder="مثال: قطة جميلة تجلس في حديقة مليئة بالزهور عند الغروب..."
                className="min-h-[120px] resize-none mb-3"
                disabled={isGenerating}
              />
              <p className="text-xs text-muted-foreground mb-3">
                يمكنك الكتابة بالعربية أو الإنجليزية
              </p>

              {/* Size selector */}
              <h4 className="text-sm font-medium mb-2">حجم الصورة</h4>
              <div className="grid grid-cols-4 gap-2">
                {SIZE_OPTIONS.map((s) => {
                  const Icon = s.icon;
                  return (
                    <button
                      key={s.id}
                      onClick={() => setSelectedSize(s.id)}
                      disabled={isGenerating}
                      className={`
                        flex flex-col items-center gap-1.5 p-2.5 rounded-xl border text-center transition-all
                        ${selectedSize === s.id
                          ? 'border-primary bg-primary/10 ring-1 ring-primary/30'
                          : 'border-border/50 hover:border-primary/30'}
                        ${isGenerating ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
                      `}
                    >
                      <Icon className="w-4 h-4 text-foreground" />
                      <span className="text-xs font-medium">{s.label}</span>
                      <span className="text-[10px] text-muted-foreground">{s.desc}</span>
                    </button>
                  );
                })}
              </div>

              {/* Generate button */}
              <Button
                onClick={handleGenerate}
                disabled={isGenerating || !prompt.trim()}
                className="w-full gap-2 mt-4"
                size="lg"
              >
                {isGenerating ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <WandSparkles className="w-5 h-5" />
                )}
                {isGenerating ? 'جارٍ الرسم...' : 'ارسم الصورة'}
              </Button>
            </CardContent>
          </Card>

          {/* Error */}
          <AnimatePresence>
            {error && (
              <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}>
                <Card className="border-destructive/50 bg-destructive/10">
                  <CardContent className="p-4 flex items-start gap-3">
                    <X className="w-5 h-5 text-destructive mt-0.5 shrink-0" />
                    <div className="flex-1">
                      <p className="text-sm font-medium text-destructive">خطأ</p>
                      <p className="text-xs text-muted-foreground mt-1">{error}</p>
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      className="shrink-0 gap-1 text-xs"
                      onClick={() => handleGenerate()}
                    >
                      <RotateCcw className="w-3 h-3" />
                      إعادة المحاولة
                    </Button>
                  </CardContent>
                </Card>
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        {/* Right: Result */}
        <div>
          <Card className="glass overflow-hidden">
            <CardContent className="p-0">
              <div className="relative min-h-[400px] flex items-center justify-center bg-black/30">
                {isGenerating && (
                  <div className="absolute inset-0 z-10 flex flex-col items-center justify-center bg-black/50 backdrop-blur-sm gap-4 px-8">
                    <Loader2 className="w-16 h-16 text-primary animate-spin" />
                    <p className="text-sm font-medium animate-pulse">{progressMsg || 'جارٍ رسم الصورة بالذكاء الاصطناعي...'}</p>
                    <Progress value={progress} className="w-64 h-2" />
                    <p className="text-xs text-muted-foreground">{progress}%</p>
                  </div>
                )}

                {generatedImage ? (
                  <img
                    src={generatedImage}
                    alt="Generated"
                    className="w-full h-auto block"
                  />
                ) : !isGenerating ? (
                  <div className="flex flex-col items-center gap-4 py-16">
                    <div className="w-20 h-20 rounded-full bg-muted/20 flex items-center justify-center">
                      <WandSparkles className="w-10 h-10 text-muted-foreground/50" />
                    </div>
                    <p className="text-muted-foreground text-center px-4">
                      الصورة المرسومة ستظهر هنا
                    </p>
                  </div>
                ) : null}
              </div>

              {/* Action buttons */}
              {generatedImage && (
                <div className="p-3 border-t border-border/50 flex items-center gap-2">
                  <Button onClick={handleSendToEditor} className="flex-1 gap-2" size="sm">
                    <ArrowRight className="w-4 h-4" />
                    تعديل الصورة
                  </Button>
                  <Button onClick={handleDownload} variant="outline" className="gap-2" size="sm">
                    <Download className="w-4 h-4" />
                    تحميل
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Example prompts */}
          {!generatedImage && !isGenerating && (
            <Card className="glass mt-4">
              <CardContent className="p-4">
                <h4 className="text-sm font-medium mb-3 flex items-center gap-2">
                  <Sparkles className="w-4 h-4 text-primary" />
                  أفكار للتجربة
                </h4>
                <div className="flex flex-wrap gap-2">
                  {[
                    'غروب على شاطئ بصخور ملساء',
                    'مدينة مستقبلية بالليل',
                    'طائر فيلمنق زاهي الألوان',
                    'قرية جبلية وسط الضباب',
                  ].map((example) => (
                    <button
                      key={example}
                      onClick={() => setPrompt(example)}
                      className="text-xs px-3 py-1.5 rounded-full border border-border/50 hover:border-primary/40 hover:bg-primary/5 transition-all cursor-pointer"
                    >
                      {example}
                    </button>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </main>
  );
}

/* ─── Main Client Component ─── */
export default function HomeClient() {
  const { currentView, editError, setEditError } = useAppStore();
  const [bannerAdminOpen, setBannerAdminOpen] = useState(false);
  const [loginOpen, setLoginOpen] = useState(false);
  const { isAdmin, isLoading, refresh: refreshSession } = useAdminSession();

  const handleLoginSuccess = useCallback(() => {
    refreshSession().then(() => {
      setBannerAdminOpen(true);
    });
  }, [refreshSession]);

  const handleLogout = useCallback(async () => {
    await signOut({ redirect: false });
    refreshSession();
  }, [refreshSession]);

  const handleSettingsClick = useCallback(() => {
    if (isAdmin) {
      setBannerAdminOpen(true);
    } else {
      setLoginOpen(true);
    }
  }, [isAdmin]);

  // Dismiss errors on click outside
  useEffect(() => {
    if (editError) {
      const timer = setTimeout(() => setEditError(null), 8000);
      return () => clearTimeout(timer);
    }
  }, [editError, setEditError]);

  return (
    <div className="min-h-screen flex flex-col">
      <Header
        isAdmin={isAdmin}
        isLoading={isLoading}
        onOpenBannerAdmin={handleSettingsClick}
        onOpenLogin={() => setLoginOpen(true)}
        onLogout={handleLogout}
      />
      <div className="w-full">
        <BannerDisplay position="top" />
      </div>
      <LoginDialog open={loginOpen} onOpenChange={setLoginOpen} onLoginSuccess={handleLoginSuccess} />
      <BannerAdmin open={bannerAdminOpen} onOpenChange={setBannerAdminOpen} />
      <AnimatePresence mode="wait">
        {currentView === 'home' && (
          <motion.div key="home" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="flex-1">
            <HomeView />
          </motion.div>
        )}
        {currentView === 'editor' && (
          <motion.div key="editor" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="flex-1 flex flex-col">
            <EditorView />
          </motion.div>
        )}
        {currentView === 'gallery' && (
          <motion.div key="gallery" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="flex-1">
            <GalleryView />
          </motion.div>
        )}
        {currentView === 'generate' && (
          <motion.div key="generate" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="flex-1 flex flex-col">
            <GenerateView />
          </motion.div>
        )}
      </AnimatePresence>
      <Footer />
    </div>
  );
}