// Broadway Interiors — main app, navigation, home, footer

const { useState: useS, useEffect: useE, useRef: useR, useMemo: useM } = React;

// ──────────────────────────────────────────────────────────────────────
// Tweaks defaults — wired through useTweaks() in the panel
// ──────────────────────────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#A98B53",
  "type": "instrument",
  "heroTreatment": "still",
  "darkChrome": false
}/*EDITMODE-END*/;

// ──────────────────────────────────────────────────────────────────────
// Tiny hash router
// ──────────────────────────────────────────────────────────────────────
function useRoute() {
  const [route, setRoute] = useS(() => parseHash(location.hash));
  useE(() => {
    const onHash = () => setRoute(parseHash(location.hash));
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  const go = (path) => { location.hash = '#' + path; window.scrollTo(0, 0); };
  return [route, go];
}
function parseHash(hash) {
  const path = (hash || '#/').replace(/^#/, '') || '/';
  const parts = path.split('/').filter(Boolean);
  if (parts.length === 0) return { page: 'home', path: '/' };
  if (parts[0] === 'projects' && parts.length === 1) return { page: 'projects', path };
  if (parts[0] === 'projects' && parts[1]) return { page: 'case', slug: parts[1], path };
  if (parts[0] === 'sectors' && parts.length === 1) return { page: 'sectors', path };
  if (parts[0] === 'sectors' && parts[1]) return { page: 'sector', id: parts[1], path };
  if (parts[0] === 'about') return { page: 'about', path };
  if (parts[0] === 'awards') return { page: 'awards', path };
  if (parts[0] === 'contact') return { page: 'contact', path };
  return { page: '404', path };
}

// ──────────────────────────────────────────────────────────────────────
// Navbar
// ──────────────────────────────────────────────────────────────────────
function Navbar({ route, go, scrolled, darkChrome }) {
  const [open, setOpen] = useS(false);
  const items = [
    { id: 'projects', label: 'Projects' },
    { id: 'sectors', label: 'Sectors' },
    { id: 'about', label: 'Studio' },
    { id: 'awards', label: 'Awards' },
    { id: 'contact', label: 'Contact' },
  ];
  // Dark chrome when explicitly forced, or on home (scrolled toggles)
  const isHome = route.page === 'home';
  const isCase = route.page === 'case';
  const transparent = (isHome || isCase) && !scrolled;
  return (
    <nav className={'nav ' + (transparent ? 'nav--transparent' : 'nav--solid') + (darkChrome ? ' nav--dark' : '')}>
      <div className="nav__inner">
        <a className="nav__brand" href="#/" onClick={(e) => { e.preventDefault(); go('/'); }}>
          <div className="nav__brand-mark">
            <span className="serif">B</span>
          </div>
          <div className="nav__brand-text">
            <div className="nav__brand-name">Broadway Interiors</div>
            <div className="nav__brand-tag">Design &amp; build · Dubai · since 1999</div>
          </div>
        </a>
        <div className="nav__links">
          {items.map(it => (
            <a key={it.id} href={'#/' + it.id} className={'nav__link ' + (route.page === it.id || (it.id === 'projects' && route.page === 'case') || (it.id === 'sectors' && route.page === 'sector') ? 'on' : '')}
              onClick={(e) => { e.preventDefault(); go('/' + it.id); }}>{it.label}</a>
          ))}
        </div>
        <div className="nav__actions">
          <div className="nav__locale">
            <button className="locale on">EN</button>
            <button className="locale">AR</button>
          </div>
          <button className="btn btn--solid nav__cta" onClick={() => go('/contact')}>
            Start a project
          </button>
          <button className="nav__burger" onClick={() => setOpen(!open)}>
            <span/><span/><span/>
          </button>
        </div>
      </div>
      {open && (
        <div className="nav__mobile" onClick={() => setOpen(false)}>
          {items.map(it => (
            <a key={it.id} href={'#/' + it.id} onClick={(e) => { e.preventDefault(); go('/' + it.id); setOpen(false); }}>{it.label}</a>
          ))}
          <a href="#/contact" className="btn btn--solid" onClick={(e) => { e.preventDefault(); go('/contact'); setOpen(false); }}>Start a project →</a>
        </div>
      )}
    </nav>
  );
}

// ──────────────────────────────────────────────────────────────────────
// Home
// ──────────────────────────────────────────────────────────────────────
function Home({ go, heroTreatment }) {
  const featured = PROJECTS.filter(p => p.featured);
  const [marqueeIdx, setMarqueeIdx] = useS(0);

  useE(() => {
    const i = setInterval(() => setMarqueeIdx(x => (x + 1) % featured.length), 4500);
    return () => clearInterval(i);
  }, [featured.length]);

  return (
    <div className="page home">
      <HeroBlock treatment={heroTreatment} go={go} />

      {/* Manifesto strip */}
      <section className="manifesto">
        <div className="manifesto__inner">
          <div className="manifesto__small">An award-winning, design-and-build consultancy in Dubai. Established 1999.</div>
          <h2 className="manifesto__h serif">
            We design it
            <span className="manifesto__amp italic">&nbsp;to be built<span className="manifesto__dot">.</span></span><br/>
            <span className="italic">And then we build it.</span>
          </h2>
          <div className="manifesto__sub">
            One studio. One project manager. One quantity surveyor. The drawings
            and the workshop sit four metres apart — which is why the rooms we
            deliver still look the way we drew them.
          </div>
        </div>
      </section>

      {/* Sectors */}
      <section className="home-sectors">
        <div className="section-head">
          <div className="eyebrow">Five sectors · 70+ projects</div>
          <h2 className="section-head__h serif">Rooms we draw and build.</h2>
        </div>
        <div className="sector-tiles">
          {SECTORS.map((s, i) => {
            const proj = PROJECTS.filter(p => p.sector === s.id);
            const cover = proj[0];
            return (
              <a key={s.id} className="sector-tile" href={`#/sectors/${s.id}`}
                 onClick={(e) => { e.preventDefault(); go(`/sectors/${s.id}`); }}
                 style={{ '--idx': i }}>
                <div className="sector-tile__media">
                  {cover && <img src={cover.image} alt="" loading="lazy" />}
                </div>
                <div className="sector-tile__meta">
                  <div className="sector-tile__num">0{i + 1}</div>
                  <div className="sector-tile__name serif">{s.label}</div>
                  <div className="sector-tile__count">{proj.length} projects →</div>
                </div>
              </a>
            );
          })}
        </div>
      </section>

      {/* Featured work — big editorial spreads */}
      <section className="home-featured">
        <div className="section-head section-head--row">
          <div>
            <div className="eyebrow">Selected case studies</div>
            <h2 className="section-head__h serif">Designed &amp; built.</h2>
          </div>
          <a className="link-arrow" href="#/projects" onClick={(e) => { e.preventDefault(); go('/projects'); }}>
            All 30 projects →
          </a>
        </div>
        <div className="feature-spreads">
          {featured.slice(0, 4).map((p, i) => (
            <FeatureSpread key={p.slug} project={p} index={i} go={go} />
          ))}
        </div>
      </section>

      {/* Design-and-build differentiator strip */}
      <section className="diff-strip">
        <div className="diff-strip__inner">
          <div className="diff-strip__label">The difference</div>
          <div className="diff-strip__grid">
            <div className="diff-cell">
              <div className="diff-cell__num serif">01.</div>
              <h3 className="serif">One studio for design and delivery.</h3>
              <p>Most fit-out projects involve at least three companies. Ours involve one. The
                programme tightens and the change orders disappear.</p>
            </div>
            <div className="diff-cell">
              <div className="diff-cell__num serif">02.</div>
              <h3 className="serif">In-house QS, on day one.</h3>
              <p>Our Managing QS sits in design reviews. The concept already knows what it costs
                — and how it will be procured — before you see it.</p>
            </div>
            <div className="diff-cell">
              <div className="diff-cell__num serif">03.</div>
              <h3 className="serif">A 70-project rolodex of trades.</h3>
              <p>Twenty-five years of vetted joiners, MEP partners and finish suppliers — picked
                per project, not assigned by default.</p>
            </div>
          </div>
        </div>
      </section>

      {/* Awards strip — marquee */}
      <section className="awards-strip">
        <div className="awards-strip__inner">
          <div className="awards-strip__head">
            <div className="eyebrow eyebrow--light">25+ design awards · 2010 — 2025</div>
            <h2 className="serif">Including a few we’re especially proud of.</h2>
          </div>
          <div className="awards-strip__list">
            {AWARDS.filter(a => a.flagship).concat(AWARDS.filter(a => !a.flagship).slice(0, 4)).map((a, i) => (
              <div key={i} className={'award-row ' + (a.flagship ? 'award-row--flagship' : '')}>
                <div className="award-row__year serif">{a.year}</div>
                <div className="award-row__body">
                  <div className="award-row__title">{a.flagship && '★ '}{a.title}</div>
                  <div className="award-row__meta">
                    {a.issuer}{a.project ? ` · ${a.project}` : ''}
                  </div>
                </div>
                {a.flagship && <div className="award-row__badge">Flagship</div>}
              </div>
            ))}
          </div>
          <div className="awards-strip__foot">
            <a className="link-arrow link-arrow--light" href="#/awards" onClick={(e) => { e.preventDefault(); go('/awards'); }}>
              The full list →
            </a>
          </div>
        </div>
      </section>

      {/* Trusted by */}
      <section className="trusted">
        <div className="trusted__inner">
          <div className="eyebrow">Public, private &amp; operator clients · selected</div>
          <div className="trusted__list">
            {['DEWA', 'KHDA', 'DIFC', 'MBRSC', 'Asia Asia', 'STK', 'Black Tap', 'Lock, Stock & Barrel',
              'Viacom', 'Anantara', 'Make Up For Ever', 'Rixos', 'Grand Millennium', 'twofour54', 'DAFZA', 'HIPA'].map(c => (
              <div key={c} className="trusted__cell">{c}</div>
            ))}
          </div>
          <div className="trusted__note">
            Some government and operator names withheld pending publication clearance.
          </div>
        </div>
      </section>

      <CtaBand go={go} />
    </div>
  );
}

function HeroBlock({ treatment, go }) {
  const hero = PROJECTS.find(p => p.hero) || PROJECTS[0];
  if (treatment === 'split') return <HeroSplit project={hero} go={go} />;
  if (treatment === 'noir') return <HeroNoir project={hero} go={go} />;
  return <HeroStill project={hero} go={go} />;
}

function HeroStill({ project, go }) {
  return (
    <header className="hero hero--still">
      <div className="hero__bg">
        <img src={project.image} alt={project.name} />
        <div className="hero__veil"/>
      </div>
      <div className="hero__content">
        <div className="hero__eyebrow">
          <span className="hero__dot" /> Award-winning interior design + build · Dubai · since 1999
        </div>
        <h1 className="hero__title serif">
          Intelligent,<br/>
          innovative<br/>
          <span className="italic">design.</span>
        </h1>
        <p className="hero__lede">
          A boutique design and build consultancy — drawing and delivering F&amp;B,
          office, government, leisure and residential interiors from a single studio
          in Barsha Heights.
        </p>
        <div className="hero__actions">
          <button className="btn btn--solid btn--light" onClick={() => go('/projects')}>See the work →</button>
          <button className="btn btn--ghost btn--light" onClick={() => go('/contact')}>Start a project</button>
        </div>
        <div className="hero__credit">
          <div className="hero__credit-num">№ 01 / Asia Asia</div>
          <div className="hero__credit-meta">Pier 7, Dubai Marina · 2013 · World’s Best Leisure Interior, 2021</div>
        </div>
      </div>
      <div className="hero__scroll">
        <span>Scroll</span>
        <div className="hero__scroll-line"/>
      </div>
    </header>
  );
}

function HeroSplit({ project, go }) {
  return (
    <header className="hero hero--split">
      <div className="hero-split">
        <div className="hero-split__copy">
          <div className="hero__eyebrow"><span className="hero__dot"/> Dubai · since 1999</div>
          <h1 className="hero__title serif">
            Intelligent,<br/>
            innovative<br/>
            <span className="italic">design.</span>
          </h1>
          <p className="hero__lede">
            Award-winning interior design + build consultancy. One studio. Five sectors.
            Seventy delivered projects.
          </p>
          <div className="hero__actions">
            <button className="btn btn--solid" onClick={() => go('/projects')}>See the work →</button>
            <button className="btn btn--ghost" onClick={() => go('/contact')}>Start a project</button>
          </div>
        </div>
        <div className="hero-split__media">
          <img src={project.image} alt={project.name} />
          <div className="hero-split__plate">
            <div>№ 01 · Asia Asia</div>
            <div className="serif italic">Pier 7, Dubai Marina · 2013</div>
          </div>
        </div>
      </div>
    </header>
  );
}

function HeroNoir({ project, go }) {
  return (
    <header className="hero hero--noir">
      <div className="hero__bg">
        <img src={project.image} alt={project.name} />
        <div className="hero__veil hero__veil--heavy"/>
      </div>
      <div className="hero__content hero__content--centered">
        <div className="hero__eyebrow">Broadway Interiors · est. 1999 · Dubai</div>
        <h1 className="hero__title serif hero__title--big">
          Intelligent,<br/>
          innovative<br/>
          <span className="italic">design.</span>
        </h1>
        <div className="hero__actions hero__actions--centered">
          <button className="btn btn--solid btn--light" onClick={() => go('/projects')}>Selected work →</button>
        </div>
      </div>
    </header>
  );
}

function FeatureSpread({ project, index, go }) {
  const sector = SECTORS.find(s => s.id === project.sector);
  return (
    <a className={'feature-spread feature-spread--' + (index % 2 === 0 ? 'right' : 'left')}
       href={`#/projects/${project.slug}`}
       onClick={(e) => { e.preventDefault(); go(`/projects/${project.slug}`); }}>
      <div className="feature-spread__media">
        <img src={project.image} alt={project.name} loading="lazy" />
      </div>
      <div className="feature-spread__copy">
        <div className="feature-spread__num serif">№ {String(index + 1).padStart(2, '0')}</div>
        <div className="feature-spread__sector">{sector ? sector.label : project.sector} · {project.location}</div>
        <h3 className="feature-spread__title serif">{project.name}<span className="period">.</span></h3>
        {project.tagline && <div className="feature-spread__tag serif italic">{project.tagline}</div>}
        <p className="feature-spread__summary">{project.summary}</p>
        <div className="feature-spread__meta">
          <span>{project.scope}</span><span className="dot">·</span><span>{project.year}</span>
        </div>
        <div className="feature-spread__cta">Read the case study →</div>
      </div>
    </a>
  );
}

// ──────────────────────────────────────────────────────────────────────
// Footer
// ──────────────────────────────────────────────────────────────────────
function Footer({ go }) {
  return (
    <footer className="footer">
      <div className="footer__inner">
        <div className="footer__col footer__col--brand">
          <div className="footer__brand serif">Broadway<br/><span className="italic">Interiors.</span></div>
          <div className="footer__tag">Intelligent, innovative design.</div>
          <div className="footer__addr">
            Office 1512, Grosvenor Business Tower<br/>
            Barsha Heights (TECOM), Dubai, UAE<br/>
            <a href="tel:+97144508546">+971 4 450 8546</a><br/>
            <a href="mailto:sales@broadwayinteriors.com">sales@broadwayinteriors.com</a>
          </div>
        </div>
        <div className="footer__col">
          <div className="footer__h">Sectors</div>
          <ul>
            {SECTORS.map(s => (
              <li key={s.id}><a href={`#/sectors/${s.id}`} onClick={(e) => { e.preventDefault(); go(`/sectors/${s.id}`); }}>{s.label}</a></li>
            ))}
          </ul>
        </div>
        <div className="footer__col">
          <div className="footer__h">Studio</div>
          <ul>
            <li><a href="#/about" onClick={(e) => { e.preventDefault(); go('/about'); }}>About</a></li>
            <li><a href="#/awards" onClick={(e) => { e.preventDefault(); go('/awards'); }}>Awards</a></li>
            <li><a href="#/projects" onClick={(e) => { e.preventDefault(); go('/projects'); }}>All projects</a></li>
            <li><a href="mailto:jobs@broadwayinteriors.com">Careers</a></li>
          </ul>
        </div>
        <div className="footer__col">
          <div className="footer__h">Contact</div>
          <ul>
            <li><a href="#/contact" onClick={(e) => { e.preventDefault(); go('/contact'); }}>Start a project</a></li>
            <li><a href="#/contact" onClick={(e) => { e.preventDefault(); go('/contact'); }}>Request a tender response</a></li>
            <li><a href="https://www.linkedin.com/company/broadway-interiors-llc" target="_blank" rel="noreferrer">LinkedIn</a></li>
            <li><a href="https://instagram.com/broadwayinteriors" target="_blank" rel="noreferrer">Instagram</a></li>
          </ul>
        </div>
      </div>
      <div className="footer__bar">
        <div>© 1999 — 2026 Broadway Interiors LLC. Dubai, UAE.</div>
        <div className="footer__legal">
          <span>UAE trade licence available on request</span>
          <span>·</span>
          <a href="#">Privacy</a>
          <span>·</span>
          <a href="#">Terms</a>
        </div>
      </div>
    </footer>
  );
}

// ──────────────────────────────────────────────────────────────────────
// Tweaks
// ──────────────────────────────────────────────────────────────────────
function TweaksUI() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useE(() => {
    const root = document.documentElement;
    root.style.setProperty('--accent', t.accent);
    root.dataset.type = t.type;
    root.dataset.darkChrome = t.darkChrome ? '1' : '0';
  }, [t.accent, t.type, t.darkChrome]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Accent" />
      <TweakColor label="Accent" value={t.accent}
        options={['#A98B53', '#1F2A2E', '#7A8B6B', '#9B3E2F', '#C6B89E']}
        onChange={(v) => setTweak('accent', v)} />

      <TweakSection label="Type" />
      <TweakRadio label="Display" value={t.type}
        options={[
          { value: 'instrument', label: 'Instrument' },
          { value: 'cormorant', label: 'Cormorant' },
          { value: 'fraunces', label: 'DM Serif' },
        ]}
        onChange={(v) => setTweak('type', v)} />

      <TweakSection label="Hero" />
      <TweakRadio label="Treatment" value={t.heroTreatment}
        options={[
          { value: 'still', label: 'Bleed' },
          { value: 'split', label: 'Split' },
          { value: 'noir', label: 'Noir' },
        ]}
        onChange={(v) => setTweak('heroTreatment', v)} />

      <TweakSection label="Navigation" />
      <TweakToggle label="Dark chrome" value={t.darkChrome}
        onChange={(v) => setTweak('darkChrome', v)} />
    </TweaksPanel>
  );
}

// ──────────────────────────────────────────────────────────────────────
// Root
// ──────────────────────────────────────────────────────────────────────
function App() {
  const [route, go] = useRoute();
  const [scrolled, setScrolled] = useS(false);
  const [projFilter, setProjFilter] = useS('all');
  const [t] = useTweaks(TWEAK_DEFAULTS);

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

  let body = null;
  if (route.page === 'home') body = <Home go={go} heroTreatment={t.heroTreatment} />;
  else if (route.page === 'projects') body = <ProjectsPage filter={projFilter} setFilter={setProjFilter} go={go} />;
  else if (route.page === 'case') body = <CaseStudy slug={route.slug} go={go} />;
  else if (route.page === 'sectors') body = <SectorsPage go={go} />;
  else if (route.page === 'sector') body = <SectorPage id={route.id} go={go} />;
  else if (route.page === 'about') body = <AboutPage go={go} />;
  else if (route.page === 'awards') body = <AwardsPage go={go} />;
  else if (route.page === 'contact') body = <ContactPage go={go} />;
  else body = <NotFound go={go} />;

  return (
    <div className="root" data-page={route.page}>
      <Navbar route={route} go={go} scrolled={scrolled} darkChrome={t.darkChrome} />
      <main key={route.path} className="main">{body}</main>
      <Footer go={go} />
      <TweaksUI />
    </div>
  );
}

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