/* global React */
// Trakkables.com — marketing header + hero, About, News & Updates and contact modals.
// Text comes from content/site.json and content/press.json (edited at /admin).
function MktIcon({ name, size = 18 }) {
  return <i data-lucide={name} style={{ width: size, height: size }} />;
}

// Master corporate lockup — "Trakkables Software Systems"
function BrandMark({ dark = false, height = 36 }) {
  const ink = dark ? '#fff' : '#161616';
  return (
    <svg height={height} viewBox="0 0 300 74" fill="none" xmlns="http://www.w3.org/2000/svg"
      role="img" aria-label="Trakkables Software Systems" style={{ display: 'block' }}>
      <rect x="2" y="2" width="296" height="48" rx="24" fill={dark ? 'none' : '#fff'} stroke={ink} strokeWidth="3" />
      <text x="150" y="34" textAnchor="middle" fontFamily="'Saira Semi Condensed',sans-serif" fontWeight="800" fontStyle="italic" fontSize="30" letterSpacing="0.5" fill={ink}>TRAKKABLES</text>
      <g stroke="#0D9488" strokeWidth="3" strokeLinecap="round">
        <line x1="90" y1="42" x2="134" y2="42" />
        <line x1="210" y1="42" x2="166" y2="42" />
      </g>
      <path d="M134 38 L143 42 L134 46 Z" fill="#0D9488" />
      <path d="M166 38 L157 42 L166 46 Z" fill="#0D9488" />
      <text x="150" y="68" textAnchor="middle" fontFamily="'Saira Semi Condensed',sans-serif" fontWeight="700" fontSize="12" letterSpacing="5" fill="#0D9488">SOFTWARE SYSTEMS</text>
    </svg>
  );
}

function scrollToPortfolio() {
  const el = document.getElementById('portfolio');
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 70, behavior: 'smooth' });
}
window.scrollToPortfolio = scrollToPortfolio;

function ProductsMenu() {
  const [open, setOpen] = React.useState(false);
  const closeTimer = React.useRef(null);
  const openNow = () => { if (closeTimer.current) clearTimeout(closeTimer.current); setOpen(true); };
  const closeSoon = () => { closeTimer.current = setTimeout(() => setOpen(false), 120); };
  const linkStyle = { color: 'var(--tk-gray-300)', fontSize: 15, fontWeight: 500, textDecoration: 'none', transition: 'var(--transition-base)', cursor: 'pointer' };
  const dot = (s) => s === 'Live' ? '#2FA89A' : s === 'Waitlist' ? '#C79A2E' : '#79828D';
  return (
    <div style={{ position: 'relative' }} onMouseEnter={openNow} onMouseLeave={closeSoon}>
      <button type="button" onClick={() => setOpen((v) => !v)}
        style={{ ...linkStyle, background: 'none', border: 'none', font: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 5, padding: 0, color: open ? '#fff' : 'var(--tk-gray-300)' }}>
        Products <i data-lucide="chevron-down" style={{ width: 15, height: 15, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 0.18s' }} />
      </button>
      {open && (
        <div role="menu" style={{ position: 'absolute', top: 'calc(100% + 12px)', left: -14, minWidth: 256, background: 'rgba(24,28,33,0.98)', backdropFilter: 'blur(12px)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 14, boxShadow: '0 24px 60px rgba(0,0,0,0.45)', padding: 8, zIndex: 40 }}>
          {tkContent().products.map((p) => ({ name: p.name, href: p.href, accent: p.menuColor || p.accent })).map((p) => (
            <a key={p.name} href={p.href} target="_blank" rel="noopener" role="menuitem"
              style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 9, textDecoration: 'none', transition: 'background 0.15s' }}
              onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.06)'}
              onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: p.accent, flex: 'none' }} />
              <span style={{ color: '#fff', fontSize: 14.5, fontWeight: 600, flex: 1 }}>Trakkables {p.name}</span>
              <i data-lucide="arrow-up-right" style={{ width: 15, height: 15, color: 'var(--tk-gray-500)' }} />
            </a>
          ))}
          <div style={{ height: 1, background: 'rgba(255,255,255,0.08)', margin: '6px 8px' }} />
          <button type="button" onClick={() => { setOpen(false); scrollToPortfolio(); }}
            style={{ width: '100%', textAlign: 'left', background: 'none', border: 'none', font: 'inherit', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', borderRadius: 9, color: '#2FA89A', fontSize: 14, fontWeight: 600, transition: 'background 0.15s' }}
            onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.06)'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
            See all products <i data-lucide="arrow-right" style={{ width: 15, height: 15 }} />
          </button>
        </div>
      )}
    </div>
  );
}

function MktHeader({ sticky = true, onAbout, onPress }) {
  const { Button } = window.DesignSystem_6ce6e1;
  React.useEffect(() => { if (window.lucide) window.lucide.createIcons(); });
  const linkStyle = { color: 'var(--tk-gray-300)', fontSize: 15, fontWeight: 500, textDecoration: 'none', transition: 'var(--transition-base)', cursor: 'pointer', background: 'none', border: 'none', font: 'inherit', padding: 0 };
  return (
    <header style={{ position: sticky ? 'sticky' : 'static', top: 0, zIndex: 20, background: 'rgba(20,24,28,0.92)', backdropFilter: 'blur(10px)', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 28, padding: '12px 28px' }}>
        <img src="/assets/images/logos/trakkables-corporate-teal.png" alt="Trakkables Software Systems" style={{ height: 44, display: 'block' }} />
        <nav style={{ display: 'flex', alignItems: 'center', gap: 26, marginLeft: 16 }}>
          <ProductsMenu />
          <button type="button" onClick={onAbout} style={linkStyle} onMouseEnter={(e) => e.currentTarget.style.color = '#fff'} onMouseLeave={(e) => e.currentTarget.style.color = 'var(--tk-gray-300)'}>About</button>
          <button type="button" onClick={onPress} style={linkStyle} onMouseEnter={(e) => e.currentTarget.style.color = '#fff'} onMouseLeave={(e) => e.currentTarget.style.color = 'var(--tk-gray-300)'}>News &amp; Updates</button>
        </nav>
        <div style={{ flex: 1 }} />
      </div>
    </header>
  );
}

function MktHero({ showEyebrow = true, onContact }) {
  const { Button } = window.DesignSystem_6ce6e1;
  const hero = tkContent().site.hero;
  return (
    <section style={{ maxWidth: 1200, margin: '0 auto', padding: '88px 28px 64px', textAlign: 'center' }}>
      {showEyebrow && (
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 14px', borderRadius: 999, background: 'color-mix(in srgb, var(--color-accent) 12%, white)', color: 'var(--color-brand-hover)', fontSize: 13, fontWeight: 600, marginBottom: 24 }}>
          <MktIcon name="radar" size={15} /> {hero.eyebrow}
        </div>
      )}
      <h1 style={{ margin: '0 auto', maxWidth: 760, fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 54, lineHeight: 1.06, letterSpacing: '-0.015em', color: 'var(--text-strong)' }}>
        {hero.title}
      </h1>
      <p style={{ margin: '22px auto 0', maxWidth: 600, fontSize: 19, lineHeight: 1.55, color: 'var(--text-muted)' }}>
        {hero.subtitle}
      </p>
      <div style={{ display: 'flex', gap: 14, justifyContent: 'center', marginTop: 34 }}>
        <Button size="lg" iconRight={<MktIcon name="arrow-right" size={18} />} onClick={() => window.scrollToPortfolio && window.scrollToPortfolio()}>{hero.primaryButton}</Button>
        <Button size="lg" variant="secondary" onClick={onContact}>{hero.secondaryButton}</Button>
      </div>
    </section>
  );
}
window.MktIcon = MktIcon;
window.BrandMark = BrandMark;
window.MktHeader = MktHeader;
window.MktHero = MktHero;

function MktAboutModal({ open, onClose }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [open, onClose]);
  if (!open) return null;
  const teal = '#2FA89A';
  const about = tkContent().site.about;
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(12,16,20,0.68)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '48px 20px', overflowY: 'auto' }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="About Trakkables" style={{ position: 'relative', width: '100%', maxWidth: 720, background: '#fff', color: '#161616', borderRadius: 18, boxShadow: '0 30px 80px rgba(0,0,0,0.4)', padding: '48px 52px 44px' }}>
        <button onClick={onClose} aria-label="Close" style={{ position: 'absolute', top: 18, right: 18, width: 36, height: 36, borderRadius: 10, border: '1px solid #E1E4E8', background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#4a5158' }}><MktIcon name="x" size={18} /></button>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: "'JetBrains Mono',ui-monospace,monospace", fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: teal, marginBottom: 18 }}>
          <span style={{ width: 26, height: 2, background: teal, display: 'inline-block' }} />About Trakkables
        </div>
        <h2 style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 800, fontSize: 'clamp(30px,4.4vw,44px)', lineHeight: 1.08, letterSpacing: '-0.02em', margin: '0 0 24px', textWrap: 'balance' }}>{about.title}</h2>
        <div className="tk-about-body" style={{ display: 'flex', flexDirection: 'column', gap: 18, fontSize: 16.5, lineHeight: 1.7, color: '#3D434B' }}
          dangerouslySetInnerHTML={{ __html: tkMarkdown(about.body) }} />
        <div style={{ marginTop: 36, paddingTop: 22, borderTop: '1px solid #E1E4E8', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap', fontSize: 14, color: '#79828D' }}>
          <span style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 700, letterSpacing: '0.04em', color: '#161616' }}>{about.footerLine}</span>
          <a href={`mailto:${about.email}`} style={{ color: teal, textDecoration: 'none', fontWeight: 600 }}>{about.email}</a>
        </div>
      </div>
    </div>
  );
}
window.MktAboutModal = MktAboutModal;

function MktPressModal({ open, onClose }) {
  const [active, setActive] = React.useState(null);
  React.useEffect(() => {
    if (!open) { setActive(null); return; }
    const onKey = (e) => { if (e.key === 'Escape') { if (active) setActive(null); else onClose(); } };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    if (window.lucide) window.lucide.createIcons();
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [open, onClose, active]);
  if (!open) return null;
  const teal = '#2FA89A';
  const rel = active;
  const releases = tkContent().press.releases;
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(12,16,20,0.68)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '48px 20px', overflowY: 'auto' }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="Trakkables newsroom" style={{ position: 'relative', width: '100%', maxWidth: 720, background: '#fff', color: '#161616', borderRadius: 18, boxShadow: '0 30px 80px rgba(0,0,0,0.4)', padding: '44px 48px 40px' }}>
        <button onClick={onClose} aria-label="Close" style={{ position: 'absolute', top: 18, right: 18, width: 36, height: 36, borderRadius: 10, border: '1px solid #E1E4E8', background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#4a5158' }}><MktIcon name="x" size={18} /></button>
        {!rel ? (
          <React.Fragment>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: "'JetBrains Mono',ui-monospace,monospace", fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: teal, marginBottom: 16 }}>
              <span style={{ width: 26, height: 2, background: teal, display: 'inline-block' }} />News &amp; Updates
            </div>
            <h2 style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 800, fontSize: 34, lineHeight: 1.1, letterSpacing: '-0.01em', margin: 0 }}>Trakkables News &amp; Updates</h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginTop: 26 }}>
              {releases.map((item) => (
                <button key={item.id} type="button" onClick={() => setActive(item)} style={{ textAlign: 'left', font: 'inherit', cursor: 'pointer', width: '100%', background: '#F7F8F9', border: '1px solid #EEF0F2', borderRadius: 14, padding: '22px 24px', display: 'flex', flexDirection: 'column', gap: 11 }}>
                  <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                    <span style={{ fontFamily: "'JetBrains Mono',ui-monospace,monospace", fontSize: 11, letterSpacing: '0.1em', color: teal }}>{item.date}</span>
                    <span style={{ width: 3, height: 3, borderRadius: '50%', background: '#CDD2D8' }} />
                    <span style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 700, fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#79828D' }}>{item.category}</span>
                  </div>
                  <div style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 800, fontSize: 20, lineHeight: 1.16, color: '#161616' }}>{item.title}</div>
                  <div style={{ fontSize: 14, lineHeight: 1.6, color: '#4a5158' }}>{item.summary}</div>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontWeight: 600, fontSize: 14, color: teal, marginTop: 2 }}>Read full release <MktIcon name="arrow-right" size={15} /></span>
                </button>
              ))}
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <button type="button" onClick={() => setActive(null)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', cursor: 'pointer', font: 'inherit', color: teal, fontWeight: 600, fontSize: 13, marginBottom: 18, padding: 0 }}><MktIcon name="arrow-left" size={15} /> Back to newsroom</button>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px 12px', alignItems: 'center', fontFamily: "'JetBrains Mono',ui-monospace,monospace", fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: teal, marginBottom: 14 }}>
              <span>For Immediate Release</span><span style={{ color: '#CDD2D8' }}>·</span><span style={{ color: '#79828D' }}>{rel.date}</span>
            </div>
            <h2 style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 800, fontSize: 28, lineHeight: 1.15, letterSpacing: '-0.01em', margin: '0 0 18px' }}>{rel.title}</h2>
            <p style={{ fontSize: 15, lineHeight: 1.72, margin: '0 0 24px', color: '#2b3138' }}><strong style={{ color: '#161616' }}>{rel.location} — </strong>{rel.lead}</p>
            <h3 style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 700, fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase', color: teal, margin: '0 0 4px' }}>{rel.highlightsHeading}</h3>
            <div style={{ height: 3, width: 54, background: teal, borderRadius: 99, marginBottom: 16 }} />
            <ul style={{ listStyle: 'none', margin: '0 0 26px', padding: 0, display: 'flex', flexDirection: 'column', gap: 11 }}>
              {(rel.highlights || []).map((b) => (
                <li key={b.title} style={{ display: 'flex', gap: 11, alignItems: 'flex-start' }}>
                  <span style={{ flex: 'none', marginTop: 2, color: teal }}>▸</span>
                  <span style={{ fontSize: 14.5, lineHeight: 1.6 }}><strong style={{ color: '#262A30' }}>{b.title}</strong>{b.detail ? ` — ${b.detail}` : ''}</span>
                </li>
              ))}
            </ul>
            <blockquote style={{ margin: '0 0 24px', padding: '20px 24px', background: '#D7F0ED', borderLeft: `5px solid ${teal}`, borderRadius: '0 12px 12px 0' }}>
              <p style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 600, fontSize: 18, lineHeight: 1.42, color: '#161616', margin: '0 0 12px' }}>{rel.quote}</p>
              <footer style={{ margin: 0, fontSize: 12.5, color: '#586069' }}>— {rel.quoteBy}</footer>
            </blockquote>
            <p style={{ fontSize: 14.5, lineHeight: 1.7, margin: 0, color: '#3D434B' }}>{rel.closing}</p>
            <div style={{ marginTop: 30, paddingTop: 20, borderTop: '1px solid #E1E4E8', display: 'flex', flexWrap: 'wrap', gap: '6px 16px', alignItems: 'center', fontFamily: "'JetBrains Mono',ui-monospace,monospace", fontSize: 11, color: '#A6AEB7' }}>
              <span style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 800, letterSpacing: '0.02em', color: teal, textTransform: 'uppercase' }}>Simple. Trackable. Approved.</span>
              <span>trakkables.com · communications@trakkables.com · ###</span>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}
window.MktPressModal = MktPressModal;

function MktContactModal({ open, onClose, formUrl, title, subtitle }) {
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    if (!open) return;
    setLoading(true);
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [open, onClose]);
  if (!open) return null;
  const teal = '#2FA89A';
  const contact = tkContent().site.contact;
  const FORM_URL = formUrl || contact.formUrl;
  title = title || contact.title;
  subtitle = subtitle || contact.subtitle;
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(12,16,20,0.68)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '48px 20px', overflowY: 'auto' }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="Contact Trakkables" style={{ position: 'relative', width: '100%', maxWidth: 560, background: '#fff', color: '#161616', borderRadius: 18, boxShadow: '0 30px 80px rgba(0,0,0,0.4)', overflow: 'hidden' }}>
        <button onClick={onClose} aria-label="Close" style={{ position: 'absolute', top: 18, right: 18, width: 36, height: 36, borderRadius: 10, border: '1px solid #E1E4E8', background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#4a5158', zIndex: 2 }}><MktIcon name="x" size={18} /></button>
        <div style={{ padding: '44px 44px 20px' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: "'JetBrains Mono',ui-monospace,monospace", fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: teal, marginBottom: 14 }}>
            <span style={{ width: 26, height: 2, background: teal, display: 'inline-block' }} />Get in touch
          </div>
          <h2 style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 800, fontSize: 30, lineHeight: 1.1, letterSpacing: '-0.01em', margin: '0 0 8px' }}>{title}</h2>
          <p style={{ fontSize: 15, lineHeight: 1.6, margin: 0, color: '#4a5158' }}>{subtitle}</p>
        </div>
        <div style={{ position: 'relative', padding: '0 20px 24px', minHeight: 420 }}>
          {loading && (
            <div style={{ position: 'absolute', inset: '0 20px 24px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14, color: '#79828D' }}>
              <span style={{ width: 30, height: 30, border: `3px solid ${teal}`, borderTopColor: 'transparent', borderRadius: '50%', display: 'inline-block', animation: 'tk-spin 0.8s linear infinite' }} />
              <span style={{ fontFamily: "'Saira Semi Condensed',sans-serif", fontWeight: 600, fontSize: 14, letterSpacing: '0.04em' }}>Loading form…</span>
            </div>
          )}
          <iframe title="Contact Trakkables" src={FORM_URL} onLoad={() => setLoading(false)}
            style={{ display: 'block', width: '100%', height: 560, border: 'none', borderRadius: 12, opacity: loading ? 0 : 1, transition: 'opacity 0.25s' }} />
        </div>
      </div>
    </div>
  );
}
window.MktContactModal = MktContactModal;
