/* ============================================================
   Tectus — routed page renderer. Reads window.ROUTES[route]
   and composes the page from declarative blocks.
   ============================================================ */
const { Button: RPButton, Eyebrow: RPEyebrow, Badge: RPBadge, Card: RPCard } = window.TectusDesignSystem_c42b34;

/* ---------- hero aside visuals (optional flavor) ---------- */
function AsideVisual({ kind }) {
  if (kind === 'mock') return <HeroMock />;
  if (kind === 'go') return <GoPhone />;
  return null;
}
function GoPhone() {
  const jobs = [
    { t: 'Event security · Pier 27', m: '6 personnel · 19:30', s: 'Accepted', tone: 'success' },
    { t: 'Mobile patrol · Bayfront', m: '4 checkpoints', s: 'En route', tone: 'gold' },
    { t: 'Executive · Mason St', m: '2 agents · armed', s: 'New', tone: 'info' },
  ];
  const TM = { success: ['var(--color-success-fg)', 'var(--color-success-soft)', 'var(--color-success)'], gold: ['var(--color-primary-light)', 'var(--color-primary-soft)', 'var(--color-primary)'], info: ['var(--color-info-fg)', 'var(--color-info-soft)', 'var(--color-info)'] };
  return (
    <div style={{ maxWidth: 320, margin: '0 auto', background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 32, padding: 12, boxShadow: 'var(--shadow-xl)' }}>
      <div style={{ background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 22, overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 18px 12px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><img src={asset('markWhite', 'assets/tectus-mark-white.webp')} alt="" style={{ height: 15 }} /><span style={{ fontSize: 13, fontWeight: 700, letterSpacing: '0.12em' }}>GO</span></div>
          <span style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', color: 'var(--color-success-fg)', display: 'inline-flex', gap: 5, alignItems: 'center' }}><span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--color-success)' }} />On shift</span>
        </div>
        <div style={{ padding: '0 14px 16px' }}>
          <div style={{ fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 700, margin: '4px 4px 10px' }}>Today · 3 jobs</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            {jobs.map((j) => { const t = TM[j.tone]; return (
              <div key={j.t} style={{ padding: '11px 12px', background: 'var(--color-surface-2)', border: '1px solid var(--color-border)', borderRadius: 12 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'center' }}>
                  <span style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{j.t}</span>
                  <span style={{ flex: '0 0 auto', fontSize: 10, fontWeight: 600, color: t[0], background: t[1], padding: '3px 8px', borderRadius: 999 }}>{j.s}</span>
                </div>
                <div style={{ fontSize: 11, color: 'var(--color-text-faint)', marginTop: 4 }}>{j.m}</div>
              </div>
            ); })}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- not found ---------- */
function NotFound() {
  return (
    <section className="wrap" style={{ padding: '120px 40px', textAlign: 'center' }}>
      <PEyebrow tone="gold">404</PEyebrow>
      <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'clamp(32px, 5vw, 56px)', letterSpacing: '-0.03em', margin: '18px 0 14px' }}>Page not found</h1>
      <p style={{ fontSize: 18, color: 'var(--color-text-muted)', maxWidth: 460, margin: '0 auto 28px', lineHeight: 1.6 }}>The page you’re looking for doesn’t exist. Head back to the platform overview to find what you need.</p>
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
        <a href="#/"><RPButton variant="primary" size="lg" iconRight={<Icon name="arrow-right" size={17} />}>Back to home</RPButton></a>
        <a href="#/services"><RPButton variant="secondary" size="lg">Browse services</RPButton></a>
      </div>
    </section>
  );
}

/* Consistent CTAs across every page — matches the global header. */
const STD_PRIMARY = 'Book a Demo';
const STD_SECONDARY = 'Get Quote';

/* ---------- main renderer ---------- */
function RoutedPage({ route }) {
  // blog post detail: route like "blog/<slug>"
  if (route.indexOf('blog/') === 0) {
    const slug = route.slice(5);
    if (slug && window.BlogPost) {
      window.scrollTo({ top: 0, behavior: 'auto' });
      return <window.BlogPost slug={slug} />;
    }
  }
  // service detail: route like "services/<slug>" — use CMS content when available
  if (route.indexOf('services/') === 0 && window.ServiceDetail) {
    const slug = route.slice(9);
    if (slug && (window.SERVICES_DETAIL || []).some((s) => s.slug === slug)) {
      window.scrollTo({ top: 0, behavior: 'auto' });
      return <window.ServiceDetail slug={slug} />;
    }
  }
  // collaboration detail: route like "collaborations/<slug>"
  if (route.indexOf('collaborations/') === 0 && window.CollabDetail) {
    const slug = route.slice(15);
    if (slug && (window.COLLABS || []).some((x) => x.slug === slug)) {
      window.scrollTo({ top: 0, behavior: 'auto' });
      return <window.CollabDetail slug={slug} />;
    }
  }

  // guide detail: route like "guides/<slug>"
  if (route.indexOf('guides/') === 0 && window.GuideDetail) {
    const slug = route.slice(7);
    if (slug && (window.GUIDES || []).some((x) => x.slug === slug)) {
      window.scrollTo({ top: 0, behavior: 'auto' });
      return <window.GuideDetail slug={slug} />;
    }
  }

  const data = (window.ROUTES || {})[route];
  useEffect(() => {
    if (data) document.title = (data.metaTitle || data.h1) + ' | Tectus';
    window.scrollTo({ top: 0, behavior: 'auto' });
    return () => { document.title = 'Tectus — Physical security, delivered faster. When it matters most.'; };
  }, [route]);

  if (!data) return <NotFound />;

  // bespoke redesigned overview pages take over the full render
  const Custom = (window.CUSTOM_PAGES || {})[route];
  if (Custom) return <Custom data={data} />;

  const isForm = data.kind === 'form';
  const isLogin = data.kind === 'login';

  return (
    <div>
      <PageHero
        group={data.group} groupHref={data.groupHref} title={data.title}
        eyebrow={data.eyebrow} h1={data.h1} sub={data.sub}
        primary={STD_PRIMARY} secondary={STD_SECONDARY}
        aside={data.aside ? <AsideVisual kind={data.aside} /> : null}
      />

      {data.intro && <ProseSection {...data.intro} />}
      {data.sections && data.sections.map((s, i) => <ProseSection key={i} {...s} />)}

      {/* in-house demo booking form */}
      {route === 'demo' && (
        <section className="wrap" style={{ padding: '40px 40px 80px', maxWidth: 1060 }}>
          <Reveal>
            <DemoScheduler />
          </Reveal>
        </section>
      )}

      {/* form layout */}
      {isForm && route !== 'demo' && (
        <section className="wrap tt-form-wrap" style={{ padding: '56px 40px 72px', display: 'grid', gridTemplateColumns: data.formSide ? '1.25fr 0.75fr' : '1fr', gap: 48, alignItems: 'start', maxWidth: data.formSide ? 1180 : 760 }}>
          <Reveal><LeadForm variant={data.formVariant} /></Reveal>
          {data.formSide && (
            <Reveal delay={100}>
              <div style={{ position: 'sticky', top: 92 }}>
                <div style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 700, marginBottom: 18 }}>{data.formSide.label}</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                  {data.formSide.items.map((it) => (
                    <div key={it.t} style={{ display: 'flex', gap: 13, alignItems: 'flex-start' }}>
                      <span style={{ flex: '0 0 auto', width: 38, height: 38, borderRadius: 'var(--radius-md)', background: 'var(--color-primary-soft)', border: '1px solid rgba(212,175,55,0.24)', color: 'var(--color-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={it.icon} size={18} /></span>
                      <div>
                        <div style={{ fontSize: 14.5, fontWeight: 600, marginBottom: 2 }}>{it.t}</div>
                        <div style={{ fontSize: 13, color: 'var(--color-text-faint)', lineHeight: 1.5 }}>{it.d}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </Reveal>
          )}
        </section>
      )}

      {/* contact special: form + channels */}
      {data.kind === 'contact' && (
        <section className="wrap tt-form-wrap" style={{ padding: '56px 40px 72px', display: 'grid', gridTemplateColumns: '1.25fr 0.75fr', gap: 48, alignItems: 'start', maxWidth: 1180 }}>
          <Reveal><ContactForm /></Reveal>
          <Reveal delay={100}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {data.channels.map((c) => (
                <div key={c.t} style={{ display: 'flex', gap: 13, alignItems: 'flex-start', padding: '16px 18px', background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-lg)' }}>
                  <span style={{ flex: '0 0 auto', width: 40, height: 40, borderRadius: 'var(--radius-md)', background: 'var(--color-surface-3)', border: '1px solid var(--color-border)', color: 'var(--color-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={c.icon} size={18} /></span>
                  <div>
                    <div style={{ fontSize: 14.5, fontWeight: 600 }}>{c.t}</div>
                    <div style={{ fontSize: 13, color: 'var(--color-text-faint)', lineHeight: 1.5, marginTop: 2 }}>{c.d}</div>
                    <a href={c.href} style={{ fontSize: 13.5, color: 'var(--color-primary-light)', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 6 }} className="tt-arrow-link">{c.link} <Icon name="arrow-right" size={13} /></a>
                  </div>
                </div>
              ))}
            </div>
          </Reveal>
        </section>
      )}

      {data.kind === 'vendor' && (
        <section className="wrap" style={{ padding: '56px 40px 72px', maxWidth: 820 }}><Reveal><VendorForm /></Reveal></section>
      )}
      {isLogin && (
        <section className="wrap" style={{ padding: '40px 40px 96px', display: 'flex', justifyContent: 'center' }}><Reveal style={{ width: '100%' }}><VendorLogin /></Reveal></section>
      )}

      {data.stats && <StatStrip stats={data.stats} />}
      {data.features && <FeatureGrid {...data.features} />}
      {data.steps && <StepRail {...data.steps} />}
      {data.listing && <ListingGrid {...data.listing} />}
      {data.legal && <LegalDoc {...data.legal} />}
      {data.faq && <FAQBlock {...data.faq} />}
      {data.cta && <CTABand {...data.cta} primary={STD_PRIMARY} secondary={STD_SECONDARY} />}
    </div>
  );
}

Object.assign(window, { RoutedPage, NotFound, GoPhone });
