// ServiceTemplate — single renderer used by every non-flagship service page.
// Reads slug from URL, then uses SERVICES_DATA + SERVICE_CONTENT + ServiceHero.

const { useState: useStateSt, useEffect: useEffectSt } = React;

function ServicePage() {
  const i18n = window.__useI18n();
  const t = i18n.t;
  const lang = i18n.lang;
  const H = window.SERVICES_HELPERS || {};
  // Pull slug from filename
  const slug = (location.pathname.split('/').pop() || '').replace(/\.html$/, '');
  const data = window.SERVICES_DATA;
  const service = data.services.find(s => s.slug === slug);
  // Per-service rich content. The content file may expose `_es` overlays
  // alongside the English source — pickContent returns a translated copy when
  // available so the renderer doesn't have to know which fields are localized.
  const rawContent = window.SERVICE_CONTENT[slug];
  const content = (typeof window.pickServiceContent === 'function')
    ? window.pickServiceContent(rawContent, lang, slug)
    : rawContent;
  const division = service && data.divisions.find(d => d.id === service.division);
  const serviceName = H.svcName ? H.svcName(service) : (service && service.name);
  const divisionLabel = H.divLabel ? H.divLabel(division) : (division && division.label);

  useEffectSt(() => {
    if (division) applyAccent(window.__PAGE_ACCENT_OVERRIDE || division.accent);
    // Reveal on mount
    requestAnimationFrame(() => {
      document.querySelectorAll('.reveal').forEach(el => el.classList.add('in'));
    });
    // Cursor glow
    const glow = document.getElementById('cursorGlow');
    if (glow) {
      const onMove = (e) => {
        glow.style.left = e.clientX + 'px';
        glow.style.top  = e.clientY + 'px';
        glow.style.setProperty('--glow-intensity', 0.7);
      };
      window.addEventListener('mousemove', onMove);
      return () => window.removeEventListener('mousemove', onMove);
    }
  }, []);

  if (!service || !content) {
    return (
      <div style={{ padding: 64, textAlign: 'center', color: '#475467' }}>
        {t('tmpl.notfound')} <code>{slug}</code>
      </div>
    );
  }

  const h = content.hero;
  // Pages with taller, more vertical hero visuals need the left column to anchor
  // at the top instead of centering — otherwise dead space opens above the video.
  const isTallHero = slug === 'd2c-fulfillment' || slug === 'wholesale-fulfillment' || slug === 'buyers-consolidation';

  const statsBlock = h.stats && (
    <div className="reveal delay-5" style={{ display: 'grid',
      gridTemplateColumns: `repeat(${h.stats.length}, 1fr)`, gap: 0,
      borderTop: '1px solid #eaecf0',
      marginTop: isTallHero ? 0 : 44,
      paddingTop: isTallHero ? 20 : 24,
      maxWidth: isTallHero ? 'none' : 560 }}>
      {h.stats.map((s, i) => (
        <div key={i} style={{ paddingLeft: i > 0 ? 20 : 0,
          paddingRight: 12,
          borderLeft: i > 0 ? '1px solid #eaecf0' : 'none',
          minWidth: 0 }}>
          <div style={{ fontSize: 19, fontWeight: 600,
            letterSpacing: '-0.015em', color: '#0B1220',
            fontVariantNumeric: 'tabular-nums',
            whiteSpace: 'nowrap', overflow: 'hidden',
            textOverflow: 'ellipsis', lineHeight: 1.15 }}>{s.value}</div>
          <div style={{ fontSize: 11.5, color: '#667085', marginTop: 6,
            letterSpacing: '0.005em', fontWeight: 500 }}>{s.label}</div>
        </div>
      ))}
    </div>
  );

  return (
    <>
      {window.MobileTopBar && <window.MobileTopBar homeHref="../Homepage.html"/>}
      <ServiceNav currentSlug={slug}/>

      {/* ——— Mobile hero */}
      {window.ServiceMobileHero && (
        <div className="mobile-only">
          <window.ServiceMobileHero slug={slug} division={division} hero={h} icon={service.icon}/>
        </div>
      )}

      {/* ——— Desktop Hero */}
      <section data-desktop-hero className="desktop-only" style={{ position: 'relative', overflow: 'hidden',
        background: 'linear-gradient(120deg, #D8E5F6 0%, #E4EEF9 28%, #F0F5FB 55%, #F9FBFE 80%, #ffffff 100%)',
        borderBottom: '1px solid #eef0f3' }}>
        {/* Top-right accent glow (existing) */}
        <div aria-hidden style={{ position: 'absolute', top: -200, right: -200,
          width: 700, height: 700, borderRadius: '50%', filter: 'blur(140px)',
          background: 'radial-gradient(circle, var(--glow-color) 0%, transparent 70%)',
          pointerEvents: 'none' }}/>
        {/* Bottom-left accent glow — balances the top-right on the opposite diagonal */}
        <div aria-hidden style={{ position: 'absolute', bottom: -220, left: -220,
          width: 640, height: 640, borderRadius: '50%', filter: 'blur(150px)',
          background: 'radial-gradient(circle, var(--glow-color) 0%, transparent 70%)',
          opacity: 0.75, pointerEvents: 'none' }}/>
        {/* Dot grid — strongest on the left, masked diagonally so it dissolves before the photo */}
        <div aria-hidden style={{ position: 'absolute', inset: 0,
          backgroundImage: 'radial-gradient(circle, rgba(24, 70, 176, 0.22) 1.1px, transparent 1.4px)',
          backgroundSize: '22px 22px',
          WebkitMaskImage: 'linear-gradient(110deg, rgba(0,0,0,0.95) 0%, rgba(0,0,0,0.75) 25%, rgba(0,0,0,0.45) 45%, rgba(0,0,0,0.15) 60%, rgba(0,0,0,0) 72%)',
          maskImage: 'linear-gradient(110deg, rgba(0,0,0,0.95) 0%, rgba(0,0,0,0.75) 25%, rgba(0,0,0,0.45) 45%, rgba(0,0,0,0.15) 60%, rgba(0,0,0,0) 72%)',
          pointerEvents: 'none' }}/>
        {/* Diagonal accent stripe — low-opacity light-sweep behind the headline */}
        <div aria-hidden style={{ position: 'absolute', inset: 0,
          background: 'linear-gradient(115deg, transparent 6%, rgba(24, 70, 176, 0.07) 20%, rgba(24, 70, 176, 0.11) 28%, rgba(24, 70, 176, 0.07) 36%, transparent 52%)',
          pointerEvents: 'none' }}/>
        <div style={{ position: 'relative', maxWidth: 1600, margin: '0 auto',
          padding: isTallHero ? '20px 64px 32px' : '32px 64px 64px', zIndex: 2 }}>
          <div className="reveal" style={{ marginBottom: isTallHero ? 16 : 28 }}>
            <Breadcrumbs division={divisionLabel} name={serviceName}/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 0.95fr',
            alignItems: isTallHero ? 'start' : 'center', gap: 64,
            minHeight: isTallHero ? 0 : 520 }}>
            <div style={{ alignSelf: isTallHero ? 'start' : 'center' }}>
              <div className="reveal delay-1" style={{ display: 'inline-flex',
                alignItems: 'center', gap: 8, padding: '6px 12px',
                background: 'var(--accent-soft, #EFF6FF)',
                border: '1px solid var(--accent-light, #BFDBFE)',
                borderRadius: 9999, fontSize: 12, fontWeight: 600,
                color: 'var(--accent-dark, #1846B0)' }}>
                <Icon name={service.icon} size={13}/>
                {h.kicker || content.kicker}
              </div>
              <h1 className="reveal delay-2" style={{ margin: '24px 0 20px',
                fontSize: 76, lineHeight: 1.02, fontWeight: 700,
                letterSpacing: '-0.035em', color: '#0B1220' }}>
                {h.title}{h.title ? <br/> : null}
                <span style={{ color: 'var(--accent-dark, #1846B0)' }}>{h.titleAccent}</span>
              </h1>
              <p className="reveal delay-3" style={{ margin: 0, fontSize: 19,
                lineHeight: 1.55, color: '#475467', maxWidth: 560,
                letterSpacing: '-0.005em' }}>{h.lead}</p>
              <div className="reveal delay-4" style={{ display: 'flex', gap: 12, marginTop: 36 }}>
                <Button variant="primary" iconAfter="arrowRight"
                  onClick={() => window.__abgsCTA && window.__abgsCTA.openQuote(
                    'service-hero-quote', { svc: slug }
                  )}>
                  {t('tmpl.cta.quote')}
                </Button>
                <Button variant="ghost"
                  onClick={() => window.__abgsCTA && window.__abgsCTA.openContact(
                    'service-hero-talk',
                    { intent: 'specialist', topic: serviceName || null }
                  )}>
                  {t('tmpl.cta.specialist')}
                </Button>
              </div>
              {!isTallHero && statsBlock}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 28,
              marginTop: isTallHero ? 52 : 0 }}>
              <div className="reveal delay-3">
                <ServiceHero slug={slug} icon={service.icon} accent={window.__PAGE_ACCENT_OVERRIDE || division.accent}/>
              </div>
              {isTallHero && statsBlock}
            </div>
          </div>
        </div>
      </section>

      {/* ——— What's included */}
      {content.included && (
        <section style={{ background: '#fff' }}>
          <div style={{ maxWidth: 1600, margin: '0 auto', padding: '72px 64px 104px' }}>
            <div style={{ marginBottom: 56 }}>
              <SectionHeader kicker={t('tmpl.included.kicker')}
                title={t('tmpl.included.title', { svc: (serviceName || '').toLowerCase() })}
                lead={t('tmpl.included.lead')}/>
            </div>
            <IncludedGrid items={content.included}/>
          </div>
        </section>
      )}

      {/* ——— Lane/Rate Table (when provided) */}
      {content.lanes && (
        <section style={{ background: '#F8FAFD' }}>
          <div style={{ maxWidth: 1600, margin: '0 auto', padding: '104px 64px' }}>
            <div style={{ marginBottom: 48 }}>
              <SectionHeader kicker={t('tmpl.lanes.kicker')}
                title={content.lanes.title}
                lead={t('tmpl.lanes.lead')}/>
            </div>
            <div style={{ background: '#fff', borderRadius: 16, border: '1px solid #eaecf0',
              overflow: 'hidden' }}>
              <div style={{ display: 'grid',
                gridTemplateColumns: '80px 1.2fr 80px 1.2fr 1fr 1fr 120px',
                padding: '16px 28px', borderBottom: '1px solid #eaecf0',
                background: '#f9fafb', fontSize: 11, fontWeight: 700, color: '#667085',
                letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                <div>{t('tmpl.lanes.col.code')}</div><div>{t('tmpl.lanes.col.origin')}</div><div>{t('tmpl.lanes.col.code')}</div><div>{t('tmpl.lanes.col.dest')}</div>
                <div>{t('tmpl.lanes.col.transit')}</div><div>{t('tmpl.lanes.col.rate')}</div><div style={{ textAlign: 'right' }}>{t('tmpl.lanes.col.book')}</div>
              </div>
              {content.lanes.rows.map((r, i) => (
                <div key={i} style={{ display: 'grid',
                  gridTemplateColumns: '80px 1.2fr 80px 1.2fr 1fr 1fr 120px',
                  padding: '18px 28px', borderBottom: i < content.lanes.rows.length-1 ? '1px solid #f2f4f7' : 'none',
                  alignItems: 'center', fontSize: 13.5, transition: 'background 180ms', cursor: 'pointer' }}
                  onMouseEnter={e => e.currentTarget.style.background = '#fafbfc'}
                  onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
                  <span style={{ fontSize: 11, fontWeight: 700, color: '#475467',
                    fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em' }}>{r[0]}</span>
                  <span style={{ color: '#0B1220', fontWeight: 600 }}>{r[1]}</span>
                  <span style={{ fontSize: 11, fontWeight: 700, color: '#475467',
                    fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em' }}>{r[2]}</span>
                  <span style={{ color: '#0B1220', fontWeight: 600 }}>{r[3]}</span>
                  <span style={{ color: '#475467', fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>{r[4]}</span>
                  <span style={{ color: '#0B1220', fontWeight: 700, fontFamily: 'JetBrains Mono, monospace',
                    fontSize: 14 }}>{r[5]}</span>
                  <span style={{ textAlign: 'right' }}>
                    <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--accent-dark)',
                      display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                      {t('tmpl.lanes.col.book')} <Icon name="arrowRight" size={12}/>
                    </span>
                  </span>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* ——— How it works */}
      {content.steps && (
        <section style={{ background: '#fff' }}>
          <div style={{ maxWidth: 1600, margin: '0 auto', padding: '104px 64px' }}>
            <div style={{ marginBottom: 72, textAlign: 'center' }}>
              <SectionHeader kicker={t('tmpl.steps.kicker')} align="center"
                title={t('tmpl.steps.title')}
                lead={t('tmpl.steps.lead')}/>
            </div>
            <HowItWorks steps={content.steps}/>
          </div>
        </section>
      )}

      {/* ——— FAQ */}
      {content.faq && (
        <section style={{ background: '#F8FAFD' }}>
          <div style={{ maxWidth: 1000, margin: '0 auto', padding: '104px 64px' }}>
            <div style={{ marginBottom: 48, textAlign: 'center' }}>
              <SectionHeader kicker={t('tmpl.faq.kicker')} align="center"
                title={t('tmpl.faq.title')}
                lead={t('tmpl.faq.lead', { svc: (serviceName || '').toLowerCase() })}/>
            </div>
            <FAQ items={content.faq}/>
          </div>
        </section>
      )}

      {/* ——— Related services */}
      {content.related && (
        <section style={{ background: '#fff' }}>
          <div style={{ maxWidth: 1600, margin: '0 auto', padding: '104px 64px' }}>
            <RelatedServices currentSlug={slug} relatedSlugs={content.related}/>
          </div>
        </section>
      )}

      <DivisionCTA divisionId={service.division}/>
      <ServiceFooter/>
      {window.MobileTabBar && <window.MobileTabBar current="services"/>}
    </>
  );
}

window.ServicePage = ServicePage;
