/* global React */
const { useState, useEffect, useRef, useCallback } = React;

// =======================================================================
//  COPY DATA (single source of truth — also used by the booking flow)
// =======================================================================

const COPY = {
  en: {
    nav: { treatments: 'Treatments', experts: 'Experts', about: 'About', location: 'The Opus', contact: 'Contact', book: 'Book a Consultation' },
    tagline: 'The Home of Mindful Aesthetics',
    values: 'Ethical · Sustainable · Personal',
    address1: 'The Opus by Omniyat',
    address2: 'Unit C201, Al A’amal Street',
    address3: 'Business Bay, Dubai, UAE',
    phone: '+971 4 456 2024',
    whatsapp: '+971 58 685 8562',
    email: 'dubai@ouronyx.com',
    direction: 'ltr',
  },
  ar: {
    nav: { treatments: 'علاجات', experts: 'خبراؤنا', about: 'عن أورونيكس', location: 'أوبس', contact: 'اتصل', book: 'احجز استشارة' },
    tagline: 'دار جماليات الوعي',
    values: 'أخلاقي · مستدام · شخصي',
    address1: 'أوبس بواسطة أومنيات',
    address2: 'الوحدة C201، شارع الأمل',
    address3: 'الخليج التجاري، دبي',
    phone: '+971 4 456 2024',
    whatsapp: '+971 58 685 8562',
    email: 'dubai@ouronyx.com',
    direction: 'rtl',
  },
};

// =======================================================================
//  Phi mark — original interpretation, NOT the proprietary logo
//  (the Greek letter phi rendered in our serif type system)
// =======================================================================

function PhiMark({ size = 28, color }) {
  const px = typeof size === 'number' ? `${size}px` : size;
  return (
    <span
      className="phi-mark"
      style={{
        fontSize: px,
        color: color || 'var(--champagne)',
        fontFamily: 'Cormorant Garamond, serif',
        fontWeight: 300,
        fontStyle: 'italic',
        letterSpacing: 0,
        display: 'inline-block',
        lineHeight: 1,
      }}
    >
      φ
    </span>
  );
}

function Wordmark({ size = 18, color }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: color || 'var(--ink)' }}>
      <PhiMark size={size + 14} color="var(--champagne)" />
      <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1 }}>
        <span style={{
          fontFamily: 'var(--serif)', fontSize: size, letterSpacing: '0.28em',
          fontWeight: 400, textTransform: 'uppercase',
        }}>OURONYX</span>
        <span style={{
          fontFamily: 'var(--mono)', fontSize: size * 0.42, letterSpacing: '0.32em',
          marginTop: 4, color: 'var(--muted)',
        }}>DUBAI</span>
      </div>
    </div>
  );
}

// =======================================================================
//  Scroll-reveal wrapper using IntersectionObserver
// =======================================================================

function Reveal({ children, delay = 0, className = '', as: As = 'div', ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) { setShown(true); io.disconnect(); } }),
      { threshold: 0.08 }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <As ref={ref} className={`reveal ${shown ? 'in' : ''} ${className}`} style={{ '--delay': `${delay}ms` }} {...rest}>
      {children}
    </As>
  );
}

// =======================================================================
//  Top Nav with sticky behavior + Treatments mega-menu
// =======================================================================

function Nav({ route, onNav, onBook, locale, onLocale, dark, onDarkToggle }) {
  const [scrolled, setScrolled] = useState(false);
  const [mega, setMega] = useState(false);
  const t = COPY[locale];

  useEffect(() => {
    const onScroll = () => {
      const el = document.querySelector('.app-scroll');
      const top = el ? el.scrollTop : window.scrollY;
      setScrolled(top > 30);
    };
    const el = document.querySelector('.app-scroll');
    if (el) el.addEventListener('scroll', onScroll);
    else window.addEventListener('scroll', onScroll);
    return () => {
      if (el) el.removeEventListener('scroll', onScroll);
      else window.removeEventListener('scroll', onScroll);
    };
  }, []);

  const link = (key, label) => (
    <button
      className={`nav-link ${route === key || (key === 'treatments' && route.startsWith('treatment')) ? 'active' : ''}`}
      onClick={() => onNav(key)}
      onMouseEnter={() => setMega(key === 'treatments')}
      onMouseLeave={() => setMega(false)}
    >
      {label}
    </button>
  );

  return (
    <header
      style={{
        position: 'sticky', top: 0, zIndex: 50,
        background: scrolled ? 'var(--bone)' : 'transparent',
        borderBottom: scrolled ? '1px solid var(--line)' : '1px solid transparent',
        backdropFilter: scrolled ? 'blur(8px)' : 'none',
        transition: 'background 0.3s, border-color 0.3s',
      }}
      onMouseLeave={() => setMega(false)}
    >
      <div className="container-wide" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: scrolled ? '14px 32px' : '22px 32px',
        transition: 'padding 0.3s',
      }}>
        <button onClick={() => onNav('home')} style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer' }}>
          <Wordmark size={14} />
        </button>

        <nav style={{ display: 'flex', alignItems: 'center', gap: 36 }}>
          {link('treatments', t.nav.treatments)}
          {link('experts', t.nav.experts)}
          {link('about', t.nav.about)}
          {link('location', t.nav.location)}
          {link('contact', t.nav.contact)}
        </nav>

        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          {/* Locale switcher */}
          <div style={{ display: 'flex', gap: 4, fontFamily: 'var(--mono)', fontSize: '0.7rem', letterSpacing: '0.18em', textTransform: 'uppercase' }}>
            {['en','ar'].map((l, i) => (
              <React.Fragment key={l}>
                {i > 0 && <span style={{ color: 'var(--muted)' }}>/</span>}
                <button onClick={() => onLocale(l)} style={{
                  background: 'none', border: 0, padding: '4px 2px', cursor: 'pointer',
                  color: locale === l ? 'var(--ink)' : 'var(--muted)',
                  fontFamily: 'inherit', fontSize: 'inherit', letterSpacing: 'inherit',
                  textDecoration: locale === l ? 'underline' : 'none',
                  textUnderlineOffset: 4,
                }}>{l}</button>
              </React.Fragment>
            ))}
          </div>
          {/* Dark toggle */}
          <button onClick={onDarkToggle} title="Toggle editorial mode" style={{
            background: 'none', border: '1px solid var(--line)', cursor: 'pointer',
            width: 32, height: 32, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--ink-soft)',
          }}>
            {dark ? (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
            ) : (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"/></svg>
            )}
          </button>
          <button className="btn btn-olive" onClick={onBook} style={{ padding: '12px 22px' }}>
            {t.nav.book}
          </button>
        </div>
      </div>

      {/* Treatments mega-menu */}
      <div
        className={`megamenu ${mega ? 'open' : ''}`}
        onMouseEnter={() => setMega(true)}
        onMouseLeave={() => setMega(false)}
      >
        <div className="container-wide" style={{ padding: '40px 32px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 36 }}>
          {[
            { id: 'skin-quality', label: locale === 'ar' ? 'جودة البشرة' : 'Skin Quality',
              sub: locale === 'ar' ? 'علاج العلامات المبكرة، صحة وإشراق البشرة' : 'Early signs, skin health, luminosity',
              kinds: ['Biostimulators','Energy-based therapies','Wrinkle relaxation','HA injectables'] },
            { id: 'facial-structure', label: locale === 'ar' ? 'بنية الوجه' : 'Facial Structure',
              sub: locale === 'ar' ? 'استعادة التوازن الطبيعي للوجه' : 'Restoring proportion, natural results',
              kinds: ['Structural support','Volume restoration','Contour balance','Profile harmony'] },
            { id: 'hair-restoration', label: locale === 'ar' ? 'إستعادة الشعر' : 'Hair Restoration',
              sub: locale === 'ar' ? 'صحة فروة الرأس بنهج علمي' : 'Scalp health, science-led non-surgical plans',
              kinds: ['Diagnostic mapping','Scalp therapy','Density support','Maintenance'] },
          ].map((p) => (
            <button
              key={p.id}
              onClick={() => { setMega(false); onNav('treatment:' + p.id); }}
              style={{ background: 'none', border: 0, textAlign: 'left', padding: 0, cursor: 'pointer', color: 'var(--ink)' }}
            >
              <div className="eyebrow" style={{ marginBottom: 12 }}>{p.id.replace('-', ' · ')}</div>
              <h3 className="serif" style={{ fontSize: '2rem', lineHeight: 1.05, marginBottom: 8 }}>{p.label}</h3>
              <p style={{ color: 'var(--ink-soft)', fontSize: '0.92rem', marginBottom: 16 }}>{p.sub}</p>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
                {p.kinds.map((k) => (
                  <li key={k} style={{ fontSize: '0.85rem', color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 16, height: 1, background: 'var(--champagne)' }} />
                    {k}
                  </li>
                ))}
              </ul>
            </button>
          ))}
        </div>
      </div>
    </header>
  );
}

// =======================================================================
//  Footer
// =======================================================================

function Footer({ locale, onNav }) {
  const t = COPY[locale];
  const ar = locale === 'ar';
  return (
    <footer style={{ background: 'var(--onyx)', color: 'var(--bone)', marginTop: 0 }}>
      <div className="container-wide" style={{ padding: '80px 32px 40px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 48, marginBottom: 64 }}>
          <div>
            <Wordmark size={14} color="var(--bone)" />
            <p style={{ marginTop: 28, color: 'rgba(242,237,227,0.65)', fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: '1.25rem', lineHeight: 1.4 }}>
              “{t.tagline}”
            </p>
            <div className="mono" style={{ marginTop: 16, color: 'rgba(242,237,227,0.55)' }}>{t.values}</div>
          </div>

          <div>
            <div className="mono" style={{ marginBottom: 18, color: 'rgba(242,237,227,0.5)' }}>{ar ? 'تصفح' : 'Explore'}</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                ['treatments', t.nav.treatments],
                ['experts', t.nav.experts],
                ['about', t.nav.about],
                ['location', t.nav.location],
                ['contact', t.nav.contact],
              ].map(([k, v]) => (
                <li key={k}>
                  <button onClick={() => onNav(k)} style={{
                    background: 'none', border: 0, padding: 0, cursor: 'pointer',
                    color: 'rgba(242,237,227,0.85)', fontSize: '0.92rem', textAlign: 'inherit', fontFamily: 'inherit',
                  }}>{v}</button>
                </li>
              ))}
            </ul>
          </div>

          <div>
            <div className="mono" style={{ marginBottom: 18, color: 'rgba(242,237,227,0.5)' }}>{ar ? 'تواصل' : 'Contact'}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: '0.92rem', color: 'rgba(242,237,227,0.85)' }}>
              <a href={`tel:${t.phone.replace(/\s/g,'')}`} style={{ color: 'inherit', textDecoration: 'none' }}>{t.phone}</a>
              <a href={`https://wa.me/${t.whatsapp.replace(/\D/g,'')}`} style={{ color: 'inherit', textDecoration: 'none' }}>WhatsApp {t.whatsapp}</a>
              <a href={`mailto:${t.email}`} style={{ color: 'inherit', textDecoration: 'none' }}>{t.email}</a>
            </div>
          </div>

          <div>
            <div className="mono" style={{ marginBottom: 18, color: 'rgba(242,237,227,0.5)' }}>{ar ? 'العنوان' : 'Address'}</div>
            <div style={{ fontSize: '0.92rem', color: 'rgba(242,237,227,0.85)', lineHeight: 1.7 }}>
              {t.address1}<br/>
              {t.address2}<br/>
              {t.address3}
            </div>
            <div className="mono" style={{ marginTop: 18, color: 'rgba(242,237,227,0.5)', fontSize: '0.62rem' }}>
              DHA Polyclinic Licence · To verify
            </div>
          </div>
        </div>

        <div style={{ borderTop: '1px solid rgba(242,237,227,0.12)', paddingTop: 28, display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '0.74rem', color: 'rgba(242,237,227,0.5)', fontFamily: 'var(--mono)', letterSpacing: '0.12em' }}>
          <span>© OURONYX DUBAI · NON-SURGICAL FACIAL AESTHETICS</span>
          <span>{ar ? 'متوافق مع دائرة الصحة بدبي' : 'DHA/MOH COMPLIANT · NO GUARANTEED RESULTS · BY CONSULTATION'}</span>
        </div>
      </div>
    </footer>
  );
}

// =======================================================================
//  Floating CTAs: WhatsApp / Call buttons (bottom-right)
// =======================================================================

function FloatingCTAs() {
  return (
    <div style={{
      position: 'fixed', bottom: 24, right: 24, zIndex: 40,
      display: 'flex', flexDirection: 'column', gap: 10,
    }}>
      <a href="https://wa.me/971586858562" title="WhatsApp" style={{
        width: 52, height: 52, borderRadius: '50%', background: 'var(--olive)', color: 'var(--bone)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 8px 24px rgba(0,0,0,0.18)', textDecoration: 'none',
      }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.8 1-.2.2-.3.2-.5.1-1.3-.6-2.4-1.4-3.4-2.9-.3-.4.3-.4.8-1.3.1-.2 0-.3-.1-.5L9.4 8c-.2-.4-.4-.4-.5-.4h-.5c-.2 0-.5.1-.7.3-.3.3-1 1-1 2.5s1 2.9 1.1 3.1c.1.2 2.1 3.2 5.1 4.5 1.9.8 2.6.9 3.5.7.6-.1 1.7-.7 1.9-1.3.2-.7.2-1.3.2-1.4-.1-.2-.3-.3-.5-.4M12 21c-1.6 0-3.2-.4-4.6-1.2L3 21l1.3-4.2C3.4 15.3 3 13.7 3 12c0-5 4-9 9-9s9 4 9 9-4 9-9 9m0-19.5C5.5 1.5 0 6.5 0 12c0 1.9.5 3.8 1.4 5.4L0 24l6.8-1.4c1.6.8 3.4 1.2 5.2 1.2 6.6 0 12-5.4 12-12s-5.4-12-12-12"/></svg>
      </a>
      <a href="tel:+97144562024" title="Call" style={{
        width: 52, height: 52, borderRadius: '50%', background: 'var(--ink)', color: 'var(--bone)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 8px 24px rgba(0,0,0,0.18)', textDecoration: 'none',
      }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.95.37 1.88.72 2.77a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.31-1.31a2 2 0 0 1 2.11-.45c.89.35 1.82.59 2.77.72A2 2 0 0 1 22 16.92Z"/></svg>
      </a>
    </div>
  );
}

// =======================================================================
//  Architectural arch SVG — echoes The Opus's curved steel structure
// =======================================================================

function ArchPattern({ color = 'currentColor', opacity = 0.3 }) {
  return (
    <svg viewBox="0 0 400 200" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity }}>
      <path d="M -20 200 Q 100 -20 200 50 T 420 200" fill="none" stroke={color} strokeWidth="0.5"/>
      <path d="M -20 200 Q 120 20 200 80 T 420 200" fill="none" stroke={color} strokeWidth="0.5"/>
      <path d="M -20 200 Q 140 60 200 110 T 420 200" fill="none" stroke={color} strokeWidth="0.5"/>
      <path d="M -20 200 Q 160 100 200 140 T 420 200" fill="none" stroke={color} strokeWidth="0.5"/>
    </svg>
  );
}

// Export
Object.assign(window, { COPY, PhiMark, Wordmark, Reveal, Nav, Footer, FloatingCTAs, ArchPattern });
