const { useState, useEffect, useRef, useCallback } = React;

/* ===== HOOKS ===== */
function useScrolled(threshold = 40) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > threshold);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [threshold]);
  return scrolled;
}

function useInView(opts = {}) {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setInView(true); obs.disconnect(); }
    }, { threshold: 0.12, ...opts });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return [ref, inView];
}

/* ===== INTERACTIVE PARTICLE NETWORK BACKGROUND =====
   Floating nodes connected by faint lines — a network metaphor
   that fits the franchise / business-networking theme.
   The cursor pushes particles away, brightens nearby connections,
   and emits a soft glow that follows it. */
function InteractiveBg() {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');

    let particles = [];
    const mouse = { x: -10000, y: -10000, active: false, t: 0 };
    let w = 0, h = 0, dpr = 1, rafId;

    const setup = () => {
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = window.innerWidth;
      h = window.innerHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      canvas.style.width = w + 'px';
      canvas.style.height = h + 'px';
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.scale(dpr, dpr);

      // Density-aware particle count (lighter on mobile for perf)
      const isMobile = w < 768;
      const divisor = isMobile ? 22000 : 16000;
      const minCount = isMobile ? 22 : 40;
      const maxCount = isMobile ? 45 : 110;
      const count = Math.max(minCount, Math.min(maxCount, Math.floor((w * h) / divisor)));
      particles = [];
      for (let i = 0; i < count; i++) {
        particles.push({
          x: Math.random() * w,
          y: Math.random() * h,
          vx: (Math.random() - 0.5) * 0.35,
          vy: (Math.random() - 0.5) * 0.35,
          r: Math.random() * 1.4 + 0.6,
          baseR: 0,
          phase: Math.random() * Math.PI * 2,
        });
        particles[i].baseR = particles[i].r;
      }
    };

    const LINK_DIST = 140;
    const MOUSE_RADIUS = 160;

    const animate = (now) => {
      ctx.clearRect(0, 0, w, h);

      // Mouse glow (soft radial)
      if (mouse.active) {
        const grad = ctx.createRadialGradient(mouse.x, mouse.y, 0, mouse.x, mouse.y, 220);
        grad.addColorStop(0, 'rgba(208, 128, 32, 0.12)');
        grad.addColorStop(0.4, 'rgba(0, 64, 96, 0.045)');
        grad.addColorStop(1, 'rgba(208, 128, 32, 0)');
        ctx.fillStyle = grad;
        ctx.beginPath();
        ctx.arc(mouse.x, mouse.y, 220, 0, Math.PI * 2);
        ctx.fill();
      }

      // Update particles
      for (let i = 0; i < particles.length; i++) {
        const p = particles[i];

        // Mouse repel
        if (mouse.active) {
          const dx = p.x - mouse.x;
          const dy = p.y - mouse.y;
          const d2 = dx * dx + dy * dy;
          if (d2 < MOUSE_RADIUS * MOUSE_RADIUS && d2 > 0.01) {
            const d = Math.sqrt(d2);
            const force = (1 - d / MOUSE_RADIUS) * 0.7;
            p.vx += (dx / d) * force * 0.18;
            p.vy += (dy / d) * force * 0.18;
          }
        }

        // Drift
        p.x += p.vx;
        p.y += p.vy;
        p.vx *= 0.985;
        p.vy *= 0.985;

        // Maintain gentle baseline motion
        const speed = Math.sqrt(p.vx * p.vx + p.vy * p.vy);
        if (speed < 0.12) {
          p.vx += (Math.random() - 0.5) * 0.04;
          p.vy += (Math.random() - 0.5) * 0.04;
        }

        // Wrap edges
        if (p.x < -10) p.x = w + 10;
        if (p.x > w + 10) p.x = -10;
        if (p.y < -10) p.y = h + 10;
        if (p.y > h + 10) p.y = -10;

        // Subtle pulse on radius
        p.r = p.baseR + Math.sin(now * 0.002 + p.phase) * 0.25;
      }

      // Draw connections
      ctx.lineWidth = 0.7;
      for (let i = 0; i < particles.length; i++) {
        const a = particles[i];
        for (let j = i + 1; j < particles.length; j++) {
          const b = particles[j];
          const dx = a.x - b.x;
          const dy = a.y - b.y;
          const d2 = dx * dx + dy * dy;
          if (d2 < LINK_DIST * LINK_DIST) {
            const d = Math.sqrt(d2);
            let alpha = (1 - d / LINK_DIST) * 0.18;
            // Boost connections near mouse
            if (mouse.active) {
              const mx = (a.x + b.x) / 2 - mouse.x;
              const my = (a.y + b.y) / 2 - mouse.y;
              const md = Math.sqrt(mx * mx + my * my);
              if (md < MOUSE_RADIUS) alpha += (1 - md / MOUSE_RADIUS) * 0.4;
            }
            ctx.strokeStyle = `rgba(0, 64, 96, ${alpha * 0.58})`;
            ctx.beginPath();
            ctx.moveTo(a.x, a.y);
            ctx.lineTo(b.x, b.y);
            ctx.stroke();
          }
        }
      }

      // Draw particles (with glow near mouse)
      for (let i = 0; i < particles.length; i++) {
        const p = particles[i];
        let alpha = 0.7;
        let color = '0, 64, 96';
        if (mouse.active) {
          const dx = p.x - mouse.x;
          const dy = p.y - mouse.y;
          const d = Math.sqrt(dx * dx + dy * dy);
          if (d < MOUSE_RADIUS) {
            const t = 1 - d / MOUSE_RADIUS;
            alpha = 0.7 + t * 0.3;
            color = '208, 128, 32';
            // Outer halo
            ctx.fillStyle = `rgba(208, 128, 32, ${t * 0.18})`;
            ctx.beginPath();
            ctx.arc(p.x, p.y, p.r * 4, 0, Math.PI * 2);
            ctx.fill();
          }
        }
        ctx.fillStyle = `rgba(${color}, ${alpha})`;
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
        ctx.fill();
      }

      rafId = requestAnimationFrame(animate);
    };

    const onMove = (e) => {
      mouse.x = e.clientX;
      mouse.y = e.clientY;
      mouse.active = true;
    };
    // Skip touch interaction — lets scroll feel native on mobile,
    // particles still drift and look alive on their own.
    const onLeave = () => { mouse.active = false; };
    const onResize = () => setup();

    setup();
    rafId = requestAnimationFrame(animate);
    window.addEventListener('mousemove', onMove, { passive: true });
    window.addEventListener('mouseout', onLeave);
    window.addEventListener('resize', onResize);

    return () => {
      cancelAnimationFrame(rafId);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseout', onLeave);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  return <canvas ref={canvasRef} className="bg-canvas" aria-hidden="true" />;
}

/* ===== LOGOS ===== */
function IFOELogo() {
  return (
    <img
      src="/ifoe-assets/ifoe-logo-navy-horizontal.png"
      alt="IFOE logo"
      style={{ width: 206, maxWidth: '46vw', height: 'auto', display: 'block' }}
    />
  );
}

/* ===== ICONS ===== */
function Icon({ name, size = 20, color = 'currentColor' }) {
  const icons = {
    location: <><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5a2.5 2.5 0 110-5 2.5 2.5 0 010 5z" fill={color} /></>,
    calendar: <><path d="M19 4h-1V2h-2v2H8V2H6v2H5a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2V6a2 2 0 00-2-2zm0 16H5V10h14v10zM5 8V6h14v2H5z" fill={color} /></>,
    phone: <><path d="M6.62 10.79a15.15 15.15 0 006.59 6.59l2.2-2.2a1 1 0 011.01-.24 11.36 11.36 0 003.58.57 1 1 0 011 1V20a1 1 0 01-1 1A17 17 0 013 4a1 1 0 011-1h3.5a1 1 0 011 1 11.36 11.36 0 00.57 3.58 1 1 0 01-.25 1.01l-2.2 2.2z" fill={color} /></>,
    handshake: <><path d="M3 12l5-5 4 4 4-4 5 5M3 12v5a2 2 0 002 2h14a2 2 0 002-2v-5M3 12l9 9M21 12l-9 9" strokeWidth="1.5" stroke={color} fill="none" strokeLinecap="round" strokeLinejoin="round" /></>,
    chart: <><rect x="3" y="13" width="4" height="8" rx="1" fill={color} /><rect x="10" y="8" width="4" height="13" rx="1" fill={color} /><rect x="17" y="3" width="4" height="18" rx="1" fill={color} /></>,
    users: <><path d="M16 21v-2a4 4 0 00-4-4H6a4 4 0 00-4 4v2" strokeWidth="1.5" stroke={color} fill="none" /><circle cx="9" cy="7" r="4" strokeWidth="1.5" stroke={color} fill="none" /><path d="M22 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" strokeWidth="1.5" stroke={color} fill="none" /></>,
    megaphone: <><path d="M3 11v2l13 5V6L3 11zM18 7v10M21 9v6" strokeWidth="1.5" stroke={color} fill="none" strokeLinecap="round" strokeLinejoin="round" /></>,
    check: <><polyline points="20 6 9 17 4 12" strokeWidth="2.5" stroke={color} fill="none" strokeLinecap="round" strokeLinejoin="round" /></>,
    email: <><path d="M4 4h16a2 2 0 012 2v12a2 2 0 01-2 2H4a2 2 0 01-2-2V6a2 2 0 012-2z" strokeWidth="1.5" stroke={color} fill="none" /><polyline points="22,6 12,13 2,6" strokeWidth="1.5" stroke={color} fill="none" /></>,
    web: <><circle cx="12" cy="12" r="10" strokeWidth="1.5" stroke={color} fill="none" /><path d="M2 12h20" strokeWidth="1.5" stroke={color} fill="none" /><path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10A15.3 15.3 0 0112 2z" strokeWidth="1.5" stroke={color} fill="none" /></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      {icons[name] || null}
    </svg>
  );
}

/* ===== NAVBAR ===== */
function Navbar() {
  const scrolled = useScrolled();
  const [menuOpen, setMenuOpen] = useState(false);
  const navItems = [
    { href: '#about', label: 'عن المعرض' },
    { href: '#stats', label: 'الأرقام' },
    { href: '#gallery', label: 'المعرض' },
    { href: 'https://ifoe-ksa.com/en', label: 'English', lang: 'en', dir: 'ltr' },
    { href: '#register', label: 'سجل الآن', cta: true },
  ];

  useEffect(() => {
    document.body.classList.toggle('menu-open', menuOpen);
    const onKey = e => { if (e.key === 'Escape') setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.classList.remove('menu-open');
      window.removeEventListener('keydown', onKey);
    };
  }, [menuOpen]);

  const closeMenu = () => setMenuOpen(false);

  return (
    <nav className={`navbar ${scrolled ? 'scrolled' : ''} ${menuOpen ? 'menu-open' : ''}`}>
      <div className="nav-inner">
        <div className="nav-logos">
          <IFOELogo />
        </div>
        <div className="nav-links">
          {navItems.slice(0, 4).map(item => (
            <a key={item.href} href={item.href} className="nav-text-link" lang={item.lang} dir={item.dir}>{item.label}</a>
          ))}
          <a href="#register" className="nav-cta">سجل الآن</a>
          <button className="nav-burger" type="button" aria-label="فتح القائمة" aria-expanded={menuOpen} onClick={() => setMenuOpen(v => !v)}>
            <span></span><span></span><span></span>
          </button>
        </div>
      </div>
      <div className={`mobile-menu-backdrop ${menuOpen ? 'open' : ''}`} onClick={closeMenu}></div>
      <div className={`mobile-menu-panel ${menuOpen ? 'open' : ''}`} role="dialog" aria-modal="true" aria-label="قائمة الموقع">
        <div className="mobile-menu-head">
          <span>قائمة الموقع</span>
          <button type="button" aria-label="إغلاق القائمة" onClick={closeMenu}>×</button>
        </div>
        <div className="mobile-menu-links">
          {navItems.map(item => (
            <a key={item.href} href={item.href} className={item.cta ? 'menu-cta' : ''} lang={item.lang} dir={item.dir} onClick={closeMenu}>{item.label}</a>
          ))}
        </div>
      </div>
    </nav>
  );
}

/* ===== HERO ===== */
function Hero({ heroVideo }) {
  const videoSrc = heroVideo?.src || '/uploads/ifoe-gallery/ifoe-hero-background-muted.mp4';
  const poster = heroVideo?.poster || '/uploads/ifoe-gallery/ifoe-last-version-poster.jpg';
  return (
    <section className="hero hero-with-video">
      <div className="hero-video-layer" aria-hidden="true">
        <video src={videoSrc} poster={poster} autoPlay muted loop playsInline preload="metadata" />
        <div className="hero-video-white-overlay"></div>
      </div>
      <div className="hero-content">
        <div className="hero-badge">النسخة الرابعة</div>
        <h1 className="hero-title">معرض فرص الامتياز التجاري الدولي - iFOE</h1>
        <p className="hero-subtitle">أكبر و أقوى معرض للفرنشايز في المملكة العربية السعودية</p>
        <div className="hero-features">
          <div className="hero-feature"><span className="dot"></span>توسع محلي ودولي</div>
          <div className="hero-feature"><span className="dot"></span>تواصل مباشر</div>
          <div className="hero-feature"><span className="dot"></span>شراكات حقيقية</div>
        </div>
        <a href="#register" className="hero-cta">سجل حضورك الآن</a>
        <a href="/signup" className="hero-quick-link">رابط التسجيل السريع</a>
      </div>
    </section>
  );
}

/* ===== EVENT INFO BAR ===== */
function EventInfoBar() {
  return (
    <div className="event-bar">
      <div className="event-bar-inner">
        <div className="event-bar-item">
          <div className="event-bar-icon">
            <Icon name="location" size={18} color="var(--accent-light)" />
          </div>
          <span>جدة - مركز جدة للمعارض والفعاليات</span>
        </div>
        <div className="event-bar-item">
          <div className="event-bar-icon">
            <Icon name="calendar" size={18} color="var(--accent-light)" />
          </div>
          <span>٣ - ٥ سبتمبر ٢٠٢٦</span>
        </div>
        <div className="event-bar-item">
          <div className="event-bar-icon">
            <Icon name="phone" size={18} color="var(--accent-light)" />
          </div>
          <span style={{ direction: 'ltr' }}>0565414847</span>
        </div>
      </div>
    </div>
  );
}

/* ===== REGISTRATION FORM ===== */
const INTERESTS = [
  'الأغذية والمقاهي والمطاعم', 'التجزئة', 'التعليم والتدريب',
  'الصحة والتجميل', 'التقنية', 'الخدمات المالية',
  'التشغيل والصيانة', 'الاستشارات', 'أخرى'
];
const PARTICIPANT_TYPES = [
  { value: 'visitor', label: 'زائر' },
  { value: 'exhibitor', label: 'عارض' }
];

function validate(d) {
  const e = {};
  if (!d.participantType) e.participantType = 'اختر نوع التسجيل';
  if (!d.fullName.trim()) e.fullName = 'الاسم الكامل مطلوب';
  if (!d.email.trim()) e.email = 'البريد الإلكتروني مطلوب';
  else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.email)) e.email = 'صيغة بريد غير صالحة';
  if (!d.phone.trim()) e.phone = 'رقم الجوال مطلوب';
  else if (!/^05\d{8}$/.test(d.phone.replace(/\s/g, ''))) e.phone = 'رقم غير صالح (مثال: 05xxxxxxxx)';
  if (!d.company.trim()) e.company = 'اسم الشركة مطلوب';
  if (!d.jobTitle.trim()) e.jobTitle = 'المسمى الوظيفي مطلوب';
  if (!d.city.trim()) e.city = 'المدينة مطلوبة';
  if (!d.interest) e.interest = 'اختر مجال الاهتمام';
  return e;
}

function RegistrationSection() {
  const [ref, inView] = useInView();
  const [form, setForm] = useState({
    fullName: '', email: '', phone: '', company: '',
    jobTitle: '', city: '', interest: '', opportunityType: ''
  });
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [otpVisible, setOtpVisible] = useState(false);
  const [otp, setOtp] = useState('');
  const [status, setStatus] = useState('');
  const [statusType, setStatusType] = useState('ok');
  const [cardUrl, setCardUrl] = useState('');

  const handleChange = (field, value) => {
    setForm(prev => ({ ...prev, [field]: value }));
    if (touched[field]) {
      const newErrors = validate({ ...form, [field]: value });
      setErrors(prev => ({ ...prev, [field]: newErrors[field] || undefined }));
    }
  };

  const handleBlur = (field) => {
    setTouched(prev => ({ ...prev, [field]: true }));
    const newErrors = validate(form);
    setErrors(prev => ({ ...prev, [field]: newErrors[field] || undefined }));
  };

  const showStatus = (message, type = 'ok') => {
    setStatus(message);
    setStatusType(type);
  };

  const buildPayload = () => {
    const fd = new FormData();
    fd.set('event', 'ifoe');
    fd.set('gender', '');
    fd.set('participantType', form.participantType);
    fd.set('name', form.fullName.trim());
    fd.set('email', form.email.trim());
    fd.set('phone', form.phone.trim());
    fd.set('company', form.company.trim());
    fd.set('jobTitle', form.jobTitle.trim());
    fd.set('city', form.city.trim() || '???');
    fd.set('sector', form.interest);
    fd.set('interest', form.opportunityType.trim());
    return fd;
  };

  const finishWithUid = (uid) => {
    if (uid) setCardUrl('/card?uid=' + encodeURIComponent(uid) + '&event=ifoe');
    setOtpVisible(false);
    setSubmitted(true);
  };

  const requestOtp = async (email) => {
    const res = await fetch('/api/guest/request-otp', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, channel: 'email', event: 'ifoe' })
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) throw new Error(data.error || 'تعذر إرسال رمز التحقق');
    setOtpVisible(true);
    showStatus('تم إرسال رمز التحقق إلى بريدك الإلكتروني. أدخل الرمز لإكمال التسجيل.', 'ok');
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const newErrors = validate(form);
    setErrors(newErrors);
    setTouched(Object.keys(form).reduce((a, k) => ({ ...a, [k]: true }), {}));
    if (Object.keys(newErrors).length > 0) return;
    setSubmitting(true);
    setStatus('');
    try {
      const res = await fetch('/api/guest/signup', { method: 'POST', body: buildPayload() });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'تعذر إكمال التسجيل');
      const uid = data.uid || (data.attendee && data.attendee.uid) || '';
      if (data.attendee && !data.canSendOtp) return finishWithUid(uid);
      if (uid) setCardUrl('/card?uid=' + encodeURIComponent(uid) + '&event=ifoe');
      await requestOtp(form.email.trim());
    } catch (err) {
      showStatus(err.message || 'تعذر إكمال التسجيل', 'err');
    } finally {
      setSubmitting(false);
    }
  };

  const verifyOtp = async () => {
    if (!otp.trim()) return showStatus('أدخل رمز التحقق أولاً.', 'err');
    setSubmitting(true);
    try {
      const res = await fetch('/api/guest/verify-otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: form.email.trim(), channel: 'email', code: otp.trim(), event: 'ifoe' })
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'رمز التحقق غير صحيح');
      const uid = (data.attendee && data.attendee.uid) || '';
      finishWithUid(uid);
    } catch (err) {
      showStatus(err.message || 'تعذر تأكيد الرمز', 'err');
    } finally {
      setSubmitting(false);
    }
  };

  const resetForm = () => {
    setSubmitted(false);
    setOtpVisible(false);
    setOtp('');
    setStatus('');
    setCardUrl('');
    setForm({ participantType: 'visitor', fullName: '', email: '', phone: '', company: '', jobTitle: '', city: '', interest: '', opportunityType: '' });
    setTouched({});
    setErrors({});
  };

  const fieldErr = (f) => touched[f] && errors[f];

  if (submitted) {
    return (
      <section className="section register-section" id="register">
        <div className="section-inner">
          <div className="success-card" style={{ maxWidth: 600, margin: '0 auto' }}>
            <div className="success-icon">
              <Icon name="check" size={32} color="#fff" />
            </div>
            <h2 className="success-title">تم التسجيل بنجاح!</h2>
            <p className="success-desc">ستتلقى رسالة تأكيد على بريدك الإلكتروني مع بطاقة الحضور.</p>
            <div className="success-details">
              <div className="success-detail-row">
                <span style={{ color: 'var(--text-70)' }}>الاسم</span>
                <span style={{ fontWeight: 700 }}>{form.fullName}</span>
              </div>
              <div className="success-detail-row">
                <span style={{ color: 'var(--text-70)' }}>البريد</span>
                <span style={{ fontWeight: 700, direction: 'ltr' }}>{form.email}</span>
              </div>
              <div className="success-detail-row">
                <span style={{ color: 'var(--text-70)' }}>المعرض</span>
                <span style={{ fontWeight: 700 }}>iFOE 2026</span>
              </div>
              <div className="success-detail-row">
                <span style={{ color: 'var(--text-70)' }}>البطاقة</span>
                <span style={{ fontWeight: 700 }}>QR Check-in</span>
              </div>
            </div>
            <button className="hero-cta" onClick={() => { setSubmitted(false); setForm({ participantType: 'visitor', fullName: '', email: '', phone: '', company: '', jobTitle: '', city: '', interest: '', opportunityType: '' }); setTouched({}); setErrors({}); }}>
              تسجيل شخص آخر
            </button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="section register-section" id="register" ref={ref}>
      <div className={`section-inner reveal ${inView ? 'in-view' : ''}`}>
        <h2 className="section-title">سجّل كزائر أو عارض</h2>
        <p className="section-subtitle">اختر نوع التسجيل، ثم أكّد بريدك لاستلام بطاقة الحضور الرقمية.</p>

        <div className="register-grid">
          <form className="form-card" onSubmit={handleSubmit} noValidate>
            <div className="form-grid">
              <div className="form-group full">
                <label className="form-label">نوع التسجيل *</label>
                <select className={`form-select ${fieldErr('participantType') ? 'error' : ''}`} value={form.participantType} onChange={e => handleChange('participantType', e.target.value)} onBlur={() => handleBlur('participantType')}>
                  {PARTICIPANT_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
                </select>
                {fieldErr('participantType') && <span className="form-error">{errors.participantType}</span>}
              </div>
              <div className="form-group">
                <label className="form-label">الاسم الكامل *</label>
                <input className={`form-input ${fieldErr('fullName') ? 'error' : ''}`} value={form.fullName} onChange={e => handleChange('fullName', e.target.value)} onBlur={() => handleBlur('fullName')} placeholder="أدخل اسمك الكامل" />
                {fieldErr('fullName') && <span className="form-error">{errors.fullName}</span>}
              </div>
              <div className="form-group">
                <label className="form-label">البريد الإلكتروني *</label>
                <input className={`form-input ${fieldErr('email') ? 'error' : ''}`} type="email" value={form.email} onChange={e => handleChange('email', e.target.value)} onBlur={() => handleBlur('email')} placeholder="example@email.com" style={{ direction: 'ltr', textAlign: 'right' }} />
                {fieldErr('email') && <span className="form-error">{errors.email}</span>}
              </div>
              <div className="form-group">
                <label className="form-label">رقم الجوال *</label>
                <input className={`form-input ${fieldErr('phone') ? 'error' : ''}`} value={form.phone} onChange={e => handleChange('phone', e.target.value)} onBlur={() => handleBlur('phone')} placeholder="05xxxxxxxx" style={{ direction: 'ltr', textAlign: 'right' }} />
                {fieldErr('phone') && <span className="form-error">{errors.phone}</span>}
              </div>
              <div className="form-group">
                <label className="form-label">الشركة / الجهة *</label>
                <input className={`form-input ${fieldErr('company') ? 'error' : ''}`} value={form.company} onChange={e => handleChange('company', e.target.value)} onBlur={() => handleBlur('company')} placeholder="اسم الشركة أو الجهة" />
                {fieldErr('company') && <span className="form-error">{errors.company}</span>}
              </div>
              <div className="form-group">
                <label className="form-label">المسمى الوظيفي *</label>
                <input className={`form-input ${fieldErr('jobTitle') ? 'error' : ''}`} value={form.jobTitle} onChange={e => handleChange('jobTitle', e.target.value)} onBlur={() => handleBlur('jobTitle')} placeholder="مثال: مدير التطوير" />
                {fieldErr('jobTitle') && <span className="form-error">{errors.jobTitle}</span>}
              </div>
              <div className="form-group">
                <label className="form-label">المدينة *</label>
                <input className={`form-input ${fieldErr('city') ? 'error' : ''}`} value={form.city} onChange={e => handleChange('city', e.target.value)} onBlur={() => handleBlur('city')} placeholder="مثال: جدة" />
                {fieldErr('city') && <span className="form-error">{errors.city}</span>}
              </div>
              <div className="form-group full">
                <label className="form-label">مجال الاهتمام *</label>
                <select className={`form-select ${fieldErr('interest') ? 'error' : ''}`} value={form.interest} onChange={e => handleChange('interest', e.target.value)} onBlur={() => handleBlur('interest')}>
                  <option value="">اختر مجال الاهتمام</option>
                  {INTERESTS.map(i => <option key={i} value={i}>{i}</option>)}
                </select>
                {fieldErr('interest') && <span className="form-error">{errors.interest}</span>}
              </div>
              <div className="form-group full">
                <label className="form-label">ما نوع الفرصة التي تبحث عنها؟</label>
                <textarea className="form-textarea" value={form.opportunityType} onChange={e => handleChange('opportunityType', e.target.value)} placeholder="مثال: امتياز غذائي، شراكات خدمات تشغيل، توسيع علامة تجارية..." />
              </div>
              <div className="form-group full">
                <p style={{ fontSize: 13, color: 'var(--text-40)', marginBottom: 12 }}>
                  سيتم ربط تسجيلك بفعالية iFOE داخل نظام الحضور والبطاقات الرقمية.
                </p>
                <button className="form-submit" type="submit" disabled={submitting}>
                  {submitting ? <><div className="spinner"></div><span>جاري التسجيل...</span></> : 'تسجيل واستلام بطاقة الحضور'}
                </button>
              </div>
                {otpVisible && (
                  <div className="form-group full" style={{ borderTop: '1px dashed var(--text-15)', paddingTop: 16 }}>
                    <label className="form-label">رمز التحقق المرسل للبريد</label>
                    <input className="form-input" value={otp} onChange={e => setOtp(e.target.value)} placeholder="000000" inputMode="numeric" style={{ direction: 'ltr', textAlign: 'right' }} />
                    <button className="form-submit" type="button" onClick={verifyOtp} disabled={submitting} style={{ marginTop: 12 }}>
                      تأكيد الرمز وإصدار البطاقة
                    </button>
                  </div>
                )}
                {status && (
                  <div className="form-group full">
                    <p style={{ margin: 0, padding: 12, borderRadius: 12, fontSize: 13, fontWeight: 700, color: statusType === 'err' ? 'var(--error)' : 'var(--success)', background: statusType === 'err' ? 'rgba(229,77,77,0.10)' : 'rgba(77,174,110,0.10)' }}>{status}</p>
                  </div>
                )}
            </div>
          </form>

          <aside className="form-info">
            <div className="info-logo-wrap">iFOE</div>
            <h3 className="info-title">نموذج تسجيل iFOE</h3>
            <p className="info-desc">هذا النموذج مخصص للزوار والعارضين في معرض فرص الامتياز التجاري الدولي. سيتم حفظ التسجيل داخل نظام الحضور والبطاقات.</p>
            <div className="info-row">
              <span className="info-row-label">المعرض</span>
              <span className="info-row-value">iFOE 2026</span>
            </div>
            <div className="info-row">
              <span className="info-row-label">المدينة</span>
              <span className="info-row-value">Jeddah</span>
            </div>
            <div className="info-row">
              <span className="info-row-label">البطاقة</span>
              <span className="info-row-value">QR Check-in</span>
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
}

/* ===== ANIMATED COUNTER ===== */
function AnimatedCounter({ end, suffix = '' }) {
  const [count, setCount] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !started.current) {
        started.current = true;
        const dur = 2000;
        const start = performance.now();
        const step = (now) => {
          const p = Math.min((now - start) / dur, 1);
          const ease = 1 - Math.pow(1 - p, 3);
          setCount(Math.round(ease * end));
          if (p < 1) requestAnimationFrame(step);
        };
        requestAnimationFrame(step);
      }
    }, { threshold: 0.3 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [end]);

  return <span ref={ref}>{count.toLocaleString('en-US')}{suffix}</span>;
}

/* ===== STATS ===== */
function StatsSection() {
  const [ref, inView] = useInView();
  const stats = [
    { number: 20, label: 'دولة مشاركة' },
    { number: 230, label: 'علامة تجارية' },
    { number: 11000, label: 'زائر ومستثمر' },
    { number: 300, label: 'اتفاقية فرنشايز' },
    { number: 12, label: 'جلسة حوارية متخصصة' },
    { number: 250, label: 'مليون ريال حجم الاتفاقيات' },
  ];

  return (
    <section className="section stats-section" id="stats" ref={ref}>
      <div className={`section-inner reveal ${inView ? 'in-view' : ''}`} style={{ textAlign: 'center' }}>
        <div className="stats-badge">أرقام النسخة الثالثة 2025</div>
        <h2 className="section-title">أرقام تتحدث عن نفسها</h2>
        <div className="stats-grid">
          {stats.map((s, i) => (
            <div className="stat-cell" key={i}>
              <div className="stat-number">
                {inView ? <AnimatedCounter end={s.number} /> : '0'}
              </div>
              <div className="stat-label">{s.label}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ===== GALLERY ===== */
function useIfoeGallery() {
  const [gallery, setGallery] = useState({ items: [], hero: null });
  useEffect(() => {
    let alive = true;
    fetch('/api/ifoe/gallery', { cache: 'no-store' })
      .then(res => res.ok ? res.json() : Promise.reject(new Error('gallery')))
      .then(data => { if (alive) setGallery({ items: data.items || [], hero: data.hero || null }); })
      .catch(() => { if (alive) setGallery({ items: [], hero: null }); });
    return () => { alive = false; };
  }, []);
  return gallery;
}

function GallerySection() {
  const [ref, inView] = useInView();
  const gallery = useIfoeGallery();
  const fallbackMedia = [
    { kind: 'video', title: 'لمحات من معرض iFOE', description: 'لقطات مختارة من أجواء المعرض والحضور واللقاءات.', badge: 'iFOE', src: '/uploads/ifoe-gallery/ifoe-last-version-clean-muted.mp4', poster: '/uploads/ifoe-gallery/ifoe-last-version-poster.jpg', muted: true, featured: true, visible: true },
  ];
  const media = (gallery.items && gallery.items.length ? gallery.items : fallbackMedia).filter(item => item.visible !== false && !item.hero);

  const renderCard = (item, i) => {
    const isVideo = item.kind === 'video';
    const title = item.title || (isVideo ? 'فيديو من iFOE' : 'صورة من iFOE');
    const inner = (
      <>
        <div className="media-thumb">
          {isVideo ? (
            <video src={item.src} poster={item.poster || '/uploads/ifoe-gallery/ifoe-last-version-poster.jpg'} muted={item.muted !== false} controls playsInline preload="metadata" />
          ) : (
            <img src={item.src || item.poster} alt={title} loading="lazy" />
          )}
        </div>
        <div className="media-content">
          <h3 className="media-title">{title}</h3>
          <p className="media-desc">{item.description || 'محتوى مختار من النسخ السابقة والنسخة الأخيرة للمعرض.'}</p>
          <div className="media-meta">
            <span>{isVideo ? 'فيديو' : 'صورة'}</span>
            <span>{item.badge || 'iFOE'}</span>
          </div>
        </div>
      </>
    );
    const className = `media-card ${item.featured || i === 0 ? 'featured' : ''} ${isVideo ? 'media-video' : 'media-photo'}`;
    return <article className={className} key={item.id || i}>{inner}</article>;
  };

  return (
    <section className="section gallery-section" id="gallery" ref={ref}>
      <div className={`section-inner reveal ${inView ? 'in-view' : ''}`} style={{ textAlign: 'center' }}>
        <div className="gallery-kicker">من آخر نسخة والنسخ السابقة</div>
        <h2 className="section-title">معرض الصور والفيديوهات</h2>
        <p className="section-subtitle">لقطات مختارة من أجواء المعرض والنسخ السابقة.</p>
        <div className="gallery-grid">{media.map(renderCard)}</div>
      </div>
    </section>
  );
}

/* ===== ABOUT ===== */
function AboutSection() {
  const [ref, inView] = useInView();
  const benefits = [
    { icon: 'handshake', title: 'تواصل وشراكات', desc: 'لقاءات مباشرة مع أصحاب الامتيازات التجارية والمستثمرين.' },
    { icon: 'chart', title: 'فرص استثمارية', desc: 'اكتشاف فرص في الأغذية، التجزئة، التعليم، الصحة، التقنية وغيرها.' },
    { icon: 'users', title: 'جلسات وورش', desc: 'محتوى تدريبي حول الاتجاهات والاستراتيجيات في الامتياز التجاري.' },
    { icon: 'megaphone', title: 'وعي بالعلامة', desc: 'منصة لعرض العلامات التجارية أمام جمهور مهتم بالنمو والتوسع.' },
  ];
  const sectors = [
    'الأغذية والمقاهي', 'التجزئة', 'التعليم والتدريب', 'الصحة والتجميل',
    'التقنية', 'الخدمات المالية', 'التشغيل والصيانة', 'الاستشارات'
  ];

  return (
    <section className="section about-section" id="about" ref={ref}>
      <div className={`section-inner reveal ${inView ? 'in-view' : ''}`}>
        <h2 className="section-title">عن المعرض</h2>
        <p className="about-text">
          يعتبر معرض فرص الامتياز التجاري الدولي منصة دولية رائدة تجمع الشركات ورواد الأعمال والمستثمرين الباحثين عن فرص الامتياز التجاري محلياً ودولياً. يعود المعرض بنسخته الرابعة في عام 2026 ليؤكد مكانته كحدث استثماري بارز يعكس تطلعات المملكة الاقتصادية وتعزيز بيئة الأعمال بما يتماشى مع رؤية المملكة 2030.
        </p>

        <div className="benefits-grid">
          {benefits.map((b, i) => (
            <div className="benefit-card" key={i}>
              <div className="benefit-icon">
                <Icon name={b.icon} size={22} color="var(--accent-light)" />
              </div>
              <h3 className="benefit-title">{b.title}</h3>
              <p className="benefit-desc">{b.desc}</p>
            </div>
          ))}
        </div>

        <h3 className="sectors-title">القطاعات المشاركة</h3>
        <div className="sectors-wrap">
          {sectors.map(s => <span className="sector-tag" key={s}>{s}</span>)}
        </div>
      </div>
    </section>
  );
}

/* ===== CTA STRIP ===== */
function CTAStrip() {
  return (
    <section className="cta-strip">
      <div className="cta-strip-inner">
        <h2 className="cta-strip-title">ابدأ توسعك من هنا... وكن جزءاً من أقوى تجمع للفرنشايز في المملكة</h2>
        <a href="#register" className="cta-strip-btn">سجل حضورك الآن</a>
      </div>
    </section>
  );
}

/* ===== FOOTER ===== */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-links">
          <a className="footer-link" href="#" target="_blank" rel="noreferrer">
            <Icon name="web" size={16} color="var(--text-40)" />
            IFOE 2026
          </a>
          <a className="footer-link" href="mailto:info@ifoe.sa">
            <Icon name="email" size={16} color="var(--text-40)" />
            info@ifoe.sa
          </a>
          <a className="footer-link" href="mailto:albatool@event-maker.sa">
            <Icon name="email" size={16} color="var(--text-40)" />
            albatool@event-maker.sa
          </a>
          <a className="footer-link" href="tel:0565414847">
            <Icon name="phone" size={16} color="var(--text-40)" />
            0565414847
          </a>
        </div>
        <div className="footer-links">
          <a className="footer-link" href="#" style={{ direction: 'rtl' }}>
            جميع الحقوق محفوظة لمعرض فرص الامتياز التجاري الدولي
          </a>
        </div>
      </div>
    </footer>
  );
}

/* ===== APP ===== */
function FastSignupIntro() {
  return (
    <section className="fast-signup-intro">
      <div className="section-inner" style={{ textAlign: 'center' }}>
        <div className="gallery-kicker">رابط التسجيل السريع</div>
        <h1 className="section-title">تسجيل زائر أو عارض في iFOE 2026</h1>
        <p className="section-subtitle">هذه الصفحة مختصرة للتسجيل السريع ومشاركة الرابط مباشرة مع الضيوف.</p>
      </div>
    </section>
  );
}

function App() {
  const gallery = useIfoeGallery();
  const path = window.location.pathname.toLowerCase();
  const isFastSignup = path.includes('/signup') || path.includes('/register');
  if (isFastSignup) {
    return (
      <>
        <InteractiveBg />
        <Navbar />
        <main>
          <FastSignupIntro />
          <RegistrationSection />
        </main>
        <Footer />
      </>
    );
  }
  return (
    <>
      <InteractiveBg />
      <Navbar />
      <main>
        <Hero heroVideo={gallery.hero} />
        <EventInfoBar />
        <StatsSection />
        <GallerySection />
        <AboutSection />
        <CTAStrip />
        <RegistrationSection />
      </main>
      <Footer />
    </>
  );
}

ReactDOM.createRoot
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
