// chrome.jsx — Header, Footer, Wordmark, primitives

function Wordmark({ size = 19, onClick, variant = 'color' }) {
  // Signature logo image. `size` maps to rendered height for backwards compat.
  const h = Math.round(size * 1.5);
  const R = (typeof window !== 'undefined' && window.__resources) || {};
  const src = variant === 'white'
    ? (R.logoWhite || 'assets/criterionmd-logo-white.png')
    : (R.logoColor || 'assets/criterionmd-logo.png');
  return (
    <a href="#" onClick={(e) => { e.preventDefault(); onClick && onClick(); }}
       className="cmd-wordmark" aria-label="CriterionMD"
       style={{ display: 'inline-flex', alignItems: 'center', lineHeight: 0, flexShrink: 0 }}>
      <img src={src} alt="CriterionMD"
           style={{ height: h, width: 'auto', objectFit: 'contain', display: 'block', flexShrink: 0 }} />
    </a>
  );
}

function ArrowRight({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function Check({ size = 14, color = "currentColor" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3.5 8.5l3 3 6-7" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function Header({ route, go, authed, onLogout }) {
  const NavLink = ({ to, children }) => (
    <a href={`#${to}`} onClick={(e) => { e.preventDefault(); go(to); }}
       className={route === to ? "active" : ""}>{children}</a>
  );
  return (
    <header className="cmd-header">
      <div className="cmd-container cmd-header-inner">
        <Wordmark size={34} variant="white" onClick={() => go(authed ? 'portal' : 'home')} />
        {!authed && (
          <nav className="cmd-nav">
            <NavLink to="home">Home</NavLink>
            <SolutionsNavDropdown route={route} go={go} />
            <NavLink to="insurify">Insurify <span style={{
              fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.08em',
              padding: '2px 6px', borderRadius: 4, marginLeft: 4,
              background: 'var(--accent-tint)', color: 'var(--accent-ink)',
              border: '1px solid var(--accent-tint-2)', verticalAlign: '2px'
            }}>PUBLIC BETA</span></NavLink>
            <AboutNavDropdown route={route} go={go} />
            <ResourcesNavDropdown route={route} go={go} />
            <ContactNavDropdown route={route} go={go} />
          </nav>
        )}
        {authed && (
          <nav className="cmd-nav">
            <NavLink to="portal">Overview</NavLink>
            <a href="#insurify-app" onClick={(e) => { e.preventDefault(); go('insurify-app'); }}
               className={route === 'insurify-app' ? 'active' : ''}>Insurify</a>
            <a href="#portal-billing" onClick={(e) => { e.preventDefault(); go('portal-billing'); }}
               className={route === 'portal-billing' ? 'active' : ''}>Billing</a>
            <a href="#portal-team" onClick={(e) => { e.preventDefault(); go('portal-team'); }}
               className={route === 'portal-team' ? 'active' : ''}>Team</a>
          </nav>
        )}
        <div className="cmd-header-cta">
          {!authed && (
            <>
              <button className="btn btn-ghost" onClick={() => go('login')}>Log in</button>
            </>
          )}
          {authed && (
            <>
              <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>Dr. Marin Okafor</span>
              <div style={{
                width: 32, height: 32, borderRadius: 999,
                background: 'var(--accent)', color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 12, fontWeight: 500, letterSpacing: '.02em'
              }}>MO</div>
              <button className="btn btn-sm btn-ghost" onClick={onLogout}>Log out</button>
            </>
          )}
        </div>
      </div>
    </header>
  );
}

function Footer({ go }) {
  return (
    <footer className="cmd-footer">
      <div className="cmd-container">
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 24, flexWrap: 'wrap'
        }}>
          <Wordmark size={20} onClick={() => go('home')} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', fontSize: 13, color: 'var(--ink-3)' }}>
            <span>© 2026 CriterionMD, Inc.</span>
            <span className="mono" style={{ fontSize: 12, letterSpacing: '.06em' }}>NEW YORK, NY</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// Compact label pair used throughout
function Stat({ label, value, hint }) {
  return (
    <div>
      <div style={{ fontSize: 35, fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1, color: 'var(--accent)' }}>{value}</div>
      <div className="eyebrow" style={{ marginTop: 14 }}>{label}</div>
      {hint && <div style={{ fontSize: 15, color: 'var(--ink-3)', marginTop: 10, lineHeight: 1.5 }}>{hint}</div>}
    </div>
  );
}

// Small product logo tile for the Solutions nav dropdown. Uses ProductMark and
// PRODUCT_COLORS exported from pages-marketing.jsx (available on window at render
// time even though chrome.jsx loads first).
function ProductLogo({ k, size = 22 }) {
  const colors = (typeof window !== 'undefined' && window.PRODUCT_COLORS) || {};
  const Mark = typeof window !== 'undefined' && window.ProductMark;
  const c = colors[k] || { tile: 'var(--accent)' };
  // ScribeAware's logo is a colored image with transparency — show it on a light
  // tile (and nearly fill it) instead of the dark product tile other glyphs use.
  const isImg = k === 'notes';
  return (
    <span style={{
      width: size, height: size, borderRadius: 6, flexShrink: 0,
      background: isImg ? 'var(--paper-2)' : c.tile,
      border: isImg ? '1px solid var(--line)' : 'none',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: isImg ? 'none' : '0 1px 2px rgba(15,20,20,.18)',
      overflow: 'hidden'
    }}>
      {Mark ? <Mark k={k} size={isImg ? size - 4 : size - 8} /> : null}
    </span>
  );
}

// ── Nav dropdown (shared by Solutions and About) ─────────────────────────────
// Hover opens a panel; clicking a section either navigates directly (if the
// section has its own `route`) or expands inline to reveal sub-items (if the
// section has `items`). Each sub-item can carry an optional status pill.
function NavDropdown({ label, targetRoute, currentRoute, go, sections, footerLabel, columns = 1 }) {
  const [open, setOpen] = React.useState(false);
  const [expanded, setExpanded] = React.useState(null);
  const closeTimer = React.useRef(null);

  const openMenu = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setOpen(true);
  };
  const scheduleClose = () => {
    closeTimer.current = setTimeout(() => {
      setOpen(false);
      setExpanded(null);
    }, 220);
  };
  const navigate = (r) => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setOpen(false);
    setExpanded(null);
    go(r);
  };

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') { setOpen(false); setExpanded(null); } };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  return (
    <div
      onMouseEnter={openMenu}
      onMouseLeave={scheduleClose}
      style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}>
      <a href={`#${targetRoute}`}
         onClick={(e) => { e.preventDefault(); navigate(targetRoute); }}
         className={currentRoute === targetRoute ? 'active' : ''}
         style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
        {label}
        <svg width="10" height="10" viewBox="0 0 12 12" fill="none"
             style={{
               transition: 'transform .2s ease',
               transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
               opacity: 0.7
             }}>
          <path d="M3 4.5l3 3 3-3" stroke="currentColor" strokeWidth="1.4"
                strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </a>

      {open && (
        <div role="menu"
             style={{
               position: 'absolute', top: 'calc(100% + 14px)',
               left: columns === 2 ? 'auto' : -20,
               right: columns === 2 ? -20 : 'auto',
               width: columns === 2 ? 520 : 320,
               background: 'var(--paper)',
               border: '1px solid var(--line)',
               borderRadius: 14,
               padding: 6,
               boxShadow:
                 '0 1px 0 rgba(15,20,20,.04), 0 24px 60px -16px rgba(15,20,20,.22)',
               zIndex: 100,
               animation: 'cmdNavFadeIn .14s ease both'
             }}>
          <style>{`
            @keyframes cmdNavFadeIn {
              0%   { opacity: 0; transform: translateY(-4px); }
              100% { opacity: 1; transform: translateY(0); }
            }
            @keyframes cmdNavSubIn {
              0%   { opacity: 0; transform: translateY(-2px); max-height: 0; }
              100% { opacity: 1; transform: translateY(0); max-height: 320px; }
            }
            .cmd-nav-audience {
              all: unset;
              display: flex; align-items: center; justify-content: space-between;
              width: 100%; box-sizing: border-box;
              padding: 12px 14px; border-radius: 10px;
              cursor: pointer; gap: 12px;
              transition: background .15s ease;
            }
            .cmd-nav-audience:hover { background: var(--paper-2); }
            .cmd-nav-audience.is-open { background: var(--paper-2); }
            .cmd-nav-audience-label {
              font-size: 14px; font-weight: 500; color: var(--ink);
              letter-spacing: -0.005em;
            }
            .cmd-nav-audience-sub {
              font-size: 12px; color: var(--ink-3); margin-top: 2px;
              line-height: 1.35;
            }
            .cmd-nav-product {
              all: unset; box-sizing: border-box;
              display: flex; align-items: center; justify-content: space-between;
              width: 100%;
              padding: 8px 12px 8px 14px;
              border-radius: 8px;
              cursor: pointer; gap: 12px;
              transition: background .15s ease;
              position: relative;
            }
            .cmd-nav-product::before {
              content: ""; position: absolute;
              left: 0; top: 12px; bottom: 12px; width: 2px;
              background: var(--line); border-radius: 2px;
            }
            .cmd-nav-product:hover { background: var(--paper-2); }
            .cmd-nav-product:hover::before { background: var(--accent); }
            .cmd-nav-product.is-static { cursor: default; }
            .cmd-nav-product.is-static:hover { background: transparent; }
            .cmd-nav-product.is-static:hover::before { background: var(--line); }
            .cmd-nav-product.is-static .cmd-nav-product-name { color: var(--ink-3); }
            .cmd-nav-product-name {
              font-size: 13.5px; font-weight: 450; color: var(--ink);
              letter-spacing: -0.005em;
            }
            .cmd-nav-status {
              font-family: var(--font-mono);
              font-size: 10px; letter-spacing: .14em; font-weight: 500;
              padding: 3px 7px; border-radius: 4px; white-space: nowrap;
              text-transform: uppercase;
            }
            .cmd-nav-status.beta {
              background: var(--accent-tint); color: var(--accent-ink);
              border: 1px solid var(--accent-tint-2);
            }
            .cmd-nav-status.soon {
              background: var(--paper-2); color: var(--ink-3);
              border: 1px solid var(--line);
            }
            .cmd-nav-sublist {
              padding: 4px 10px 8px 28px;
              overflow: hidden;
              animation: cmdNavSubIn .22s cubic-bezier(.2,.7,.2,1) both;
            }
            .cmd-nav-footer {
              border-top: 1px solid var(--line);
              margin-top: 4px; padding: 10px 14px 8px;
              display: flex; justify-content: space-between; align-items: center;
            }
            .cmd-nav-footer a {
              font-size: 13px; font-weight: 500; color: var(--accent);
              display: inline-flex; align-items: center; gap: 6px;
            }
          `}</style>

          <div style={columns === 2 ? {
            display: 'grid', gridTemplateColumns: '1fr 1fr',
            gap: 2, alignItems: 'start'
          } : undefined}>
          {sections.map(sec => {
            // Direct-nav section (no sub-items)
            if (sec.route && !sec.items) {
              return (
                <button key={sec.id}
                        className="cmd-nav-audience"
                        onClick={() => navigate(sec.route)}>
                  <div style={{ minWidth: 0 }}>
                    <div className="cmd-nav-audience-label">{sec.label}</div>
                    {sec.sub && <div className="cmd-nav-audience-sub">{sec.sub}</div>}
                  </div>
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none"
                       style={{ color: 'var(--ink-4)', flexShrink: 0 }}>
                    <path d="M3 6h6M7 3l3 3-3 3" stroke="currentColor" strokeWidth="1.4"
                          strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </button>
              );
            }
            // Expandable section with sub-items
            const isOpen = expanded === sec.id;
            return (
              <div key={sec.id}>
                <button
                  className={'cmd-nav-audience' + (isOpen ? ' is-open' : '')}
                  onMouseEnter={() => setExpanded(sec.id)}
                  onClick={() => setExpanded(isOpen ? null : sec.id)}
                  aria-expanded={isOpen}>
                  <div style={{ minWidth: 0 }}>
                    <div className="cmd-nav-audience-label">{sec.label}</div>
                    {sec.sub && <div className="cmd-nav-audience-sub">{sec.sub}</div>}
                  </div>
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none"
                       style={{
                         transition: 'transform .2s ease',
                         transform: isOpen ? 'rotate(90deg)' : 'rotate(0deg)',
                         color: 'var(--ink-3)', flexShrink: 0
                       }}>
                    <path d="M4.5 3l3 3-3 3" stroke="currentColor" strokeWidth="1.4"
                          strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </button>
                {isOpen && (
                  <div className="cmd-nav-sublist">
                    {sec.items.map(item => {
                      const clickable = item.status !== 'soon';
                      const Tag = clickable ? 'button' : 'div';
                      return (
                      <Tag key={item.name}
                              className={'cmd-nav-product' + (clickable ? '' : ' is-static')}
                              {...(clickable
                                ? { onClick: () => navigate(item.route) }
                                : { 'aria-disabled': true })}>
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                          {item.productKey && <ProductLogo k={item.productKey} />}
                          <span className="cmd-nav-product-name">{item.name}</span>
                        </span>
                        {item.status && (
                          <span className={'cmd-nav-status ' + item.status}>
                            {item.status === 'beta' ? 'Public beta' : 'In development'}
                          </span>
                        )}
                      </Tag>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
          </div>

          {footerLabel !== null && (
            <div className="cmd-nav-footer">
              <a href={`#${targetRoute}`}
                 onClick={(e) => { e.preventDefault(); navigate(targetRoute); }}>
                {footerLabel || `See ${label.toLowerCase()}`} <ArrowRight />
              </a>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ── Solutions nav dropdown ───────────────────────────────────────────────────
const SOLUTIONS_NAV_AUDIENCES = [
  {
    id: 'physicians',
    label: 'Physicians',
    sub: 'For individual clinicians and APPs',
    items: [
      { name: 'Insurify',    productKey: 'insurify', route: 'insurify', status: 'beta' },
      { name: 'ScribeAware', productKey: 'notes',    route: 'solutions', status: 'soon' }
    ]
  },
  {
    id: 'practices',
    label: 'Office Practices',
    sub: 'For procedural-specialty practices',
    items: [
      { name: 'Greenlight', productKey: 'authdesk', route: 'solutions', status: 'soon' },
      { name: 'Reckon',     productKey: 'rcmiq',    route: 'solutions', status: 'soon' },
      { name: 'Rebound',    productKey: 'denials',  route: 'solutions', status: 'soon' }
    ]
  },
  {
    id: 'enterprise',
    label: 'Enterprise',
    sub: 'For multi-practice and health system rollouts',
    items: [
      { name: 'Sentinel', productKey: 'policy',   route: 'solutions', status: 'soon' },
      { name: 'Reckon',   productKey: 'rcmiq',    route: 'solutions', status: 'soon' },
      { name: 'Rebound',  productKey: 'denials',  route: 'solutions', status: 'soon' }
    ]
  }
];

function SolutionsNavDropdown({ route, go }) {
  return (
    <NavDropdown
      label="Solutions"
      targetRoute="solutions"
      currentRoute={route}
      go={go}
      sections={SOLUTIONS_NAV_AUDIENCES}
      footerLabel="See all solutions" />
  );
}

// ── About nav dropdown ───────────────────────────────────────────────────────
const ABOUT_NAV_SECTIONS = [
  {
    id: 'leadership',
    label: 'Executive Leadership',
    sub: 'Founders and the team',
    route: 'about'
  },
  {
    id: 'advisory',
    label: 'Advisory Boards',
    sub: 'Physician and general advisors',
    items: [
      { name: 'Physician Advisory Board', route: 'physician-board' },
      { name: 'General Advisory Board',   route: 'general-board' }
    ]
  }
];

function AboutNavDropdown({ route, go }) {
  const ABOUT_ROUTES = ['about', 'physician-board', 'general-board'];
  const currentRoute = ABOUT_ROUTES.includes(route) ? 'about' : route;
  return (
    <NavDropdown
      label="About Us"
      targetRoute="about"
      currentRoute={currentRoute}
      go={go}
      sections={ABOUT_NAV_SECTIONS}
      columns={1}
      footerLabel={null} />
  );
}

// ── Resources nav dropdown ───────────────────────────────────────────────────
const RESOURCES_NAV_SECTIONS = [
  {
    id: 'press',
    label: 'Press Releases',
    sub: 'Company news and announcements',
    route: 'press'
  },
  {
    id: 'legal',
    label: 'Privacy & Security',
    sub: 'Compliance posture and policies',
    items: [
      { name: 'Security overview', route: 'security' },
      { name: 'Privacy',           route: 'privacy'  },
      { name: 'Terms of Use',      route: 'terms'    }
    ]
  }
];

function ResourcesNavDropdown({ route, go }) {
  const RESOURCE_ROUTES = ['press', 'security', 'privacy', 'terms'];
  const currentRoute = RESOURCE_ROUTES.includes(route) ? 'press' : route;
  return (
    <NavDropdown
      label="Resources"
      targetRoute="press"
      currentRoute={currentRoute}
      go={go}
      sections={RESOURCES_NAV_SECTIONS}
      columns={1}
      footerLabel={null} />
  );
}

// ── Contact nav dropdown ─────────────────────────────────────────────────────
const CONTACT_NAV_SECTIONS = [
  {
    id: 'demos',
    label: 'Product Demos & Pilots',
    sub: 'For physicians and practices',
    route: 'contact-demos'
  },
  {
    id: 'press',
    label: 'Media Inquiries',
    sub: 'Editorial and journalist inquiries',
    route: 'contact-media'
  },
  {
    id: 'investors',
    label: 'Investor Relations',
    sub: 'Updates and inquiries',
    route: 'contact-investors'
  },
  {
    id: 'development',
    label: 'Product Development',
    sub: 'Co-develop with our team',
    route: 'contact-development'
  },
  {
    id: 'careers',
    label: 'Careers',
    sub: 'Join the team',
    route: 'contact-careers'
  }
];

function ContactNavDropdown({ route, go }) {
  const CONTACT_ROUTES = ['contact', 'contact-demos', 'contact-media', 'contact-investors', 'contact-development', 'contact-careers'];
  const currentRoute = CONTACT_ROUTES.includes(route) ? 'contact' : route;
  return (
    <NavDropdown
      label="Contact Us"
      targetRoute="contact"
      currentRoute={currentRoute}
      go={go}
      sections={CONTACT_NAV_SECTIONS}
      columns={2}
      footerLabel="All contact options" />
  );
}

Object.assign(window, { Wordmark, Header, Footer, ArrowRight, Check, Stat });
