// Couture Events Worldwide — App shell, routing, Nav, Home, Footer
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ────────────────────────────────────────────────────────────────
// Tweakable defaults
// ────────────────────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "ivory",
  "displayFont": "cormorant",
  "heroLayout": "cinematic",
  "showConsentStrip": true
}/*EDITMODE-END*/;

// Apply tweaks to DOM (palette & font)
function applyTweaks(t) {
  const root = document.documentElement;
  const palettes = {
    ivory: { paper: '#FBF8F3', ivory: '#F3EBDF', ink: '#1A1614', gold: '#B6924E', goldPale: '#D9C39A', line: '#E6DCCD' },
    noir:  { paper: '#F5F0E8', ivory: '#1A1614', ink: '#0F0C0B', gold: '#C9A86A', goldPale: '#D9C39A', line: '#2A2522' },
    sand:  { paper: '#F4ECDE', ivory: '#E8DDC8', ink: '#2A211B', gold: '#A87A3E', goldPale: '#CDA86E', line: '#D8C9AC' },
    pearl: { paper: '#F7F4ED', ivory: '#EBE4D5', ink: '#26201C', gold: '#7C6B4A', goldPale: '#B5A079', line: '#DDD2BD' },
  };
  const p = palettes[t.palette] || palettes.ivory;
  root.style.setProperty('--paper', p.paper);
  root.style.setProperty('--ivory', p.ivory);
  root.style.setProperty('--ink', p.ink);
  root.style.setProperty('--gold', p.gold);
  root.style.setProperty('--gold-pale', p.goldPale);
  root.style.setProperty('--line', p.line);

  const fonts = {
    cormorant: "'Cormorant Garamond', serif",
    playfair: "'Playfair Display', serif",
    tenor: "'Tenor Sans', serif",
    italiana: "'Italiana', serif",
  };
  // override the display font globally
  let style = document.getElementById('__tweak-font-style');
  if (!style) {
    style = document.createElement('style');
    style.id = '__tweak-font-style';
    document.head.appendChild(style);
  }
  style.textContent = `
    h1, h2, h3, h4, h5,
    .feature-txt h3, .sector-tile h3, .proj-card h3,
    .pullquote, .hero-title, .cs-hero h1, .about-hero h1,
    .leader-card .info h3, .footer-brand, .nav-brand,
    .timeline-list .yr, .cs-intro .lead, .contact-form-side h1,
    .event-types .pick .label, .feature-img-wrap, .success h2,
    .about-hero .stat .num, .contact-info .block .value, .press-item,
    .serif {
      font-family: ${fonts[t.displayFont] || fonts.cormorant};
    }
  `;
}

// ────────────────────────────────────────────────────────────────
// Router (state-based, no history)
// ────────────────────────────────────────────────────────────────
function useRouter() {
  const [route, setRoute] = useState({ page: 'home', slug: null });
  const navigate = useCallback((page, slug = null) => {
    setRoute({ page, slug });
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, []);
  return [route, navigate];
}

// ────────────────────────────────────────────────────────────────
// Nav
// ────────────────────────────────────────────────────────────────
function Nav({ route, navigate, dark }) {
  const [scrolled, setScrolled] = useState(false);
  const [lang, setLang] = useState('en');

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const isActive = (p) => route.page === p;
  const links = [
    { id: 'portfolio',  label: 'Portfolio' },
    { id: 'weddings',   label: 'Weddings',  goto: { page: 'portfolio', filter: 'weddings' } },
    { id: 'corporate',  label: 'Corporate', goto: { page: 'portfolio', filter: 'corporate' } },
    { id: 'about',      label: 'Studio' },
    { id: 'contact',    label: 'Contact' },
  ];

  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "") + (dark ? " dark" : "")}>
      <div className="nav-inner">
        <button className="nav-brand" onClick={() => navigate('home')} aria-label="Home">
          <span>Couture Events</span>
          <span className="sub">Worldwide · Dubai · Since 2004</span>
        </button>
        <div className="nav-links">
          {links.map(l => (
            <button
              key={l.id}
              className={"nav-link" + (isActive(l.id) ? ' active' : '')}
              onClick={() => {
                if (l.goto) {
                  navigate(l.goto.page);
                  setTimeout(() => window.dispatchEvent(new CustomEvent('cew:filter', { detail: l.goto.filter })), 50);
                } else {
                  navigate(l.id);
                }
              }}
            >{l.label}</button>
          ))}
        </div>
        <div className="nav-right">
          <div className="lang-toggle" aria-label="Language toggle">
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
            <span>/</span>
            <button className={lang === 'ar' ? 'active' : ''} onClick={() => setLang('ar')}>AR</button>
          </div>
          <button className="nav-cta-ghost" onClick={() => navigate('contact')}>Book a Consultation</button>
        </div>
      </div>
    </nav>
  );
}

// ────────────────────────────────────────────────────────────────
// Hero (cinematic, multi-image fade)
// ────────────────────────────────────────────────────────────────
function Hero({ navigate, layout }) {
  const slides = [
    { img: 'media/hero-bulgari-garden.webp',     loc: 'Bulgari · Jumeira Bay',    label: 'A Garden Reception' },
    { img: 'media/hero-armani-ballroom.webp',    loc: 'Armani · Burj Khalifa',    label: 'A Ballroom in Monochrome' },
    { img: 'media/hero-four-seasons.webp',       loc: 'Four Seasons · Jumeirah',  label: 'A Henna by the Sea' },
    { img: 'media/wedding-zabeel-saray.webp',    loc: 'Zabeel Saray · Palm',      label: 'A Quiet Ballroom' },
  ];
  const [i, setI] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setI(v => (v + 1) % slides.length), 6500);
    return () => clearInterval(t);
  }, []);

  return (
    <section className="hero" data-screen-label="01 Home — Hero">
      <div className="hero-images" aria-hidden="true">
        {slides.map((s, idx) => (
          <div
            key={idx}
            className={"hero-img" + (i === idx ? ' active' : '')}
            style={{ backgroundImage: `url(${s.img})` }}
          />
        ))}
      </div>

      <div className="hero-top">
        <div className="hero-eyebrow">
          <span className="dash"></span>
          <span>Est. Dubai · 2004 · 21 Years</span>
        </div>
        <div className="hero-counter">
          <div className="frac">{String(i + 1).padStart(2, '0')} / {String(slides.length).padStart(2, '0')}</div>
          <span className="lbl">{slides[i].loc}</span>
        </div>
      </div>

      <div className="hero-content">
        <div className="wrap">
          <div>
            <h1 className="hero-title">
              Every event,<br />
              <span className="em">a masterpiece.</span>
            </h1>
            <p className="hero-sub">
              A Dubai-based luxury event management studio — weddings, corporate &amp; brand events,
              private celebrations and bespoke proposals. Elegant, immersive, unforgettable —
              produced worldwide since 2004.
            </p>
            <div className="hero-ctas">
              <button className="btn btn-gold" onClick={() => navigate('contact')}>
                Book a Consultation <span style={{fontFamily:'serif', fontSize:'16px'}}>→</span>
              </button>
              <button className="btn btn-ghost-light" onClick={() => navigate('portfolio')}>
                View the Portfolio
              </button>
            </div>
          </div>
          <div className="hero-meta-col">
            <div className="meta-row">
              <span>Now showing</span>
              <strong>{slides[i].label}</strong>
            </div>
            <div className="meta-row">
              <span>Studio</span>
              <strong>Couture Events FZ-LLC, Dubai</strong>
            </div>
            <div className="meta-row">
              <span>Sectors</span>
              <strong>Weddings · Corporate · Social · Proposals</strong>
            </div>
          </div>
        </div>
      </div>

      <div className="hero-dots">
        {slides.map((_, idx) => (
          <div key={idx}
               className={"hero-dot" + (i === idx ? ' active' : '')}
               onClick={() => setI(idx)} />
        ))}
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────────
// Sector tiles
// ────────────────────────────────────────────────────────────────
function SectorTiles({ navigate }) {
  const tiles = [
    { id: 'weddings',  num: '01', label: 'Weddings',  blurb: 'Multicultural celebrations, destination ceremonies, multi-day events.',     img: 'media/wedding-armani.webp' },
    { id: 'corporate', num: '02', label: 'Corporate', blurb: 'Conferences, launches, awards, galas, exhibitions, PR & influencer.',        img: 'media/corporate-emirates-event.webp' },
    { id: 'social',    num: '03', label: 'Social',    blurb: 'Milestone birthdays, anniversaries, private dinners, brand-of-one moments.', img: 'media/decor-zen-den-lounge.webp' },
    { id: 'proposals', num: '04', label: 'Proposals', blurb: 'Bespoke "couture proposals" — quiet, cinematic, unrepeatable.',               img: 'media/wedding-inna-ceremony.webp' },
  ];

  return (
    <section className="section" data-screen-label="01 Home — Sectors">
      <div className="wrap" style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:'40px', alignItems:'end', marginBottom:'48px'}}>
        <div>
          <div className="eyebrow">— What we make</div>
          <h2 className="display-l" style={{marginTop:'18px'}}>
            Four practices,<br />
            <span className="italic" style={{color:'var(--gold)'}}>one studio.</span>
          </h2>
        </div>
        <p style={{color:'var(--muted-2)', fontSize:'15.5px', lineHeight:1.7, maxWidth:'480px'}}>
          Each sector is a distinct creative practice with its own production crew and design vocabulary —
          held together by a single studio standard. Briefs are bespoke; we never publish a price list.
        </p>
      </div>
      <div className="wrap" style={{padding:0}}>
        <div className="sector-grid wrap">
          {tiles.map(t => (
            <button
              key={t.id}
              className="sector-tile"
              onClick={() => {
                navigate('portfolio');
                setTimeout(() => window.dispatchEvent(new CustomEvent('cew:filter', { detail: t.id })), 50);
              }}
            >
              <div className="sector-tile-img" style={{backgroundImage:`url(${t.img})`}}></div>
              <div className="num">{t.num} / {t.label}</div>
              <h3>{t.label}</h3>
              <p>{t.blurb}</p>
              <div className="tag-line">
                <span>Explore the work</span>
                <span style={{fontFamily:'serif', fontSize:'14px'}}>→</span>
              </div>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────────
// Featured projects (alternating layout)
// ────────────────────────────────────────────────────────────────
function FeaturedProjects({ navigate }) {
  const featured = PROJECTS.filter(p => ['armani-pavilion','bulgari-garden','emirates-conference'].includes(p.slug));

  return (
    <section className="section" style={{background:'var(--ivory)'}} data-screen-label="01 Home — Featured">
      <div className="wrap">
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:'72px', flexWrap:'wrap', gap:'24px'}}>
          <div>
            <div className="eyebrow">— Selected work · 2023–24</div>
            <h2 className="display-l" style={{marginTop:'18px'}}>
              Three recent <span className="italic" style={{color:'var(--gold)'}}>productions.</span>
            </h2>
          </div>
          <button className="link-arrow" onClick={() => navigate('portfolio')}>
            All projects <span className="arr">→</span>
          </button>
        </div>

        {featured.map((p, idx) => (
          <div
            key={p.slug}
            className={"feature-row" + (idx % 2 === 1 ? ' reverse' : '')}
            onClick={() => navigate('case', p.slug)}
            style={{cursor:'pointer'}}
          >
            <div className="feature-img-wrap">
              <img src={p.cover} alt={p.title} />
            </div>
            <div className="feature-txt">
              <div className="feature-num">Project · {String(idx + 1).padStart(2,'0')}</div>
              <h3>{p.title}</h3>
              <p>{p.lead}</p>
              <dl className="feature-meta">
                <div><dt>Sector</dt><dd style={{textTransform:'capitalize'}}>{p.sector}</dd></div>
                <div><dt>Venue</dt><dd>{p.venue}</dd></div>
                <div><dt>Guests</dt><dd>{p.guests}</dd></div>
                <div><dt>Year</dt><dd>{p.year}</dd></div>
              </dl>
              <button className="link-arrow" onClick={(e) => { e.stopPropagation(); navigate('case', p.slug); }}>
                Read the case study <span className="arr">→</span>
              </button>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────────
// Editorial / venue grid + press strip
// ────────────────────────────────────────────────────────────────
function VenuesEditorial() {
  return (
    <section className="section" data-screen-label="01 Home — Venues">
      <div className="wrap">
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:'80px', alignItems:'end', marginBottom:'24px'}}>
          <div>
            <div className="eyebrow">— Familiar grounds</div>
            <h2 className="display-l" style={{marginTop:'18px'}}>
              The rooms we <span className="italic" style={{color:'var(--gold)'}}>know best.</span>
            </h2>
          </div>
          <p style={{color:'var(--muted-2)', fontSize:'15.5px', lineHeight:1.7, maxWidth:'480px'}}>
            We have produced events at most of the region's flagship hotels and a long list of private venues.
            Each room has its own rhythm; the design follows the architecture, never fights it.
          </p>
        </div>

        <div className="editorial-grid">
          <div className="editorial-card ed-a"><img src="media/venue-atlantis-the-royal.webp" alt="Atlantis the Royal" /><div className="caption"><span>Atlantis the Royal</span><span>Dubai · 2024</span></div></div>
          <div className="editorial-card ed-b"><img src="media/venue-jumeirah-golf-estates.webp" alt="Jumeirah Golf Estates" /><div className="caption"><span>Jumeirah Golf Estates</span><span>Dubai · 2023</span></div></div>
          <div className="editorial-card ed-c"><img src="media/venue-glass-tent-dubai.webp" alt="Glass Pavilion" /><div className="caption"><span>Glass Pavilion</span><span>Sharjah · 2024</span></div></div>
          <div className="editorial-card ed-d"><img src="media/venue-oman-shangrila.webp" alt="Shangri-La Oman" /><div className="caption"><span>Shangri-La</span><span>Muscat · 2024</span></div></div>
          <div className="editorial-card ed-e"><img src="media/venue-address-beach-resort.webp" alt="Address Beach Resort" /><div className="caption"><span>Address Beach Resort</span><span>Dubai · 2023</span></div></div>
        </div>
      </div>
    </section>
  );
}

function PressStrip() {
  return (
    <section className="press-strip" data-screen-label="01 Home — Press">
      <div className="wrap">
        <div className="press-strip-inner">
          <div className="press-strip-label">As featured in</div>
          <div className="press-list">
            {PRESS.map(p => (
              <span key={p.name} className="press-item">
                {p.name}<span className="pending">[ pending ]</span>
              </span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────────
// Pull-quote / philosophy
// ────────────────────────────────────────────────────────────────
function Philosophy() {
  return (
    <section className="section" data-screen-label="01 Home — Philosophy">
      <div className="wrap">
        <div style={{display:'grid', gridTemplateColumns:'1fr 2.4fr', gap:'80px', alignItems:'start'}}>
          <div>
            <div className="eyebrow">— Philosophy</div>
            <div className="meta" style={{marginTop:'18px'}}>Note no. 04</div>
          </div>
          <div>
            <p className="pullquote">
              <span className="open">"</span>
              Every detail is curated with intention, every concept executed with artistry —
              ensuring each event is not just an occasion, but an unforgettable <span className="italic" style={{color:'var(--gold)'}}>experience.</span>
            </p>
            <div style={{marginTop:'40px', display:'flex', gap:'20px', alignItems:'baseline'}}>
              <span className="meta">— Hannah Matthews</span>
              <span className="meta">CEO &amp; Creative Director</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────────
// Closing CTA band
// ────────────────────────────────────────────────────────────────
function CTABand({ navigate }) {
  return (
    <section className="cta-band" data-screen-label="01 Home — CTA">
      <div className="wrap">
        <div className="cta-band-inner">
          <h2>
            Begin a <span className="em">conversation.</span>
          </h2>
          <div>
            <p>
              Every commission starts with a quiet conversation. Tell us what you have in mind —
              a date, a guest count, a feeling. We will reply within one working day with next steps.
              No price list, no commitment.
            </p>
            <div className="actions">
              <button className="btn btn-gold" onClick={() => navigate('contact')}>
                Book a Consultation <span style={{fontFamily:'serif', fontSize:'16px'}}>→</span>
              </button>
              <a className="btn btn-ghost-light" href={CONTACT.whatsapp} target="_blank" rel="noopener">
                Message on WhatsApp
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────────
// Footer
// ────────────────────────────────────────────────────────────────
function Footer({ navigate }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <div className="footer-brand">
              Couture Events
              <span className="sub">Worldwide · Dubai · Since 2004</span>
            </div>
            <p style={{fontSize:'13.5px', lineHeight:1.7, maxWidth:'360px'}}>
              A luxury event management studio producing weddings, corporate &amp; brand events, private
              celebrations and bespoke proposals worldwide from Dubai.
            </p>
          </div>
          <div>
            <h4>Practices</h4>
            <ul>
              <li><button onClick={() => { navigate('portfolio'); setTimeout(() => window.dispatchEvent(new CustomEvent('cew:filter', { detail: 'weddings' })), 50); }}>Weddings</button></li>
              <li><button onClick={() => { navigate('portfolio'); setTimeout(() => window.dispatchEvent(new CustomEvent('cew:filter', { detail: 'corporate' })), 50); }}>Corporate</button></li>
              <li><button onClick={() => { navigate('portfolio'); setTimeout(() => window.dispatchEvent(new CustomEvent('cew:filter', { detail: 'social' })), 50); }}>Social</button></li>
              <li><button onClick={() => { navigate('portfolio'); setTimeout(() => window.dispatchEvent(new CustomEvent('cew:filter', { detail: 'proposals' })), 50); }}>Proposals</button></li>
            </ul>
          </div>
          <div>
            <h4>Studio</h4>
            <ul>
              <li><button onClick={() => navigate('about')}>About &amp; team</button></li>
              <li><button onClick={() => navigate('portfolio')}>Portfolio</button></li>
              <li><button onClick={() => navigate('contact')}>Contact</button></li>
              <li><a href={CONTACT.whatsapp} target="_blank" rel="noopener">WhatsApp</a></li>
            </ul>
          </div>
          <div>
            <h4>Contact</h4>
            <ul>
              <li><a href={`tel:${CONTACT.phone1.replace(/\s/g, '')}`}>{CONTACT.phone1}</a></li>
              <li><a href={`tel:${CONTACT.phone2.replace(/\s/g, '')}`}>{CONTACT.phone2}</a></li>
              <li><a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a></li>
              <li style={{display:'flex', gap:'14px', marginTop:'8px'}}>
                <a href={CONTACT.ig_url} target="_blank" rel="noopener">IG</a>
                <a href={CONTACT.fb_url} target="_blank" rel="noopener">FB</a>
                <a href={CONTACT.pinterest_url} target="_blank" rel="noopener">PIN</a>
                <a href={CONTACT.tiktok_url} target="_blank" rel="noopener">TT</a>
              </li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 · Couture Events FZ-LLC · Dubai · UAE</div>
          <div>coutureeventsworldwide.com</div>
        </div>
      </div>
    </footer>
  );
}

// ────────────────────────────────────────────────────────────────
// Consent strip
// ────────────────────────────────────────────────────────────────
function ConsentStrip() {
  return (
    <div className="consent-strip">
      <span className="gold-dot">●</span> &nbsp;
      Design mockup — all event imagery shown is reference only. Photographer credit, couple &amp; client
      consent pending per Couture Events publishing policy.
    </div>
  );
}

// ────────────────────────────────────────────────────────────────
// WhatsApp FAB
// ────────────────────────────────────────────────────────────────
function WhatsAppFab() {
  return (
    <a className="whatsapp-fab" href={CONTACT.whatsapp} target="_blank" rel="noopener">
      <span className="wa-dot"></span>
      <span>WhatsApp the Studio</span>
    </a>
  );
}

// ────────────────────────────────────────────────────────────────
// Home page
// ────────────────────────────────────────────────────────────────
function Home({ navigate, tweaks }) {
  return (
    <div className="page-enter">
      <Hero navigate={navigate} layout={tweaks.heroLayout} />
      {tweaks.showConsentStrip && <ConsentStrip />}
      <SectorTiles navigate={navigate} />
      <FeaturedProjects navigate={navigate} />
      <PressStrip />
      <VenuesEditorial />
      <Philosophy />
      <CTABand navigate={navigate} />
    </div>
  );
}

// ────────────────────────────────────────────────────────────────
// App
// ────────────────────────────────────────────────────────────────
function App() {
  const [route, navigate] = useRouter();
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);

  useEffect(() => { applyTweaks(tweaks); }, [tweaks]);

  // Nav uses default light/black styling on every page (no transparent-dark variant).
  const darkNav = false;

  return (
    <div className="app">
      <Nav route={route} navigate={navigate} dark={darkNav} />
      {route.page === 'home'      && <Home navigate={navigate} tweaks={tweaks} />}
      {route.page === 'portfolio' && <Portfolio navigate={navigate} />}
      {route.page === 'case'      && <CaseStudy slug={route.slug} navigate={navigate} />}
      {route.page === 'about'     && <About navigate={navigate} />}
      {route.page === 'contact'   && <Contact navigate={navigate} />}
      <Footer navigate={navigate} />
      <WhatsAppFab />
      <CewTweaks defaults={TWEAK_DEFAULTS} onChange={setTweaks} />
    </div>
  );
}

Object.assign(window, { App, applyTweaks });
