/* ============================================================
   Tectus — scroll-pinned "How it works" (step-synced visuals)
   + continuous service marquee. Motion patterns adapted into the
   Tectus dark design system (original visuals & content).
   ============================================================ */
const { Eyebrow: HWEyebrow, Badge: HWBadge, Button: HWButton } = window.TectusDesignSystem_c42b34;
const { STORE_LINKS } = window;

const HIW_STEPS = [
  { n: '01', t: 'Submit request details', d: 'Set time, location, armed or unarmed preference, personnel, and special notes — a complete request in minutes.' },
  { n: '02', t: 'Match with vetted vendors', d: 'Your request is matched to licensed vendors with the right credentials, ranked by fit and availability.' },
  { n: '03', t: 'Coordinate through the platform', d: 'Confirm details, message the vendor, and align on every requirement in one shared thread.' },
  { n: '04', t: 'Track', d: 'Follow status from assigned to on site to completed — every step logged and audit-ready.' },
];

/* ---------- shared panel chrome ---------- */
function HiwPanel({ title, right, children }) {
  return (
    <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-xl)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '15px 20px', borderBottom: '1px solid var(--color-divider)', background: 'var(--color-chrome)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <img src={asset('markWhite', 'assets/tectus-mark-white.webp')} alt="" style={{ height: 15 }} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>{title}</span>
        </div>
        {right}
      </div>
      <div style={{ padding: 20, flex: 1, display: 'flex', flexDirection: 'column', gap: 13 }}>{children}</div>
    </div>
  );
}
function HiwField({ icon, label, value, mono }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 700, marginBottom: 6 }}>
        <Icon name={icon} size={12} />{label}
      </div>
      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--color-text)', fontFamily: mono ? 'var(--font-mono)' : 'var(--font-sans)' }}>{value}</div>
    </div>
  );
}

/* ---------- visual 1 — request ---------- */
function VisualRequest() {
  return (
    <HiwPanel title="New request" right={<HWBadge tone="neutral">Draft</HWBadge>}>
      <HiwField icon="map-pin" label="Location" value="Pier 27 Gala · San Francisco" />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <HiwField icon="calendar" label="Date" value="Tonight" />
        <HiwField icon="clock" label="Window" value="19:30 – 01:00" mono />
      </div>
      <div>
        <div style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 700, marginBottom: 7 }}>Requirement</div>
        <div style={{ display: 'grid', gridAutoFlow: 'column', gridAutoColumns: '1fr', gap: 4, padding: 4, background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)' }}>
          <div style={{ textAlign: 'center', padding: '8px 0', fontSize: 13, fontWeight: 600, color: 'var(--color-text-muted)' }}>Unarmed</div>
          <div style={{ textAlign: 'center', padding: '8px 0', fontSize: 13, fontWeight: 600, color: 'var(--color-primary-light)', background: 'var(--color-surface-3)', border: '1px solid rgba(212,175,55,0.4)', borderRadius: 'var(--radius-sm)' }}>Armed</div>
        </div>
      </div>
      <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 14, borderTop: '1px solid var(--color-divider)' }}>
        <div>
          <div style={{ fontSize: 10.5, color: 'var(--color-text-faint)' }}>Estimated</div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 20, fontWeight: 700 }}>$2,100</div>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, height: 40, padding: '0 18px', borderRadius: 'var(--radius-md)', background: 'var(--color-primary)', color: 'var(--color-on-primary)', fontSize: 13.5, fontWeight: 600 }}>Submit request <Icon name="arrow-right" size={15} color="var(--color-on-primary)" /></span>
      </div>
    </HiwPanel>
  );
}

/* ---------- visual 2 — match ---------- */
const CANDIDATES = [
  { in: 'SV', name: 'Sentinel Vetted', meta: 'Executive · Armed', match: '98%', best: true },
  { in: 'AP', name: 'Apex Protection', meta: 'Event · Armed', match: '94%', best: false },
  { in: 'GL', name: 'Guardline Security', meta: 'Patrol · Unarmed', match: '89%', best: false },
];
function VisualMatch() {
  return (
    <HiwPanel title="Matching" right={<HWBadge tone="gold" dot>3 candidates</HWBadge>}>
      {CANDIDATES.map((c) => (
        <div key={c.name} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 13px', background: c.best ? 'linear-gradient(160deg, rgba(212,175,55,0.10), transparent 70%), var(--color-surface-2)' : 'var(--color-surface-2)', border: '1px solid ' + (c.best ? 'rgba(212,175,55,0.32)' : 'var(--color-border)'), borderRadius: 'var(--radius-md)' }}>
          <span style={{ flex: '0 0 auto', width: 38, height: 38, borderRadius: '50%', background: 'var(--color-surface-3)', border: '1px solid var(--color-border)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, color: 'var(--color-text-muted)' }}>{c.in}</span>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
              <span style={{ fontSize: 13.5, fontWeight: 600 }}>{c.name}</span>
              {c.best && <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--color-primary-light)' }}>Best match</span>}
            </div>
            <div style={{ display: 'flex', gap: 6, marginTop: 5 }}>
              {['Licensed', 'Insured'].map((b) => (
                <span key={b} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10, color: 'var(--color-success-fg)' }}><Icon name="check" size={11} color="var(--color-success)" />{b}</span>
              ))}
              <span style={{ fontSize: 11, color: 'var(--color-text-faint)' }}>· {c.meta}</span>
            </div>
          </div>
          <span style={{ flex: '0 0 auto', fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 700, color: c.best ? 'var(--color-primary-light)' : 'var(--color-text-muted)' }}>{c.match}</span>
        </div>
      ))}
      <div style={{ marginTop: 'auto', paddingTop: 4 }}>
        <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, height: 42, borderRadius: 'var(--radius-md)', background: 'var(--color-primary)', color: 'var(--color-on-primary)', fontSize: 13.5, fontWeight: 600 }}>Assign Sentinel Vetted <Icon name="user-check" size={15} color="var(--color-on-primary)" /></span>
      </div>
    </HiwPanel>
  );
}

/* ---------- visual 3 — coordinate ---------- */
function VisualCoordinate() {
  return (
    <HiwPanel title="Coordination" right={<span style={{ fontSize: 11, color: 'var(--color-text-faint)', fontFamily: 'var(--font-mono)' }}>RQ-2048</span>}>
      <div style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
        <span style={{ flex: '0 0 auto', width: 28, height: 28, borderRadius: '50%', background: 'var(--color-surface-3)', border: '1px solid var(--color-border)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700, color: 'var(--color-text-muted)' }}>SV</span>
        <div style={{ background: 'var(--color-surface-2)', border: '1px solid var(--color-border)', borderRadius: '4px 14px 14px 14px', padding: '10px 13px', fontSize: 13, color: 'var(--color-text)', lineHeight: 1.45, maxWidth: '78%' }}>Two close-protection agents confirmed. We'll arrive 30 min ahead for a site sweep.</div>
      </div>
      <div style={{ display: 'flex', gap: 9, alignItems: 'flex-start', flexDirection: 'row-reverse' }}>
        <span style={{ flex: '0 0 auto', width: 28, height: 28, borderRadius: '50%', background: 'var(--color-primary-soft)', border: '1px solid rgba(212,175,55,0.3)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, color: 'var(--color-primary-light)' }}>You</span>
        <div style={{ background: 'var(--color-primary-soft)', border: '1px solid rgba(212,175,55,0.22)', borderRadius: '14px 4px 14px 14px', padding: '10px 13px', fontSize: 13, color: 'var(--color-text)', lineHeight: 1.45, maxWidth: '78%' }}>Perfect. Point of contact is at the north entrance.</div>
      </div>
      <div style={{ marginTop: 'auto', background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', padding: '12px 14px' }}>
        <div style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 700, marginBottom: 9 }}>Requirements confirmed</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {['Access details shared', 'Dress code: business formal', 'On-site contact assigned'].map((r) => (
            <div key={r} style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13, color: 'var(--color-text)' }}><Icon name="check" size={15} color="var(--color-success)" />{r}</div>
          ))}
        </div>
      </div>
    </HiwPanel>
  );
}

/* ---------- visual 4 — track ---------- */
const TRACK = [
  { t: 'Requested', s: '19:02', state: 'done' },
  { t: 'Vendor assigned', s: '19:08', state: 'done' },
  { t: 'On site', s: '19:34', state: 'active' },
  { t: 'Completed', s: 'Est. 01:00', state: 'pending' },
];
function VisualTrack() {
  return (
    <HiwPanel title="Service status" right={<HWBadge tone="success" dot>On site</HWBadge>}>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {TRACK.map((r, i) => {
          const done = r.state === 'done', active = r.state === 'active';
          const color = done ? 'var(--color-success)' : active ? 'var(--color-primary)' : 'var(--color-text-faint)';
          return (
            <div key={r.t} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', alignSelf: 'stretch' }}>
                <span style={{ flex: '0 0 auto', width: 22, height: 22, borderRadius: '50%', border: '2px solid ' + color, background: done ? 'var(--color-success)' : active ? 'var(--color-primary-soft)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: active ? '0 0 0 4px rgba(212,175,55,0.15)' : 'none' }}>
                  {done && <Icon name="check" size={12} color="var(--color-on-primary)" />}
                  {active && <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--color-primary)' }} />}
                </span>
                {i < TRACK.length - 1 && <span style={{ width: 2, flex: 1, minHeight: 26, background: done ? 'var(--color-success)' : 'var(--color-border)' }} />}
              </div>
              <div style={{ paddingBottom: 18 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: active || done ? 'var(--color-text)' : 'var(--color-text-faint)' }}>{r.t}</div>
                <div style={{ fontSize: 11.5, color: 'var(--color-text-faint)', fontFamily: 'var(--font-mono)', marginTop: 2 }}>{r.s}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 12, borderTop: '1px solid var(--color-divider)' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12, color: 'var(--color-text-muted)' }}><Icon name="shield-check" size={14} color="var(--color-success)" />Logged & audit-ready</span>
        <span style={{ fontSize: 11.5, fontFamily: 'var(--font-mono)', color: 'var(--color-text-faint)' }}>Updated 14s ago</span>
      </div>
    </HiwPanel>
  );
}

const HIW_VISUALS = [VisualRequest, VisualMatch, VisualCoordinate, VisualTrack];

/* ---------- how it works — scroll-pinned; each scroll advances a step ---------- */
function HowItWorksPinned() {
  const [active, setActive] = useState(0);
  const [progress, setProgress] = useState(0);
  const secRef = useRef(null);
  const [inView, setInView] = useState(false);
  const DURATION = 6000; // ms per step for auto-advance

  // reveal + pause auto-advance when off-screen
  useEffect(() => {
    const el = secRef.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { threshold: 0.35 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // auto-advance the active tab with a progress bar
  useEffect(() => {
    if (!inView) return;
    let raf = 0, start = performance.now();
    const tick = (now) => {
      const p = Math.min(1, (now - start) / DURATION);
      setProgress(p);
      if (p >= 1) { start = now; setActive((a) => (a + 1) % HIW_STEPS.length); }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [inView, active]);

  const pick = (i) => { setActive(i); setProgress(0); };
  const V = HIW_VISUALS[active];

  return (
    <section id="how-it-works" ref={secRef} className="tt-hiw" style={{ background: 'var(--color-surface)' }}>
      {/* desktop / tablet: Apollo-style tabbed feature layout */}
      <div className="tt-hiw-desktop wrap" style={{ padding: 'var(--section-y, 96px) 40px' }}>
        <div style={{ textAlign: 'center', maxWidth: 680, margin: '0 auto 44px' }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}><HWEyebrow tick tone="gold">How it works</HWEyebrow></div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(30px, 3.6vw, 46px)', letterSpacing: '-0.025em', lineHeight: 1.1, margin: 0, textWrap: 'balance' }}>A structured workflow, end to end</h2>
        </div>

        {/* tab row */}
        <div className="tt-hiw-tabs" style={{ display: 'grid', gridTemplateColumns: `repeat(${HIW_STEPS.length}, 1fr)`, gap: 14, marginBottom: 40 }}>
          {HIW_STEPS.map((s, i) => {
            const on = i === active;
            return (
              <button key={s.n} type="button" onClick={() => pick(i)} className="tt-hiw-tab"
                style={{ position: 'relative', textAlign: 'left', cursor: 'pointer', font: 'inherit', background: on ? 'var(--color-bg)' : 'transparent', border: '1px solid ' + (on ? 'var(--color-border-strong)' : 'var(--color-border)'), borderRadius: 'var(--radius-lg)', padding: '18px 20px 20px', overflow: 'hidden', transition: 'background 300ms, border-color 300ms' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 8 }}>
                  <span style={{ flex: '0 0 auto', width: 30, height: 30, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, background: on ? 'var(--color-primary)' : 'var(--color-surface-3)', color: on ? 'var(--color-on-primary)' : 'var(--color-text-faint)', border: on ? 'none' : '1px solid var(--color-border)', transition: 'all 300ms' }}>{s.n}</span>
                  <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(15px, 1.15vw, 17px)', fontWeight: 600, margin: 0, color: on ? 'var(--color-text)' : 'var(--color-text-muted)', lineHeight: 1.2 }}>{s.t}</h3>
                </div>
                <p style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--color-text-faint)', margin: 0 }}>{s.d}</p>
                {/* progress bar */}
                <span style={{ position: 'absolute', left: 0, bottom: 0, height: 3, width: '100%', background: 'var(--color-border)' }}>
                  <span style={{ display: 'block', height: '100%', width: on ? `${progress * 100}%` : '0%', background: 'var(--color-primary)', transition: on ? 'none' : 'width 200ms' }} />
                </span>
              </button>
            );
          })}
        </div>

        {/* large swapping visual panel */}
        <div style={{ position: 'relative', maxWidth: 760, margin: '0 auto' }}>
          <div key={active} className="tt-hiw-panel" style={{ animation: 'tt-hiw-in 500ms cubic-bezier(0.16,1,0.3,1)' }}>
            <V />
          </div>
        </div>
      </div>

      {/* mobile: stacked */}
      <div className="tt-hiw-mobile wrap" style={{ padding: '56px 20px' }}>
        <div style={{ marginBottom: 16 }}><HWEyebrow tick tone="gold">How it works</HWEyebrow></div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(24px, 7vw, 30px)', letterSpacing: '-0.02em', lineHeight: 1.1, margin: '0 0 28px', textWrap: 'balance' }}>A structured workflow, end to end</h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
          {HIW_STEPS.map((s, i) => {
            const V = HIW_VISUALS[i];
            return (
              <div key={s.n} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ flex: '0 0 auto', width: 30, height: 30, borderRadius: '50%', background: 'var(--color-primary-soft)', border: '1px solid rgba(212,175,55,0.3)', color: 'var(--color-primary-light)', fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{s.n}</span>
                  <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(17px, 5vw, 20px)', fontWeight: 600, margin: 0 }}>{s.t}</h3>
                </div>
                <p style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--color-text-muted)', margin: '0 0 4px', paddingLeft: 42 }}>{s.d}</p>
                <div className="tt-hiw-mvis"><V /></div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ---------- service marquee ---------- */
function Marquee() {
  const items = ['Executive protection', 'Event security', 'Mobile patrol', 'Retail security', 'Alarm response', 'Corporate security', 'Fire watch'];
  const loop = [...items, ...items];
  return (
    <div style={{ borderBottom: '1px solid var(--color-border)', background: 'var(--color-bg)', overflow: 'hidden', padding: '18px 0' }}>
      <div className="tt-marquee">
        {loop.map((t, i) => (
          <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 28, fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 600 }}>
            {t}
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--color-primary)', flex: '0 0 auto' }} />
          </span>
        ))}
      </div>
    </div>
  );
}

/* ---------- video section (placeholder) ---------- */
function VideoSection() {
  const videoRef = useRef(null);
  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) v.play().catch(() => {});
      else v.pause();
    }, { threshold: 0.4 });
    obs.observe(v);
    return () => obs.disconnect();
  }, []);
  return (
    <section id="watch" className="wrap" style={{ padding: '92px 40px 8px' }}>
      <Reveal>
        <div style={{ textAlign: 'center', maxWidth: 680, margin: '0 auto 40px' }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}><HWEyebrow tick tone="gold">Watch</HWEyebrow></div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(29px, 3.6vw, 44px)', letterSpacing: '-0.025em', lineHeight: 1.08, margin: '0 0 14px', textWrap: 'balance' }}>See Tectus in action</h2>
          <p style={{ fontSize: 17.5, lineHeight: 1.6, color: 'var(--color-text-muted)', margin: 0 }}>A short overview of how coverage gets requested, matched, and tracked — start to finish.</p>
        </div>
        <div style={{ borderRadius: 'var(--radius-xl)', overflow: 'hidden', border: '1px solid var(--color-border)', boxShadow: 'var(--shadow-lg)', aspectRatio: '16 / 9', background: '#000' }}>
          <video ref={videoRef} src="https://pub-e7380c1d8c954ad99281ca20ff4a1273.r2.dev/tectus-promo.mp4" controls muted playsInline preload="metadata" loop style={{ width: '100%', height: '100%', display: 'block' }} />
        </div>
      </Reveal>
    </section>
  );
}

Object.assign(window, { HowItWorksPinned, Marquee, VideoSection });

/* ============================================================
   App download section — both apps, with store buttons.
   ============================================================ */
function AppDownload() {
  const apps = [
    {
      name: 'Tectus', tag: 'For clients', mark: 'assets/tectus-icon-white.webp', markId: 'iconWhite', store: 'tectus',
      desc: 'Request and manage licensed security coverage. Submit requests by time, location, and requirement, then track every job to completion.',
      points: ['Request coverage in minutes', 'Live status from match to completion', 'Coordinate with vendors in one place'],
      label: 'Tectus',
    },
    {
      name: 'Tectus GO', tag: 'For vendors', mark: 'assets/tectus-go-icon-white.webp', markId: 'goIconWhite', store: 'go',
      desc: 'The operations app for approved security vendors and personnel. Accept jobs, assign teams, and update status from the field.',
      points: ['Accept and manage job requests', 'Assign personnel and schedules', 'Update job status on site'],
      label: 'Tectus GO',
    },
  ];
  return (
    <section id="apps" style={{ position: 'relative', overflow: 'hidden', borderTop: '1px solid var(--color-border)', borderBottom: '1px solid var(--color-border)', background: 'var(--color-surface)' }}>
      <div aria-hidden="true" style={{ position: 'absolute', top: -160, left: '50%', transform: 'translateX(-50%)', width: 720, height: 420, background: 'radial-gradient(ellipse, rgba(212,175,55,0.07), transparent 66%)', pointerEvents: 'none' }} />
      <div className="wrap" style={{ padding: '96px 40px', position: 'relative' }}>
        <Reveal>
          <div style={{ textAlign: 'center', maxWidth: 680, margin: '0 auto 52px' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}><HWEyebrow tick tone="gold">Get the apps</HWEyebrow></div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(29px, 3.6vw, 44px)', letterSpacing: '-0.025em', lineHeight: 1.08, margin: '0 0 14px', textWrap: 'balance' }}>Tectus, on every device</h2>
            <p style={{ fontSize: 17.5, lineHeight: 1.6, color: 'var(--color-text-muted)', margin: 0 }}>Two connected apps — one for requesting coverage, one for running it. Download whichever fits your role.</p>
          </div>
        </Reveal>
        <div className="tt-split-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
          {apps.map((a, i) => (
            <Reveal key={a.name} delay={i * 100}>
              <div style={{ background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-xl)', padding: 40, height: '100%', display: 'flex', flexDirection: 'column' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
                  <span style={{ width: 52, height: 52, borderRadius: 'var(--radius-md)', background: 'var(--color-surface-3)', border: '1px solid var(--color-border)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 10 }}><img src={asset(a.markId, a.mark)} alt={a.name} style={{ maxWidth: '100%', maxHeight: '100%', display: 'block' }} /></span>
                  <div className="tt-app-head" style={{ display: 'flex', alignItems: 'center', gap: 11, flexWrap: 'wrap' }}>
                    <span className="tt-app-title" style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700, letterSpacing: '-0.01em', whiteSpace: 'nowrap' }}>{a.name}</span>
                    <span style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 700, padding: '4px 9px', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-pill)', whiteSpace: 'nowrap' }}>{a.tag}</span>
                  </div>
                </div>
                <p style={{ fontSize: 15.5, color: 'var(--color-text-muted)', lineHeight: 1.6, margin: '0 0 22px' }}>{a.desc}</p>
                <ul style={{ listStyle: 'none', margin: '0 0 28px', padding: 0, display: 'flex', flexDirection: 'column', gap: 13 }}>
                  {a.points.map((p) => (
                    <li key={p} style={{ display: 'flex', gap: 11, alignItems: 'flex-start', fontSize: 14.5, color: 'var(--color-text)', lineHeight: 1.45 }}>
                      <Icon name="check" size={17} color="var(--color-primary)" style={{ marginTop: 1, flex: '0 0 auto' }} />{p}
                    </li>
                  ))}
                </ul>
                <div style={{ marginTop: 'auto', paddingTop: 24, borderTop: '1px solid var(--color-divider)' }}>
                  <div style={{ fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 700, marginBottom: 12 }}>Download {a.name}</div>
                  <StoreButtons appleHref={STORE_LINKS[a.store].apple} googleHref={STORE_LINKS[a.store].google} label={a.label} block />
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { AppDownload });

/* ============================================================
   Coverage map — supported-city availability (Google Places + embed)
   ============================================================ */
const GMAPS_KEY = 'AIzaSyDfxORl_-2husdM0RaSUa9fMKhULhzv5Mc';
const LOCATION_URL_BASE = 'https://tectusapp.com/location';
const US_STATES = { AL:'alabama', AK:'alaska', AZ:'arizona', AR:'arkansas', CA:'california', CO:'colorado', CT:'connecticut', DE:'delaware', DC:'district of columbia', FL:'florida', GA:'georgia', HI:'hawaii', ID:'idaho', IL:'illinois', IN:'indiana', IA:'iowa', KS:'kansas', KY:'kentucky', LA:'louisiana', ME:'maine', MD:'maryland', MA:'massachusetts', MI:'michigan', MN:'minnesota', MS:'mississippi', MO:'missouri', MT:'montana', NE:'nebraska', NV:'nevada', NH:'new hampshire', NJ:'new jersey', NM:'new mexico', NY:'new york', NC:'north carolina', ND:'north dakota', OH:'ohio', OK:'oklahoma', OR:'oregon', PA:'pennsylvania', RI:'rhode island', SC:'south carolina', SD:'south dakota', TN:'tennessee', TX:'texas', UT:'utah', VT:'vermont', VA:'virginia', WA:'washington', WV:'west virginia', WI:'wisconsin', WY:'wyoming' };

function covNorm(v) {
  return (v || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[’']/g, '').replace(/[^a-z0-9\s,-]/g, ' ').replace(/\s+/g, ' ').trim();
}
function covPhrase(hay, phrase) {
  if (!hay || !phrase) return false;
  const esc = phrase.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  return new RegExp(`(^|[\\s,])${esc}([\\s,]|$)`, 'i').test(hay);
}
function covParseState(q) {
  for (const [code, name] of Object.entries(US_STATES)) {
    if (covPhrase(q, code.toLowerCase()) || covPhrase(q, name)) return code.toLowerCase();
  }
  return '';
}
function covScore(item, rawQuery) {
  const q = covNorm(rawQuery); if (!q) return 0;
  const city = covNorm(item.city), state = covNorm(item.state);
  const stateName = covNorm(US_STATES[item.state] || '');
  const labelComma = covNorm(`${item.city}, ${item.state}`);
  const labelName = covNorm(`${item.city}, ${stateName}`);
  const hasCity = covPhrase(q, city);
  const hasCode = covPhrase(q, state);
  const hasName = stateName ? covPhrase(q, stateName) : false;
  const parsed = covParseState(q);
  if (q === labelComma) return 5000;
  if (q === labelName) return 4950;
  if (q === city) return 4900;
  if (q.includes(labelComma)) return 4800;
  if (q.includes(labelName)) return 4750;
  if (hasCity && (hasCode || hasName)) return 4700;
  if (hasCity) { if (parsed && parsed !== state) return 0; return 4200; }
  return 0;
}

let __gmapsPromise = null;
function loadGmaps() {
  if (window.google && window.google.maps && window.google.maps.importLibrary) return Promise.resolve();
  if (__gmapsPromise) return __gmapsPromise;
  __gmapsPromise = new Promise((resolve, reject) => {
    const s = document.createElement('script');
    s.src = `https://maps.googleapis.com/maps/api/js?key=${GMAPS_KEY}&loading=async&v=weekly&libraries=places`;
    s.async = true; s.defer = true;
    s.onload = () => resolve(); s.onerror = () => reject(new Error('gmaps load'));
    document.head.appendChild(s);
  });
  return __gmapsPromise;
}

function CoverageMap() {
  const LOCS = window.TECTUS_LOCATIONS || [];
  const [query, setQuery] = useState('');
  const [searched, setSearched] = useState('');
  const [showSug, setShowSug] = useState(false);
  const [gsug, setGsug] = useState([]);
  const [ready, setReady] = useState(false);

  useEffect(() => { let c = false; loadGmaps().then(() => !c && setReady(true)).catch(() => {}); return () => { c = true; }; }, []);

  const tq = query.trim();

  // local supported-city suggestions
  const localSug = useMemo(() => {
    const q = covNorm(tq); if (!q) return [];
    return LOCS.filter((i) => covNorm(i.city).startsWith(q) || covNorm(`${i.city}, ${i.state}`).includes(q))
      .slice(0, 6).map((i) => ({ id: `l-${i.city}-${i.state}`, label: `${i.city}, ${i.state}`, kind: 'Supported location' }));
  }, [tq]);

  // google place suggestions
  useEffect(() => {
    let c = false;
    async function run() {
      if (!ready || tq.length < 3) { setGsug([]); return; }
      try {
        const { AutocompleteSuggestion } = await window.google.maps.importLibrary('places');
        const res = await AutocompleteSuggestion.fetchAutocompleteSuggestions({ input: tq, includedRegionCodes: ['us'] });
        if (c) return;
        setGsug((res && res.suggestions || []).slice(0, 5).map((s, i) => {
          const p = s.placePrediction;
          return { id: (p && p.placeId) || `g-${i}`, label: (p && p.text && p.text.text) || tq, kind: 'Google suggestion' };
        }));
      } catch (e) { if (!c) setGsug([]); }
    }
    const t = setTimeout(run, 180);
    return () => { c = true; clearTimeout(t); };
  }, [ready, tq]);

  const sugg = useMemo(() => {
    const seen = new Set(); const out = [];
    [...localSug, ...gsug].forEach((s) => { const k = covNorm(s.label); if (!seen.has(k)) { seen.add(k); out.push(s); } });
    return out.slice(0, 8);
  }, [localSug, gsug]);

  const results = useMemo(() => {
    if (!searched) return [];
    return LOCS.map((i) => ({ ...i, score: covScore(i, searched) })).filter((i) => i.score >= 4200)
      .sort((a, b) => b.score - a.score || `${a.city}, ${a.state}`.localeCompare(`${b.city}, ${b.state}`)).slice(0, 4);
  }, [searched]);

  const primary = results[0] || null;
  const embedQ = primary ? `${primary.city}, ${primary.state}, USA` : (searched || 'United States');
  const mapSrc = `https://www.google.com/maps/embed/v1/place?key=${GMAPS_KEY}&q=${encodeURIComponent(embedQ)}&zoom=${searched ? 12 : 4}`;

  const runSearch = (v) => { const n = (v != null ? v : query).trim(); setQuery(n); setSearched(n); setShowSug(false); };

  return (
    <section id="coverage" style={{ background: 'var(--color-surface)', borderTop: '1px solid var(--color-border)', borderBottom: '1px solid var(--color-border)' }}>
      <div className="wrap" style={{ padding: '96px 40px', maxWidth: 1000 }}>
        <Reveal>
          <div style={{ textAlign: 'center', maxWidth: 640, margin: '0 auto 36px' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}><HWEyebrow tick tone="gold">Coverage</HWEyebrow></div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(29px, 3.6vw, 44px)', letterSpacing: '-0.025em', lineHeight: 1.08, margin: '0 0 14px', textWrap: 'balance' }}>Check Tectus availability</h2>
            <p style={{ fontSize: 17.5, lineHeight: 1.6, color: 'var(--color-text-muted)', margin: 0 }}>Enter a city or full address. Search suggestions appear as you type.</p>
          </div>
        </Reveal>

        <Reveal delay={80}>
          {/* search */}
          <form onSubmit={(e) => { e.preventDefault(); runSearch(); }} style={{ position: 'relative', marginBottom: 18, zIndex: 20 }}>
            <span style={{ position: 'absolute', left: 18, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-text-faint)', display: 'inline-flex' }}><Icon name="search" size={18} /></span>
            <input value={query}
              onChange={(e) => { setQuery(e.target.value); setShowSug(Boolean(e.target.value.trim())); if (!e.target.value.trim()) setSearched(''); }}
              onFocus={() => { if (tq) setShowSug(true); }}
              onBlur={() => setTimeout(() => setShowSug(false), 150)}
              placeholder="Enter city, ZIP code, or address" autoComplete="off"
              style={{ width: '100%', height: 56, padding: '0 60px 0 48px', background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', color: 'var(--color-text)', font: 'inherit', fontSize: 15.5, outline: 'none' }}
              onFocusCapture={(e) => (e.target.style.borderColor = 'var(--color-primary)')} />
            <button type="submit" aria-label="Search coverage" style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)', width: 38, height: 38, borderRadius: 'var(--radius-md)', background: 'var(--color-primary-soft)', border: '1px solid rgba(212,175,55,0.32)', color: 'var(--color-primary-light)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="arrow-up-right" size={18} /></button>

            {showSug && tq && sugg.length > 0 && (
              <div style={{ position: 'absolute', top: 62, left: 0, right: 0, zIndex: 30, background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', overflow: 'hidden', boxShadow: 'var(--shadow-lg)' }}>
                {sugg.map((s) => (
                  <button key={s.id} type="button" onMouseDown={(e) => { e.preventDefault(); runSearch(s.label); }}
                    className="tt-cov-sug" style={{ width: '100%', textAlign: 'left', padding: '12px 16px', border: 'none', borderBottom: '1px solid var(--color-divider)', background: 'transparent', color: 'var(--color-text)', cursor: 'pointer', font: 'inherit' }}>
                    <div style={{ fontSize: 14.5 }}>{s.label}</div>
                    <div style={{ fontSize: 12, color: 'var(--color-text-faint)', marginTop: 2 }}>{s.kind}</div>
                  </button>
                ))}
              </div>
            )}
          </form>

          {/* map */}
          <div style={{ borderRadius: 'var(--radius-xl)', overflow: 'hidden', border: '1px solid var(--color-border)', boxShadow: 'var(--shadow-lg)', background: 'var(--color-bg)' }}>
            <iframe title={searched ? `Map of ${searched}` : 'Map of United States'} src={mapSrc} width="100%" height="440" style={{ display: 'block', border: 0 }} loading="lazy" allowFullScreen referrerPolicy="no-referrer-when-downgrade"></iframe>
          </div>

          {/* results — only after a search */}
          {searched && (
            <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {results.length > 0 ? results.map((item, idx) => (
                <div key={`${item.slug}-${idx}`} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap', padding: '18px 24px', background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-lg)' }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, color: 'var(--color-text-faint)', marginBottom: 6 }}>{searched}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                      <span style={{ fontFamily: 'var(--font-display)', fontSize: 21, fontWeight: 700 }}>{item.city}, {item.state}</span>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, height: 26, padding: '0 11px', borderRadius: 'var(--radius-pill)', background: 'var(--color-success-soft)', color: 'var(--color-success-fg)', fontSize: 12, fontWeight: 600 }}>
                        <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--color-success)' }} />Available
                      </span>
                    </div>
                    <div style={{ fontSize: 13.5, color: 'var(--color-text-muted)', marginTop: 6 }}>Coverage available in your area.</div>
                  </div>
                  <a href={`#/location/${item.slug}`}><HWButton variant="primary" size="md" iconRight={<Icon name="arrow-right" size={16} />}>View details</HWButton></a>
                </div>
              )) : (
                <div style={{ padding: '20px 24px', background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-lg)', color: 'var(--color-text-muted)', fontSize: 14.5, lineHeight: 1.6 }}>
                  This location isn’t currently supported. Try another city, or contact Tectus for availability.
                </div>
              )}
            </div>
          )}

          {/* advisor row */}
          <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap', padding: '20px 26px', background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-lg)' }}>
            <span style={{ fontSize: 15.5, color: 'var(--color-text)', fontWeight: 500 }}>Have questions about our services?</span>
            <a href="#/demo"><HWButton variant="secondary" size="md">Talk to an advisor</HWButton></a>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { CoverageMap });
