// Interactive prototype — Variation A (Cosy Craftsman).
// Wraps the existing page components with router state, page transitions,
// interactive gallery filters, working contact form, and click delegation
// for inline CTAs (so "Get a quote" buttons inside pages also navigate).

const THEME = THEMES.cosy;

// Page list (with synthetic "Trade" page that just routes home for now)
const PAGES = ['Home','Services','Gallery','About','Contact'];

// =============================================================
// Interactive Gallery — filterable
// =============================================================
const ALL_PROJECTS = [
  { id:'chiswick',  hue:'oak',    tone:'warm',  title:'Chiswick semi · Whole-house oak laminate',  meta:'128m² · 6 days',           tag:'Laminate',  room:'Living' },
  { id:'sevenoaks', hue:'walnut', tone:'dusk',  title:'Sevenoaks kitchen · Karndean herringbone',  meta:'24m² · 3 days · LVT',      tag:'LVT',       room:'Kitchen' },
  { id:'edinburgh', hue:'cream',  tone:'cream', title:'Edinburgh townhouse · Wool stair runner',   meta:'Stairs + landing · 2 days',tag:'Carpet',    room:'Stairs' },
  { id:'bristol',   hue:'grey',   tone:'stone', title:'Bristol office · Commercial-grade LVT',     meta:'Before/after · 60m²',      tag:'Commercial',room:'Commercial' },
  { id:'cotswolds', hue:'ash',    tone:'warm',  title:'Cotswolds farmhouse · Reclaimed-look LVT',  meta:'Subfloor screeded + fitted',tag:'LVT',       room:'Living' },
  { id:'hampstead', hue:'walnut', tone:'cool',  title:'Hampstead hallway · Engineered laminate',   meta:'18m² · 2 days',            tag:'Laminate',  room:'Hallway' },
  { id:'brighton',  hue:'cream',  tone:'cream', title:'Brighton master bedroom · Plush wool',      meta:'Soft cosy underlay · 32m²',tag:'Carpet',    room:'Bedroom' },
  { id:'manchester',hue:'oak',    tone:'warm',  title:'Manchester let-flat · Quick turnaround',    meta:'42m² in 2 days',           tag:'Laminate',  room:'Living' },
  { id:'surrey',    hue:'walnut', tone:'dusk',  title:'Surrey new-build · LVT throughout',         meta:'Levelled + fitted · 110m²',tag:'LVT',       room:'Kitchen' },
];

function InteractiveDesktopGallery({ t }) {
  const [tag, setTag] = React.useState('All work');
  const [room, setRoom] = React.useState('All rooms');
  const cats = ['All work','Laminate','LVT','Carpet','Commercial'];
  const rooms = ['All rooms','Kitchen','Living','Hallway','Bedroom','Stairs','Commercial'];
  const filtered = ALL_PROJECTS.filter(p =>
    (tag === 'All work' || p.tag === tag || (tag === 'LVT' && p.tag === 'LVT')) &&
    (room === 'All rooms' || p.room === room)
  );

  return (
    <div style={{ background: t.bg, color: t.ink, fontFamily: t.bFont }}>
      <Header t={t} active="Gallery"/>
      <Section t={t} pad="56px 48px 32px">
        <Eyebrow t={t}>Gallery</Eyebrow>
        <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr', gap: 48, alignItems:'flex-end' }}>
          <h1 style={{ fontFamily: t.hFont, fontSize: 72, lineHeight: 1, letterSpacing: -1, margin: 0, color: t.ink, fontWeight: 500 }}>
            Real homes,<br/>real floors, real prep.
          </h1>
          <p style={{ fontSize: 16, lineHeight: 1.55, color: t.body, margin: 0 }}>
            Every project here was prepped, supplied and installed by our own teams. Click any to see the before/after.
          </p>
        </div>
      </Section>

      <Section t={t} pad="0 48px 24px">
        <div style={{ display:'flex', gap: 12, alignItems:'center', borderBottom:`1px solid ${t.line}`, paddingBottom: 18, flexWrap:'wrap' }}>
          <span style={{ fontSize: 11, letterSpacing: 2, color: t.muted, textTransform:'uppercase', marginRight: 8 }}>Filter</span>
          <div style={{ display:'flex', gap: 8, flexWrap:'wrap' }}>
            {cats.map(c => (
              <button key={c} onClick={() => setTag(c)} style={chip(t, c === tag)}>{c}</button>
            ))}
          </div>
          <div style={{ width: 1, height: 22, background: t.line, margin: '0 8px' }}/>
          <div style={{ display:'flex', gap: 8, flexWrap:'wrap' }}>
            {rooms.map(r => (
              <button key={r} onClick={() => setRoom(r)} style={chip(t, r === room, true)}>{r}</button>
            ))}
          </div>
          {(tag !== 'All work' || room !== 'All rooms') && (
            <button onClick={() => { setTag('All work'); setRoom('All rooms'); }} style={{
              marginLeft: 'auto', background:'transparent', border:'none', color: t.primary,
              fontSize: 13, fontFamily: t.bFont, fontWeight: 600, cursor:'pointer', textDecoration:'underline',
            }}>Clear filters</button>
          )}
        </div>
        <div style={{ fontSize: 12, color: t.muted, marginTop: 14, fontFamily: t.bFont }}>
          Showing <strong style={{ color: t.ink }}>{filtered.length}</strong> of {ALL_PROJECTS.length} projects
        </div>
      </Section>

      <Section t={t} pad="8px 48px 88px">
        {filtered.length === 0 ? (
          <div style={{ padding: '64px 0', textAlign:'center', color: t.muted, fontFamily: t.bFont }}>
            No projects match. <button onClick={() => { setTag('All work'); setRoom('All rooms'); }} style={{ background:'none', border:'none', color: t.primary, cursor:'pointer', textDecoration:'underline', fontSize: 14 }}>Clear filters</button>
          </div>
        ) : (
          <div style={{ columnCount: 3, columnGap: 18 }}>
            {filtered.map((p, i) => (
              <ProjectCard key={p.id} t={t} p={p} i={i}/>
            ))}
          </div>
        )}
      </Section>

      <Footer t={t}/>
    </div>
  );
}

function ProjectCard({ t, p, i }) {
  const [hover, setHover] = React.useState(false);
  return (
    <article
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        breakInside:'avoid', marginBottom: 18, background: t.surface,
        borderRadius: t.radius, overflow:'hidden', border:`1px solid ${t.line}`,
        boxShadow: hover ? '0 12px 32px -12px rgba(60,40,20,.3)' : t.shadow,
        transform: hover ? 'translateY(-2px)' : 'none',
        transition: 'all .25s ease', cursor:'pointer',
      }}>
      <div style={{ height: 220 + (i % 3) * 40, position:'relative' }}>
        <RoomPlaceholder w={400} h={220 + (i % 3) * 40} theme={t} tone={p.tone} label={`${p.tag.toUpperCase()} · ${p.room.toUpperCase()}`}/>
        <div style={{
          position:'absolute', top: 12, left: 12,
          background: t.bg, padding: '5px 10px', borderRadius: 999,
          fontSize: 11, letterSpacing:.3, color: t.ink, fontFamily: t.bFont, fontWeight: 600,
          border:`1px solid ${t.line}`,
        }}>{p.tag}</div>
        {i % 3 === 0 && (
          <div style={{
            position:'absolute', top: 12, right: 12,
            background: t.primary, color: t.primaryInk, padding: '5px 10px', borderRadius: 999,
            fontSize: 11, fontFamily: t.bFont, fontWeight: 600,
          }}>Before / after</div>
        )}
      </div>
      <div style={{ padding: '16px 18px 18px' }}>
        <h3 style={{ fontFamily: t.hFont, fontSize: 18, margin: 0, color: t.ink, fontWeight: 500, lineHeight: 1.25 }}>{p.title}</h3>
        <div style={{ fontSize: 12, color: t.muted, marginTop: 6 }}>{p.meta}</div>
      </div>
    </article>
  );
}

function chip(t, active, alt) {
  return {
    fontSize: 13, padding: '8px 14px', borderRadius: 999,
    background: active ? (alt ? t.ink : t.primary) : 'transparent',
    color: active ? t.primaryInk : t.body,
    border: active ? 'none' : `1px solid ${t.line}`,
    fontFamily: t.bFont, fontWeight: 500, cursor:'pointer',
    transition: 'all .15s ease',
  };
}

// Mobile gallery, interactive
function InteractiveMobileGallery({ t }) {
  const [tag, setTag] = React.useState('All work');
  const cats = ['All work','Laminate','LVT','Carpet','Commercial'];
  const filtered = ALL_PROJECTS.filter(p => tag === 'All work' || p.tag === tag);
  return (
    <MobileShell t={t} active="Gallery">
      <section style={{ padding:'24px 18px 16px' }}>
        <div style={{ fontSize: 10, letterSpacing: 2, textTransform:'uppercase', color: t.primary, fontWeight: 600, marginBottom: 8 }}>Gallery</div>
        <h1 style={{ fontFamily: t.hFont, fontSize: 42, lineHeight: 1, letterSpacing:-1, margin:0, color: t.ink, fontWeight: 500 }}>
          Real homes,<br/>real prep.
        </h1>
      </section>
      <section style={{ padding:'0 18px 12px' }}>
        <div style={{ display:'flex', gap: 6, overflowX:'auto', paddingBottom: 6 }}>
          {cats.map(c => (
            <button key={c} onClick={() => setTag(c)} style={{...chip(t, c === tag), whiteSpace:'nowrap', fontSize: 12 }}>{c}</button>
          ))}
        </div>
        <div style={{ fontSize: 11.5, color: t.muted, marginTop: 8, fontFamily: t.bFont }}>{filtered.length} projects</div>
      </section>
      <section style={{ padding:'4px 18px 24px' }}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 10 }}>
          {filtered.map((p,i) => (
            <article key={p.id} style={{ background: t.surface, borderRadius: t.radius, overflow:'hidden', border:`1px solid ${t.line}`, cursor:'pointer' }}>
              <div style={{ height: 160 + (i%2)*40, position:'relative' }}>
                <RoomPlaceholder w={170} h={160 + (i%2)*40} theme={t} tone={p.tone} label=""/>
                {i % 3 === 0 && (
                  <div style={{ position:'absolute', top: 8, left: 8, background: t.primary, color: t.primaryInk, padding:'3px 8px', borderRadius: 999, fontSize: 10, fontWeight: 600 }}>Before / after</div>
                )}
              </div>
              <div style={{ padding:'10px 12px 12px' }}>
                <div style={{ fontFamily: t.hFont, fontSize: 14, color: t.ink, fontWeight: 500, lineHeight: 1.2 }}>{p.title.split(' · ')[0]}</div>
                <div style={{ fontSize: 11, color: t.muted, marginTop: 2 }}>{p.tag}</div>
              </div>
            </article>
          ))}
        </div>
      </section>
    </MobileShell>
  );
}

// =============================================================
// Interactive Contact form
// =============================================================
function InteractiveContact({ t, mobile }) {
  const [form, setForm] = React.useState({ name:'', phone:'', postcode:'', time:'', message:'' });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  const update = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Tell us your name';
    if (!/^[\d\s+()-]{7,}$/.test(form.phone.trim())) e.phone = 'A phone we can ring';
    if (!form.postcode.trim()) e.postcode = 'So we know who is nearest';
    return e;
  };
  const submit = (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) setSubmitted(true);
  };

  const InputField = ({ k, label, placeholder, type='text', multi }) => (
    <label style={{ display:'flex', flexDirection:'column', gap: 6 }}>
      <span style={{ fontSize: 11.5, letterSpacing: 1.4, textTransform:'uppercase', color: t.muted, fontFamily: t.bFont, fontWeight: 600 }}>{label}</span>
      {multi ? (
        <textarea value={form[k]} onChange={update(k)} placeholder={placeholder} rows={3} style={inputStyle(t, !!errors[k])}/>
      ) : (
        <input type={type} value={form[k]} onChange={update(k)} placeholder={placeholder} style={inputStyle(t, !!errors[k])}/>
      )}
      {errors[k] && <span style={{ fontSize: 11.5, color: '#C44A1E', fontFamily: t.bFont }}>{errors[k]}</span>}
    </label>
  );

  const formInner = (
    <form onSubmit={submit} style={{ background: t.surface, borderRadius: t.radius, padding: mobile?'22px 20px':'36px 36px', border:`1px solid ${t.line}` }}>
      <Eyebrow t={t}>Request a callback</Eyebrow>
      <h2 style={{ fontFamily: t.hFont, fontSize: mobile?24:32, margin: '0 0 4px', color: t.ink, fontWeight: 500, letterSpacing:-.2 }}>
        Or we&rsquo;ll call you.
      </h2>
      <p style={{ fontSize: 13.5, color: t.muted, marginBottom: 22 }}>Four fields, no spam, no follow-ups unless you want them.</p>

      {submitted ? (
        <div style={{
          background: t.primary, color: t.primaryInk, borderRadius: t.radiusSm,
          padding: '20px 22px', display:'flex', gap: 14, alignItems:'center',
        }}>
          <div style={{
            width: 36, height: 36, borderRadius:'50%', background:'rgba(255,255,255,.18)',
            display:'grid', placeItems:'center', fontSize: 18, color: t.primaryInk,
          }}>✓</div>
          <div>
            <div style={{ fontFamily: t.hFont, fontSize: 18, fontWeight: 500, color: t.primaryInk }}>Thanks, {form.name.split(' ')[0] || 'we got it'}.</div>
            <div style={{ fontSize: 13, color:'rgba(255,255,255,.85)', marginTop: 2 }}>We&rsquo;ll call {form.phone} within 1 working day.</div>
          </div>
          <button type="button" onClick={() => { setSubmitted(false); setForm({ name:'', phone:'', postcode:'', time:'', message:'' }); }} style={{
            marginLeft:'auto', background:'transparent', border:'1px solid rgba(255,255,255,.4)', color: t.primaryInk,
            padding:'8px 14px', borderRadius: t.radiusSm, fontSize: 13, cursor:'pointer', fontFamily: t.bFont,
          }}>Send another</button>
        </div>
      ) : (
        <>
          <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 14 }}>
            <InputField k="name" label="Your name" placeholder="Helena Page"/>
            <InputField k="phone" label="Phone" placeholder="07700 900 123" type="tel"/>
            <InputField k="postcode" label="Postcode" placeholder="SE19 2QF"/>
            <InputField k="time" label="Best time to call" placeholder="Weekday morning"/>
          </div>
          <div style={{ marginTop: 14 }}>
            <InputField k="message" label="What do you need?" placeholder="Living room (~22m²) — old laminate to come up, new LVT down." multi/>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap: 14, marginTop: 22, flexWrap:'wrap' }}>
            <button type="submit" style={{...btnPrimary(t), padding:'14px 24px' }}>Request callback →</button>
            <span style={{ fontSize: 12, color: t.muted }}>We&rsquo;ll be in touch within 1 working day.</span>
          </div>
        </>
      )}
    </form>
  );

  if (mobile) {
    return (
      <MobileShell t={t} active="Contact">
        <section style={{ padding:'24px 18px 12px' }}>
          <Eyebrow t={t}>Contact</Eyebrow>
          <h1 style={{ fontFamily: t.hFont, fontSize: 44, lineHeight: 1, letterSpacing:-1, margin: 0, color: t.ink, fontWeight: 500 }}>
            Pick up the phone. Fin&rsquo;s on the other end.
          </h1>
        </section>
        <section style={{ padding:'12px 18px 24px' }}>
          <div style={{ background: t.primary, color: t.primaryInk, borderRadius: t.radius, padding: '24px 22px' }}>
            <div style={{ fontSize: 10, letterSpacing: 2, textTransform:'uppercase', color:'rgba(255,255,255,.7)', fontWeight: 600, marginBottom: 8 }}>Mon – Sat · 7am to 7pm</div>
            <a href="tel:08080942210" style={{ fontFamily: t.hFont, fontSize: 40, lineHeight: 1, color: t.primaryInk, letterSpacing:-1.2, fontWeight: 500, textDecoration:'none', display:'block' }}>0808 094 2210</a>
            <p style={{ fontSize: 13, color:'rgba(255,255,255,.85)', marginTop: 14, lineHeight: 1.55 }}>
              Free, no-pressure quote. Or send photos by WhatsApp — we&rsquo;ll come back with a ballpark within a day.
            </p>
          </div>
        </section>
        <section style={{ padding:'8px 18px 28px' }}>{formInner}</section>
        <section style={{ padding:'8px 18px 32px' }}>
          <Eyebrow t={t}>Where we work</Eyebrow>
          <h2 style={{ fontFamily: t.hFont, fontSize: 26, margin: 0, color: t.ink, fontWeight: 500, letterSpacing:-.2 }}>The whole of the UK.</h2>
          <p style={{ fontSize: 13.5, color: t.body, lineHeight: 1.55, marginTop: 10 }}>Regional teams across England, Wales and Scotland.</p>
          <UkMap t={t}/>
        </section>
      </MobileShell>
    );
  }

  return (
    <div style={{ background: t.bg, color: t.ink, fontFamily: t.bFont }}>
      <Header t={t} active="Contact"/>
      <Section t={t} pad="64px 48px 40px">
        <Eyebrow t={t}>Contact</Eyebrow>
        <h1 style={{ fontFamily: t.hFont, fontSize: 88, lineHeight: 1, letterSpacing: -1.4, margin: 0, color: t.ink, fontWeight: 500 }}>
          Pick up the phone.<br/>Fin&rsquo;s on the other end.
        </h1>
      </Section>
      <Section t={t} pad="12px 48px 56px">
        <div style={{ background: t.primary, color: t.primaryInk, borderRadius: t.radius, padding: '48px 56px', display:'grid', gridTemplateColumns:'1.4fr 1fr', gap: 36, alignItems:'center' }}>
          <div>
            <div style={{ fontFamily: t.bFont, fontSize: 12, letterSpacing: 2.4, textTransform:'uppercase', color:'rgba(255,255,255,.7)', marginBottom: 12, fontWeight: 600 }}>Mon – Sat · 7am to 7pm</div>
            <a href="tel:08080942210" style={{ fontFamily: t.hFont, fontSize: 84, lineHeight: 1, color: t.primaryInk, textDecoration:'none', display:'block', letterSpacing: -2, fontWeight: 500 }}>0808 094 2210</a>
            <p style={{ fontSize: 15, color:'rgba(255,255,255,.85)', marginTop: 18, maxWidth: 480 }}>
              Free, no-pressure quote in plain English. Or send us a couple of photos by WhatsApp — we&rsquo;ll come back with a ballpark within a day.
            </p>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap: 10 }}>
            <a style={{ background: t.primaryInk, color: t.primary, fontFamily: t.bFont, fontWeight: 600, padding: '16px 20px', borderRadius: t.radiusSm, textAlign:'center', textDecoration:'none', fontSize: 15, cursor:'pointer' }}>WhatsApp Fin · 07700 900 211</a>
            <a style={{ background:'transparent', color: t.primaryInk, fontFamily: t.bFont, fontWeight: 600, padding: '16px 20px', borderRadius: t.radiusSm, textAlign:'center', textDecoration:'none', fontSize: 15, border:'1px solid rgba(255,255,255,.4)', cursor:'pointer' }}>hello@finsflooring.co.uk</a>
          </div>
        </div>
      </Section>
      <Section t={t} pad="0 48px 88px">
        <div style={{ display:'grid', gridTemplateColumns:'1.1fr 1fr', gap: 48 }}>
          {formInner}
          <div>
            <Eyebrow t={t}>Where we work</Eyebrow>
            <h2 style={{ fontFamily: t.hFont, fontSize: 32, margin: '0 0 14px', color: t.ink, fontWeight: 500, letterSpacing:-.3 }}>The whole of the UK.</h2>
            <p style={{ fontSize: 14.5, color: t.body, lineHeight: 1.6 }}>We run regional teams across England, Wales and Scotland — one number for the whole job.</p>
            <UkMap t={t}/>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 10, marginTop: 18 }}>
              {['North & Scotland · Dave','Midlands · Jess','South & London · Sam','South West & Wales · Aaron'].map(r => (
                <div key={r} style={{ fontSize: 13, color: t.body, display:'flex', gap: 10, alignItems:'center' }}>
                  <span style={{ width: 6, height: 6, borderRadius:'50%', background: t.primary }}/>{r}
                </div>
              ))}
            </div>
          </div>
        </div>
      </Section>
      <Footer t={t}/>
    </div>
  );
}

function inputStyle(t, error) {
  return {
    background: t.bg, border: `1px solid ${error ? '#C44A1E' : t.line}`,
    borderRadius: t.radiusSm, padding: '12px 14px', fontFamily: t.bFont,
    fontSize: 14, color: t.ink, lineHeight: 1.5, outline: 'none',
    transition: 'border-color .15s ease', boxShadow: error ? '0 0 0 3px rgba(196,74,30,.12)' : 'none',
    resize: 'vertical',
  };
}

// =============================================================
// Site app — real URLs, real navigation, no design-tool chrome
// =============================================================

const PATH_TO_PAGE = { '/': 'Home', '/home': 'Home', '/services': 'Services', '/gallery': 'Gallery', '/about': 'About', '/contact': 'Contact' };
const PAGE_TO_PATH = { Home: '/', Services: '/services', Gallery: '/gallery', About: '/about', Contact: '/contact' };

function pageFromLocation() {
  const path = window.location.pathname.toLowerCase().replace(/\/+$/, '') || '/';
  return PATH_TO_PAGE[path] || 'Home';
}

function FinsFlooringApp() {
  const [page, setPage] = React.useState(pageFromLocation);
  const [isMobile, setIsMobile] = React.useState(() =>
    typeof window !== 'undefined' && window.matchMedia('(max-width: 820px)').matches
  );

  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 820px)');
    const onMq = (e) => setIsMobile(e.matches);
    mq.addEventListener ? mq.addEventListener('change', onMq) : mq.addListener(onMq);

    const onPop = () => setPage(pageFromLocation());
    window.addEventListener('popstate', onPop);

    return () => {
      mq.removeEventListener ? mq.removeEventListener('change', onMq) : mq.removeListener(onMq);
      window.removeEventListener('popstate', onPop);
    };
  }, []);

  React.useEffect(() => {
    document.title = page === 'Home'
      ? "Fin's Flooring — Supply, prep & install nationwide"
      : `${page} · Fin's Flooring`;
  }, [page]);

  const router = React.useMemo(() => ({
    page,
    go: (to) => {
      if (to === 'Trade') to = 'Services';
      if (!PAGES.includes(to)) return;
      if (to === page) { window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
      setPage(to);
      window.history.pushState({}, '', PAGE_TO_PATH[to]);
      window.scrollTo(0, 0);
    },
  }), [page]);

  // Click delegation — inline CTAs ("Get a quote", "See our work →", etc.) route via this.
  const onClickRoot = (ev) => {
    const el = ev.target.closest('button, a');
    if (!el || el.type === 'submit') return;
    const txt = (el.textContent || '').trim().toLowerCase();
    const tests = [
      ['Gallery',  ['see our work', 'see full gallery', 'all →', 'view gallery']],
      ['Contact',  ['call now', 'call 0808', 'whatsapp', 'request callback', 'request a callback', 'get a quote', 'get a free quote', 'talk to fin', 'free quote']],
      ['Services', ['explore laminate', 'explore lvt', 'explore carpet', 'trade enquiries', 'explore →']],
      ['About',    ['meet our installers', 'about fin']],
    ];
    for (const [target, phrases] of tests) {
      if (phrases.some(p => txt.includes(p))) {
        router.go(target);
        ev.preventDefault();
        return;
      }
    }
  };

  const t = THEME;

  const renderPage = () => {
    if (isMobile) {
      if (page === 'Home')     return <MobileHome t={t}/>;
      if (page === 'Services') return <MobileServices t={t}/>;
      if (page === 'Gallery')  return <InteractiveMobileGallery t={t}/>;
      if (page === 'About')    return <MobileAbout t={t}/>;
      if (page === 'Contact')  return <InteractiveContact t={t} mobile/>;
    }
    if (page === 'Home')     return <DesktopHome t={t}/>;
    if (page === 'Services') return <DesktopServices t={t}/>;
    if (page === 'Gallery')  return <InteractiveDesktopGallery t={t}/>;
    if (page === 'About')    return <DesktopAbout t={t}/>;
    if (page === 'Contact')  return <InteractiveContact t={t}/>;
    return null;
  };

  return (
    <RouterProvider value={router}>
      <div onClick={onClickRoot} style={{ minHeight: '100vh', background: t.bg }}>
        <PageTransition page={page + (isMobile ? '-m' : '-d')}>
          {renderPage()}
        </PageTransition>
      </div>
    </RouterProvider>
  );
}

// Fade-in on page change
function PageTransition({ page, children }) {
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    setShown(false);
    const id = requestAnimationFrame(() => setShown(true));
    return () => cancelAnimationFrame(id);
  }, [page]);
  return (
    <div style={{
      opacity: shown ? 1 : 0,
      transition: 'opacity .25s ease',
    }}>{children}</div>
  );
}

Object.assign(window, { FinsFlooringApp });
