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: 'About' },
    { href: '#stats', label: 'Numbers' },
    { href: '#gallery', label: 'Gallery' },
    { href: 'https://ifoe-ksa.com/', label: 'العربية', lang: 'ar', dir: 'rtl' },
    { href: '#register', label: 'Register now', 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">Register now</a>
          <button className="nav-burger" type="button" aria-label="Open menu" 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="Site menu">
        <div className="mobile-menu-head"><span>Site menu</span><button type="button" aria-label="Close menu" 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 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 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">4th Edition</div>
        <h1 className="hero-title">International Franchise Opportunities Exhibition - iFOE</h1>
        <p className="hero-subtitle">Saudi Arabia’s leading franchise opportunities exhibition</p>
        <div className="hero-features">
          <div className="hero-feature"><span className="dot"></span>Local and international growth</div>
          <div className="hero-feature"><span className="dot"></span>Direct business networking</div>
          <div className="hero-feature"><span className="dot"></span>Real partnership opportunities</div>
        </div>
        <a href="#register" className="hero-cta">Register your attendance</a>
        <a href="/en/signup" className="hero-quick-link">Quick registration link</a>
      </div>
    </section>
  );
}

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>Jeddah Center for Exhibitions and Events</span></div>
      <div className="event-bar-item"><div className="event-bar-icon"><Icon name="calendar" size={18} color="var(--accent-light)" /></div><span>3–5 September 2026</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>
  );
}

const INTERESTS = ['Food, cafés and restaurants','Retail','Education and training','Health and beauty','Technology','Financial services','Operations and maintenance','Consulting','Other'];
const PARTICIPANT_TYPES = [{ value:'visitor', label:'Visitor' }, { value:'exhibitor', label:'Exhibitor' }];
function validateForm(d) {
  const e = {};
  if (!d.participantType) e.participantType = 'Choose registration type';
  if (!d.fullName.trim()) e.fullName = 'Full name is required';
  if (!/^\S+@\S+\.\S+$/.test(d.email)) e.email = 'Enter a valid email';
  if (!d.phone.trim()) e.phone = 'Mobile number is required';
  if (!d.company.trim()) e.company = 'Company is required';
  if (!d.jobTitle.trim()) e.jobTitle = 'Job title is required';
  if (!d.city.trim()) e.city = 'City is required';
  if (!d.interest) e.interest = 'Choose an area of interest';
  return e;
}

function RegistrationSection() {
  const [ref, inView] = useInView();
  const [form, setForm] = useState({ participantType:'visitor', fullName: '', email: '', phone: '', company: '', jobTitle: '', city: '', interest: '', opportunityType: '' });
  const [touched, setTouched] = useState({});
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [status, setStatus] = useState('');
  const [statusType, setStatusType] = useState('ok');
  const [otpVisible, setOtpVisible] = useState(false);
  const [otp, setOtp] = useState('');
  const [submitted, setSubmitted] = useState(false);
  const [currentUid, setCurrentUid] = useState('');
  const setField = (k, v) => { const n = { ...form, [k]: v }; setForm(n); if (touched[k]) setErrors(validateForm(n)); };
  const blur = k => { setTouched({ ...touched, [k]: true }); setErrors(validateForm(form)); };
  const fieldErr = k => touched[k] && errors[k];
  const card = uid => '/card?uid=' + encodeURIComponent(uid) + '&event=ifoe';
  async function submit(e) {
    e.preventDefault();
    const v = validateForm(form); setErrors(v); setTouched(Object.keys(form).reduce((a,k)=>({ ...a, [k]: true }), {}));
    if (Object.keys(v).length) return;
    setSubmitting(true); setStatus('Submitting registration...'); setStatusType('ok');
    try {
      const fd = new FormData();
      fd.set('event','ifoe'); fd.set('gender',''); fd.set('participantType',form.participantType); fd.set('name',form.fullName); fd.set('email',form.email); fd.set('phone',form.phone);
      fd.set('company',form.company); fd.set('jobTitle',form.jobTitle); fd.set('city',form.city); fd.set('sector',form.interest); fd.set('interest',form.opportunityType || form.interest);
      const res = await fetch('/api/guest/signup', { method:'POST', body: fd });
      const data = await res.json().catch(()=>({}));
      if (!res.ok) throw new Error(data.error || 'Registration failed');
      setCurrentUid(data.uid || '');
      if (data.canSendOtp) {
        const otpRes = await fetch('/api/guest/request-otp', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ email: form.email, channel:'email', event:'ifoe' }) });
        const otpData = await otpRes.json().catch(()=>({}));
        if (!otpRes.ok) throw new Error(otpData.error || 'Could not send verification code');
        setOtpVisible(true); setStatus('A verification code was sent to your email. Enter it to complete registration.'); setStatusType('ok');
      } else {
        setSubmitted(true); setStatus('Registration completed. Opening your attendance card...'); setStatusType('ok'); if (data.uid) setTimeout(()=>location.href=card(data.uid), 900);
      }
    } catch (err) { setStatus(err.message || 'Registration failed'); setStatusType('err'); }
    finally { setSubmitting(false); }
  }
  async function verifyOtp() {
    if (!otp.trim()) { setStatus('Enter the verification code'); setStatusType('err'); return; }
    setSubmitting(true); setStatus('Verifying code...'); setStatusType('ok');
    try {
      const res = await fetch('/api/guest/verify-otp', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ email: form.email, code: otp, channel:'email', event:'ifoe' }) });
      const data = await res.json().catch(()=>({})); if (!res.ok) throw new Error(data.error || 'Verification failed');
      const uid = data.uid || currentUid; setSubmitted(true); setStatus('Email verified. Opening your attendance card...'); setStatusType('ok'); if (uid) setTimeout(()=>location.href=card(uid), 900);
    } catch(err) { setStatus(err.message || 'Verification failed'); setStatusType('err'); }
    finally { setSubmitting(false); }
  }
  if (submitted) return (
    <section className="section register-section" id="register"><div className="section-inner"><div className="success-card"><div className="success-icon"><Icon name="check" size={34} color="#fff" /></div><h2>Registration received</h2><p>Your attendance card will open automatically. If it does not open, check your email or try again.</p><button className="hero-cta" onClick={()=>setSubmitted(false)}>Register another visitor/exhibitor</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">Register as a visitor or exhibitor</h2>
        <p className="section-subtitle">Choose your registration type, then verify your email to receive your digital attendance card.</p>
        <div className="register-grid">
          <form className="register-form" onSubmit={submit}>
            <div className="form-grid">
              <div className="form-group full"><label className="form-label">Registration type *</label><select className={`form-select ${fieldErr('participantType') ? 'error' : ''}`} value={form.participantType} onChange={e=>setField('participantType', e.target.value)} onBlur={()=>blur('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">Full name *</label><input className={`form-input ${fieldErr('fullName') ? 'error' : ''}`} value={form.fullName} onChange={e=>setField('fullName', e.target.value)} onBlur={()=>blur('fullName')} placeholder="Enter your full name" />{fieldErr('fullName') && <span className="form-error">{errors.fullName}</span>}</div>
              <div className="form-group"><label className="form-label">Email *</label><input className={`form-input ${fieldErr('email') ? 'error' : ''}`} type="email" value={form.email} onChange={e=>setField('email', e.target.value)} onBlur={()=>blur('email')} placeholder="example@email.com" />{fieldErr('email') && <span className="form-error">{errors.email}</span>}</div>
              <div className="form-group"><label className="form-label">Mobile number *</label><input className={`form-input ${fieldErr('phone') ? 'error' : ''}`} value={form.phone} onChange={e=>setField('phone', e.target.value)} onBlur={()=>blur('phone')} placeholder="05xxxxxxxx" />{fieldErr('phone') && <span className="form-error">{errors.phone}</span>}</div>
              <div className="form-group"><label className="form-label">Company / organization *</label><input className={`form-input ${fieldErr('company') ? 'error' : ''}`} value={form.company} onChange={e=>setField('company', e.target.value)} onBlur={()=>blur('company')} placeholder="Company name" />{fieldErr('company') && <span className="form-error">{errors.company}</span>}</div>
              <div className="form-group"><label className="form-label">Job title *</label><input className={`form-input ${fieldErr('jobTitle') ? 'error' : ''}`} value={form.jobTitle} onChange={e=>setField('jobTitle', e.target.value)} onBlur={()=>blur('jobTitle')} placeholder="e.g. Development Manager" />{fieldErr('jobTitle') && <span className="form-error">{errors.jobTitle}</span>}</div>
              <div className="form-group"><label className="form-label">City *</label><input className={`form-input ${fieldErr('city') ? 'error' : ''}`} value={form.city} onChange={e=>setField('city', e.target.value)} onBlur={()=>blur('city')} placeholder="e.g. Jeddah" />{fieldErr('city') && <span className="form-error">{errors.city}</span>}</div>
              <div className="form-group full"><label className="form-label">Area of interest *</label><select className={`form-select ${fieldErr('interest') ? 'error' : ''}`} value={form.interest} onChange={e=>setField('interest', e.target.value)} onBlur={()=>blur('interest')}><option value="">Choose an area</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">What kind of opportunity are you looking for?</label><textarea className="form-textarea" value={form.opportunityType} onChange={e=>setField('opportunityType', e.target.value)} placeholder="Example: food franchise, services partnership, brand expansion..." /></div>
              <div className="form-group full"><p style={{ fontSize: 13, color: 'var(--text-40)', marginBottom: 12 }}>Your registration will be connected to the iFOE attendance and digital card system.</p><button className="form-submit" type="submit" disabled={submitting}>{submitting ? <><div className="spinner"></div><span>Submitting...</span></> : 'Register and receive attendance card'}</button></div>
              {otpVisible && <div className="form-group full" style={{ borderTop:'1px dashed var(--text-15)', paddingTop:16 }}><label className="form-label">Email verification code</label><input className="form-input" value={otp} onChange={e=>setOtp(e.target.value)} placeholder="000000" inputMode="numeric" /><button className="form-submit" type="button" onClick={verifyOtp} disabled={submitting} style={{ marginTop:12 }}>Verify code and issue card</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 registration form</h3><p className="info-desc">This form is for visitors and exhibitors of the International Franchise Opportunities Exhibition. Your registration is saved in the attendance and card system.</p><div className="info-row"><span className="info-row-label">Event</span><span className="info-row-value">iFOE 2026</span></div><div className="info-row"><span className="info-row-label">City</span><span className="info-row-value">Jeddah</span></div><div className="info-row"><span className="info-row-label">Card</span><span className="info-row-value">QR Check-in</span></div></aside>
        </div>
      </div>
    </section>
  );
}

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, start=performance.now(); const step=now=>{ const p=Math.min((now-start)/dur,1), ease=1-Math.pow(1-p,3); setCount(Math.round(ease*end)); if(p<1) requestAnimationFrame(step); }; requestAnimationFrame(step); } },{threshold:.3}); obs.observe(el); return()=>obs.disconnect(); }, [end]);
  return <span ref={ref}>{count.toLocaleString('en-US')}{suffix}</span>;
}
function StatsSection() {
  const [ref, inView] = useInView();
  const stats = [{number:20,label:'Participating countries'},{number:230,label:'Brands'},{number:11000,label:'Visitors and investors'},{number:300,label:'Franchise agreements'},{number:12,label:'Specialized sessions'},{number:250,label:'Million SAR agreement value'}];
  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">Third edition 2025 numbers</div><h2 className="section-title">Numbers that speak for themselves</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>;
}

function GallerySection() {
  const [ref, inView] = useInView(); const gallery=useIfoeGallery();
  const fallbackMedia=[{kind:'video',title:'Highlights from iFOE',description:'Selected moments from the exhibition, visitors and business networking.',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&&item.title.includes('iFOE')?item.title:'Highlights from iFOE'; return <article className={`media-card ${item.featured||i===0?'featured':''} ${isVideo?'media-video':'media-photo'}`} key={item.id||i}><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">{isVideo?'Selected moments from the exhibition, visitors and business networking.':(item.description||'Selected media from iFOE.')}</p><div className="media-meta"><span>{isVideo?'Video':'Image'}</span><span>iFOE</span></div></div></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">From the latest and previous editions</div><h2 className="section-title">Photo and video gallery</h2><p className="section-subtitle">Selected moments from the exhibition and previous editions.</p><div className="gallery-grid">{media.map(renderCard)}</div></div></section>;
}

function AboutSection() {
  const [ref, inView]=useInView();
  const benefits=[{icon:'handshake',title:'Networking and partnerships',desc:'Meet franchisors, investors and business owners directly.'},{icon:'chart',title:'Investment opportunities',desc:'Discover opportunities across food, retail, education, health, technology and services.'},{icon:'users',title:'Sessions and workshops',desc:'Practical content around franchising trends, strategy and expansion.'},{icon:'megaphone',title:'Brand exposure',desc:'A focused platform for brands seeking growth and new markets.'}];
  const sectors=['Food and cafés','Retail','Education and training','Health and beauty','Technology','Financial services','Operations and maintenance','Consulting'];
  return <section className="section about-section" id="about" ref={ref}><div className={`section-inner reveal ${inView?'in-view':''}`}><h2 className="section-title">About the exhibition</h2><p className="section-subtitle">The International Franchise Opportunities Exhibition is a leading platform connecting companies, entrepreneurs and investors looking for franchise opportunities locally and internationally. The fourth edition in 2026 reinforces its position as a major investment event aligned with Saudi Vision 2030.</p><div className="benefits-grid">{benefits.map(b=><div className="benefit-card" key={b.title}><div className="benefit-icon"><Icon name={b.icon} size={24} color="var(--accent-light)" /></div><h3>{b.title}</h3><p>{b.desc}</p></div>)}</div><h3 className="sectors-title">Participating sectors</h3><div className="sectors-wrap">{sectors.map(s=><span className="sector-tag" key={s}>{s}</span>)}</div></div></section>;
}
function CTAStrip(){ return <section className="cta-strip"><div className="cta-strip-inner"><h2 className="cta-strip-title">Start your expansion here and be part of Saudi Arabia’s strongest franchise gathering</h2><a href="#register" className="cta-strip-btn">Register now</a></div></section>; }
function Footer(){ return <footer className="footer"><div className="footer-inner"><div className="footer-links"><a className="footer-link" href="#"><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="/">العربية</a></div></div></footer>; }
function FastSignupIntro(){ return <section className="fast-signup-intro"><div className="section-inner" style={{textAlign:'center'}}><div className="gallery-kicker">Quick registration link</div><h1 className="section-title">Register as a visitor or exhibitor for iFOE 2026</h1><p className="section-subtitle">A short page for direct visitor and exhibitor registration.</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(document.getElementById('root')).render(<App />);
