/* ============================================================
   Tectus — shared helpers, sitemap data, section primitives
   ============================================================ */
const { useState, useEffect, useRef, useCallback } = React;
/* Expose hooks globally — each text/babel script is its own scope. */
window.useState = React.useState;
window.useEffect = React.useEffect;
window.useRef = React.useRef;
window.useMemo = React.useMemo;
window.useCallback = React.useCallback;

/* Resource resolver — uses inlined blob URLs (window.__resources) when the
   page is bundled standalone, otherwise falls back to the on-disk path. */
function asset(id, path) {
  return (window.__resources && window.__resources[id]) || path;
}
window.asset = asset;

/* ---------- Lucide icon ---------- */
function Icon({ name, size = 18, color, style, strokeWidth }) {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current && window.lucide) {
      ref.current.innerHTML = '';
      const el = document.createElement('i');
      el.setAttribute('data-lucide', name);
      ref.current.appendChild(el);
      window.lucide.createIcons({
        attrs: { width: size, height: size, 'stroke-width': strokeWidth || 1.75 },
        nameAttr: 'data-lucide',
      });
    }
  }, [name, size, strokeWidth]);
  return <span ref={ref} style={{ display: 'inline-flex', lineHeight: 0, color: color || 'inherit', ...style }} />;
}

/* ---------- Reveal on scroll ---------- */
function Reveal({ children, as: Tag = 'div', delay = 0, style, className = '', ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const node = ref.current;
    if (!node) return;
    let done = false;
    const reveal = () => { if (!done) { done = true; setSeen(true); } };
    let io;
    if ('IntersectionObserver' in window) {
      io = new IntersectionObserver(
        ([e]) => { if (e.isIntersecting) { reveal(); io.disconnect(); } },
        { threshold: 0.08, rootMargin: '0px 0px -6% 0px' }
      );
      io.observe(node);
    } else {
      reveal();
    }
    // reveal immediately if already in (or near) the viewport on mount
    requestAnimationFrame(() => {
      const r = node.getBoundingClientRect();
      if (r.top < (window.innerHeight || 800) + 40 && r.bottom > -40) reveal();
    });
    // safety fallback — never leave content hidden
    const fallback = setTimeout(reveal, 600);
    return () => { io && io.disconnect(); clearTimeout(fallback); };
  }, []);
  return (
    <Tag
      ref={ref}
      className={`reveal ${seen ? 'in' : ''} ${className}`}
      style={{ transitionDelay: seen ? `${delay}ms` : '0ms', ...style }}
      {...rest}
    >
      {children}
    </Tag>
  );
}

/* ---------- Section header ---------- */
function SectionHead({ eyebrow, title, sub, center, light, maxWidth }) {
  const { Eyebrow } = window.TectusDesignSystem_c42b34;
  return (
    <div style={{ maxWidth: maxWidth || (center ? 720 : 780), margin: center ? '0 auto 56px' : '0 0 48px', textAlign: center ? 'center' : 'left' }}>
      <div style={{ display: 'flex', justifyContent: center ? 'center' : 'flex-start', marginBottom: 18 }}>
        <Eyebrow tick tone="gold">{eyebrow}</Eyebrow>
      </div>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(29px, 3.6vw, 44px)', letterSpacing: '-0.025em', lineHeight: 1.08, margin: '0 0 16px', textWrap: 'balance' }}>
        {title}
      </h2>
      {sub && (
        <p style={{ fontSize: 17.5, lineHeight: 1.62, color: 'var(--color-text-muted)', margin: 0, maxWidth: center ? 640 : 620, marginLeft: center ? 'auto' : 0, marginRight: center ? 'auto' : 0, textWrap: 'pretty' }}>
          {sub}
        </p>
      )}
    </div>
  );
}

/* ---------- Gold keyword wrapper ---------- */
function Gold({ children }) {
  return <span className="tt-goldtext" style={{ color: 'var(--color-primary-light)' }}>{children}</span>;
}
function Faint({ children }) {
  return <span style={{ color: 'var(--color-text-muted)' }}>{children}</span>;
}

/* ============================================================
   SITEMAP — exact per spec. Each group renders a mega-menu.
   ============================================================ */
const SITEMAP = {
  Platform: {
    href: '#/platform',
    intro: 'The operating layer for physical security on demand — request, coordinate, and track licensed coverage in one place.',
    columns: [
      {
        heading: 'Platform',
        links: [
          { label: 'Tectus', href: '#/tectus', desc: 'For businesses requesting coverage', icon: 'building-2' },
          { label: 'Tectus GO', href: '#/tectus-go', desc: 'For licensed vendors & personnel', icon: 'smartphone' },
          { label: 'How It Works', href: '#/how-it-works', desc: 'The end-to-end workflow', icon: 'route' },
        ],
      },
      {
        heading: 'Capabilities',
        links: [
          { label: 'Features', href: '#/features', desc: 'Everything in the platform', icon: 'layers' },
          { label: 'Use Cases', href: '#/use-cases', desc: 'Coverage for every request', icon: 'briefcase' },
          { label: 'Compliance', href: '#/compliance', desc: 'Verification & accountability', icon: 'badge-check' },
          { label: 'Demo', href: '#/demo', desc: 'See the platform live', icon: 'play' },
        ],
      },
    ],
    feature: { eyebrow: 'New', title: 'Tectus GO is live', desc: 'The operations app for approved vendor teams.', cta: 'See Tectus GO', href: '#/tectus-go' },
  },
  Services: {
    href: '#/services',
    intro: 'One workflow across the services businesses ask for most — each staffed by licensed, vetted vendors.',
    columns: [
      {
        heading: 'Coverage types',
        links: [
          { label: 'Executive & VIP Protection', href: '#/services/executive-protection', desc: 'Close protection & secure transport', icon: 'user-round-check' },
          { label: 'Event Security', href: '#/services/event-security', desc: 'Access control & crowd coordination', icon: 'ticket' },
          { label: 'Mobile Patrol', href: '#/services/mobile-patrol', desc: 'Scheduled & on-call patrol', icon: 'route' },
          { label: 'Retail Security', href: '#/services/retail-security', desc: 'Loss-prevention & front-of-house', icon: 'store' },
        ],
      },
      {
        heading: 'More services',
        links: [
          { label: 'Alarm Response', href: '#/services/alarm-response', desc: 'Rapid verified response', icon: 'bell-ring' },
          { label: 'Corporate Security', href: '#/services/corporate-security', desc: 'Facility & front-desk coverage', icon: 'building' },
          { label: 'Fire Watch', href: '#/services/fire-watch', desc: 'Continuous monitored watch', icon: 'flame' },
        ],
      },
    ],
    feature: { eyebrow: 'Get started', title: 'Request coverage', desc: 'Set time, location, and requirement — get matched in minutes.', cta: 'Get a quote', href: '#/get-quote', primary: true, secondary: { label: 'Book Now', href: '#/book-now' } },
  },
  Partners: {
    href: '#/partners',
    intro: 'Licensed, insured security companies can apply to join the Tectus network through a structured onboarding process.',
    columns: [
      {
        heading: 'For vendors',
        links: [
          { label: 'Become a Vendor', href: '#/become-a-vendor', desc: 'Apply to the network', icon: 'user-plus' },
          { label: 'Vendor Standards', href: '#/vendor-standards', desc: 'What we require', icon: 'clipboard-check' },
        ],
      },
      {
        heading: 'Resources',
        links: [
          { label: 'How Partnering Works', href: '#/how-partnering-works', desc: 'The onboarding process', icon: 'route' },
          { label: 'Partner FAQ', href: '#/partner-faq', desc: 'Common vendor questions', icon: 'help-circle' },
        ],
      },
    ],
    feature: { eyebrow: 'Tectus GO', title: 'Run ops on Tectus GO', desc: 'Manage jobs, assignments, and status in one app.', cta: 'Become a vendor', href: '#/become-a-vendor' },
  },
  Resources: {
    href: '#/resources',
    intro: 'Practical guidance and operational insight for teams coordinating licensed security coverage.',
    columns: [
      {
        heading: 'Library',
        links: [
          { label: 'Blog', href: '#/blog', desc: 'Latest from Tectus', icon: 'newspaper' },
          { label: 'Guides', href: '#/guides', desc: 'Step-by-step playbooks', icon: 'book-open' },
        ],
      },
      {
        heading: 'Learn',
        links: [
          { label: 'Insights', href: '#/insights', desc: 'Operational analysis', icon: 'line-chart' },
          { label: 'FAQ', href: '#/faq', desc: 'Answers to common questions', icon: 'help-circle' },
        ],
      },
    ],
    feature: { eyebrow: 'Guide', title: 'Planning event coverage', desc: 'A practical checklist for security at scale.', cta: 'Read the guide', href: '#/guides' },
  },
  About: {
    href: '#/about',
    intro: 'Tectus is building the operating layer for physical security on demand.',
    columns: [
      {
        heading: 'Company',
        links: [
          { label: 'About Tectus', href: '#/about', desc: 'Our mission and approach', icon: 'info' },
          { label: 'Collaborations', href: '#/collaborations', desc: 'Who we work with', icon: 'users' },
          { label: 'Contact', href: '#/contact', desc: 'Get in touch', icon: 'mail' },
        ],
      },
      {
        heading: 'Legal',
        links: [
          { label: 'Privacy Policy', href: '#/privacy', desc: 'How we handle data', icon: 'shield' },
          { label: 'Terms and Conditions', href: '#/terms', desc: 'Terms & conditions', icon: 'file-text' },
        ],
      },
    ],
    feature: { eyebrow: 'Talk to us', title: 'Book a live demo', desc: 'See how Tectus simplifies security coordination.', cta: 'Book a Demo', href: '#/demo', primary: true },
  },
};

const NOTIF_MESSAGES = [
  { tag: 'Live', text: 'Physical security, delivered faster. When it matters most.', cta: 'Book now', href: '#/book-now' },
  { tag: 'New', text: 'Now available: Tectus GO for approved vendor operations.', cta: 'See Tectus GO', href: '#/tectus-go' },
  { tag: 'Demo', text: 'Book a live demo to see how Tectus simplifies security coordination.', cta: 'Book a Demo', href: '#/demo' },
];

/* ---------- App-store buttons ---------- */
function StoreGlyph({ store, size = 22 }) {
  if (store === 'apple') {
    return (
      <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" style={{ flex: '0 0 auto' }}>
        <path d="M17.543 12.34c-.02-2.18 1.78-3.23 1.86-3.28-.1-.15-1.07-1.86-3.07-2.05-1.31-.13-2.55.77-3.21.77-.66 0-1.68-.75-2.77-.73-1.42.02-2.74.83-3.47 2.1-1.48 2.57-.38 6.37 1.06 8.46.7 1.02 1.54 2.17 2.63 2.13 1.06-.04 1.46-.68 2.74-.68 1.27 0 1.64.68 2.76.66 1.14-.02 1.86-1.04 2.56-2.07.81-1.19 1.14-2.34 1.16-2.4-.03-.01-2.22-.85-2.24-3.38zM15.45 5.4c.58-.71.98-1.69.87-2.67-.84.03-1.86.56-2.46 1.26-.54.62-1.01 1.62-.89 2.58.94.07 1.9-.47 2.48-1.17z" />
      </svg>
    );
  }
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" style={{ flex: '0 0 auto' }}>
      <path d="M4.05 3.02c-.34.18-.55.53-.55.93v16.1c0 .4.21.75.55.93l9.3-9-9.3-8.96z" opacity="0.95" />
      <path d="M16.9 9.78l-2.85-1.64-2.4 2.34 2.4 2.34 2.86-1.65c.66-.38.66-1.01-.01-1.39z" />
      <path d="M13.35 10.48L4.5 1.9c.13-.06.28-.09.43-.07.18.02.35.08.5.17l9.27 5.34-1.35 3.14z" opacity="0.85" />
      <path d="M13.35 13.52l-8.85 8.58c.13.06.28.09.43.07.18-.02.35-.08.5-.17l9.27-5.34-1.35-3.14z" opacity="0.7" />
    </svg>
  );
}
function StoreButton({ store = 'apple', href = '#', label, compact, iconOnly, block }) {
  const top = store === 'apple' ? 'Download on the' : 'Get it on';
  const big = store === 'apple' ? 'App Store' : 'Google Play';
  const target = (href && href !== '#') ? { target: '_blank', rel: 'noopener noreferrer' } : {};
  if (iconOnly) {
    return (
      <a href={href} {...target} aria-label={`${big}${label ? ' — ' + label : ''}`} className="tt-store-btn" title={big}
         style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 40, height: 40, background: 'var(--color-surface-2)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', color: 'var(--color-text)', transition: 'border-color var(--dur-base), background var(--dur-base)' }}>
        <StoreGlyph store={store} size={19} />
      </a>
    );
  }
  return (
    <a href={href} {...target} aria-label={`${big}${label ? ' — ' + label : ''}`} className="tt-store-btn"
       style={{ display: 'inline-flex', alignItems: 'center', justifyContent: block ? 'center' : 'flex-start', flex: block ? 1 : '0 0 auto', gap: 11, height: compact ? 46 : 54, padding: compact ? '0 15px' : '0 20px', background: 'var(--color-surface-2)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', color: 'var(--color-text)', transition: 'border-color var(--dur-base), background var(--dur-base)' }}>
      <StoreGlyph store={store} size={compact ? 20 : 23} />
      <span style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.05, textAlign: 'left', minWidth: 0 }}>
        <span style={{ fontSize: 9.5, letterSpacing: '0.05em', color: 'var(--color-text-faint)', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>{top}</span>
        <span style={{ fontSize: compact ? 14 : 16, fontWeight: 600, marginTop: 2, fontFamily: 'var(--font-display)', whiteSpace: 'nowrap' }}>{big}</span>
      </span>
    </a>
  );
}
function StoreButtons({ href = '#', appleHref, googleHref, label, stack, compact, iconOnly, block }) {
  return (
    <div style={{ display: 'flex', gap: iconOnly ? 8 : 10, flexDirection: (stack && !iconOnly) ? 'column' : 'row', flexWrap: block ? 'nowrap' : 'wrap', alignItems: 'stretch' }}>
      <StoreButton store="apple" href={appleHref || href} label={label} compact={compact} iconOnly={iconOnly} block={block} />
      <StoreButton store="google" href={googleHref || href} label={label} compact={compact} iconOnly={iconOnly} block={block} />
    </div>
  );
}

/* ---------- App store links ---------- */
const STORE_LINKS = {
  tectus: {
    apple: 'https://apps.apple.com/us/app/tectus/id6758456782',
    google: 'https://play.google.com/store/apps/details?id=com.tectusapp.client&hl=en',
  },
  go: {
    apple: 'https://apps.apple.com/ph/app/tectus-go/id6757723756',
    google: 'https://play.google.com/store/apps/details?id=com.tectusapp.go',
  },
};

/* ---------- App download toggle — "Download now" + lockup tabs + icon badges ---------- */
const APP_ROLES = [
  { key: 'tectus', name: 'Tectus', logo: 'assets/tectus-pill-mark.webp', logoId: 'pillMark', label: 'Tectus' },
  { key: 'go', name: 'Tectus GO', logo: 'assets/tectus-go-pill-mark.webp', logoId: 'pillGoMark', label: 'Tectus GO' },
];
function AppDownloadToggle() {
  const [role, setRole] = useState('tectus');
  const active = APP_ROLES.find((r) => r.key === role) || APP_ROLES[0];
  return (
    <div style={{ maxWidth: 320 }}>
      <div style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--color-primary-light)', fontWeight: 700, marginBottom: 11 }}>Download now</div>
      {/* segmented toggle — lockup only */}
      <div role="tablist" aria-label="Choose app" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, padding: 5, background: 'var(--color-surface-2)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-pill)' }}>
        {APP_ROLES.map((r) => {
          const on = r.key === role;
          return (
            <button key={r.key} type="button" role="tab" aria-selected={on} aria-label={r.name} onClick={() => setRole(r.key)}
              style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '11px 12px', borderRadius: 'var(--radius-pill)', border: 'none', cursor: 'pointer', font: 'inherit',
                background: on ? 'var(--color-primary)' : 'transparent',
                transition: 'background var(--dur-base) var(--ease-standard)' }}>
              <img src={asset(r.logoId, r.logo)} alt={r.name} style={{ height: 17, width: 'auto', display: 'block', filter: on ? 'brightness(0)' : 'none', opacity: on ? 0.9 : 0.95 }} />
            </button>
          );
        })}
      </div>
      {/* icon-only store badges side by side */}
      <div style={{ marginTop: 14 }}>
        <StoreButtons appleHref={STORE_LINKS[role].apple} googleHref={STORE_LINKS[role].google} label={active.label} iconOnly />
      </div>
    </div>
  );
}

/* ---------- Socials ---------- */
const SOCIALS = [
  { name: 'facebook', href: 'https://www.facebook.com/people/Tectus/61573895185075/', label: 'Facebook' },
  { name: 'linkedin', href: 'https://www.linkedin.com/company/tectusprotection/posts/?feedView=all', label: 'LinkedIn' },
  { name: 'mail', href: 'mailto:support@tectusapp.com', label: 'Email' },
  { name: 'phone', href: 'tel:+18332832887', label: 'Call 833-2TECTUS' },
];
function Socials({ size = 17 }) {
  return (
    <div style={{ display: 'flex', gap: 10 }}>
      {SOCIALS.map((s) => {
        const ext = /^https?:/.test(s.href);
        return (
        <a key={s.name} href={s.href} aria-label={s.label} title={s.label} className="tt-social"
           {...(ext ? { target: '_blank', rel: 'noopener noreferrer' } : {})}
           style={{ width: 40, height: 40, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--color-surface-2)', border: '1px solid var(--color-border)', color: 'var(--color-text-muted)', transition: 'color var(--dur-base), border-color var(--dur-base)' }}>
          <Icon name={s.name} size={size} />
        </a>
        );
      })}
    </div>
  );
}

/* ---------- AutoplayVideo — muted autoplay when scrolled into view ---------- */
function AutoplayVideo({ src, style }) {
  const ref = useRef(null);
  useEffect(() => {
    const v = ref.current;
    if (!v) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { v.play().catch(() => {}); }
        else { v.pause(); }
      });
    }, { threshold: 0.4 });
    io.observe(v);
    return () => io.disconnect();
  }, []);
  return (
    <video ref={ref} muted playsInline loop controls preload="metadata"
      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', display: 'block', objectFit: 'cover', ...style }}>
      <source src={src} type="video/mp4" />
    </video>
  );
}

Object.assign(window, { Icon, Reveal, SectionHead, Gold, Faint, SITEMAP, NOTIF_MESSAGES, StoreButton, StoreButtons, AppDownloadToggle, Socials, STORE_LINKS, AutoplayVideo });
