// Shared marketing page building blocks — used identically by Homepage.html and RealtimeInfrastructure.html
// so both pages share literally the same MarketingNavigation, MegaMenu, CTABand, and MarketingFooter config.
const { MarketingNav, MarketingFooter, CTABand, FeatureGrid, Testimonial, CommentPin, FloatingThread, Thread, HeroStage, UseCaseCarousel, FeatureIcon, ProductIcon } = window.LiveblocksDesignSystem_ad32b9;

// Every key maps to exactly one FeatureIcon name/concept — 'bolt' means speed/fast-shipping only,
// never reused as a stand-in for presence, ai, or sync. Legacy call sites keep working unchanged:
// each entry forwards width/height/stroke/strokeWidth props through to the shared FeatureIcon.
const I = {
  msg: p => <FeatureIcon name="comments" {...p} />,
  bolt: p => <FeatureIcon name="bolt" {...p} />,
  bell: p => <FeatureIcon name="notifications" {...p} />,
  book: p => <FeatureIcon name="book" {...p} />,
  people: p => <FeatureIcon name="people" {...p} />,
  db: p => <FeatureIcon name="db" {...p} />,
  globe: p => <FeatureIcon name="globe" {...p} />,
  merge: p => <FeatureIcon name="merge" {...p} />,
  wifiOff: p => <FeatureIcon name="wifiOff" {...p} />,
  undo: p => <FeatureIcon name="undo" {...p} />,
  trend: p => <FeatureIcon name="trend" {...p} />,
  sliders: p => <FeatureIcon name="sliders" {...p} />,
  check: p => <FeatureIcon name="check" {...p} />,
  shield: p => <FeatureIcon name="shield" {...p} />,
  activity: p => <FeatureIcon name="activity" {...p} />,
  layers: p => <FeatureIcon name="layers" {...p} />,
  rocket: p => <FeatureIcon name="rocket" {...p} />,
  users2: p => <FeatureIcon name="users2" {...p} />,
  cloud: p => <FeatureIcon name="cloud" {...p} />,
  lock: p => <FeatureIcon name="lock" {...p} />,
  server: p => <FeatureIcon name="server" {...p} />,
  plug: p => <FeatureIcon name="plug" {...p} />,
  grid: p => <FeatureIcon name="grid" {...p} />,
  history: p => <FeatureIcon name="history" {...p} />,
  send: p => <FeatureIcon name="send" {...p} />,
  video: p => <FeatureIcon name="video" {...p} />,
  waveform: p => <FeatureIcon name="waveform" {...p} />,
  pencil: p => <FeatureIcon name="pencil" {...p} />,
  presence: p => <FeatureIcon name="presence" {...p} />,
  ai: p => <FeatureIcon name="ai" {...p} />,
  sync: p => <FeatureIcon name="multiplayerSync" {...p} />,
  dollar: p => <FeatureIcon name="dollar" {...p} />,
};

// Shared hero context carousel — one HeroStage + UseCaseCarousel composition, reused verbatim by
// every marketing surface that needs the "contextual product" hero (Comments page, Signature visuals
// guideline, etc). Never fork a second mock version of this — extend the options/previews instead.
const HERO_CONTEXTS = [
  { id: 'text-editor', label: 'Text editor', icon: <I.pencil/>, accent: 'var(--uc-text-editor)', headline: 'Enable feedback in your text editor effortlessly' },
  { id: 'media-player', label: 'Media player', icon: <I.waveform/>, accent: 'var(--uc-media-player)', headline: 'Enable feedback in your media player effortlessly' },
  { id: 'whiteboard', label: 'Whiteboard', icon: <I.grid/>, accent: 'var(--uc-whiteboard)', headline: 'Enable feedback on your whiteboard effortlessly' },
  { id: 'website', label: 'Website', icon: <I.globe/>, accent: 'var(--uc-website)', headline: 'Enable feedback on your website effortlessly' },
  { id: 'video-editor', label: 'Video editor', icon: <I.video/>, accent: 'var(--uc-video-editor)', headline: 'Enable feedback in your video editor effortlessly' },
];

// Short, coordinated stagger for a scene's own layers (backdrop → canvas → supporting detail →
// comment panel → markers) — skipped entirely under reduced motion, and only ever a handful of
// groups per scene, never every element.
function useSceneStagger(){
  const reduced = useReducedMotionLocal();
  return (ms) => reduced ? {} : { animation: 'lb-uc-scene-in 0.5s var(--ease-out-cubic) both', animationDelay: ms + 'ms' };
}

function DocSkeletonLines(){
  return (
    <div aria-hidden="true" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{ height: 10, width: '92%', borderRadius: 5, background: 'var(--foreground-subtle)' }} />
      <div style={{ height: 10, width: '78%', borderRadius: 5, background: 'var(--foreground-subtle)' }} />
      <div style={{ height: 10, width: '86%', borderRadius: 5, background: 'var(--foreground-subtle)' }} />
      <div style={{ height: 10, width: '60%', borderRadius: 5, background: 'var(--foreground-subtle)' }} />
    </div>
  );
}
function TextEditorPreview(){
  const st = useSceneStagger();
  return (
    <div style={{ position: 'relative', padding: '2rem 2.5rem', minHeight: 220 }}>
      <div style={st(60)}><DocSkeletonLines/></div>
      <div style={{ position: 'absolute', left: 66, top: 34, ...st(220) }}><CommentPin x={0} y={0} author="Priya Ramaswami" active count={1} /></div>
      <div style={{ position: 'absolute', left: 120, top: 64, width: 260, ...st(280) }}><FloatingThread comments={[{ author: 'Priya Ramaswami', date: Date.now() - 90000, body: 'Can we tighten this sentence?' }]} /></div>
    </div>
  );
}
function MediaPlayerPreview(){
  const st = useSceneStagger();
  const bars = [8,20,14,28,18,32,12,24,16,30,10,22];
  return (
    <div style={{ position: 'relative', padding: '2.5rem 2rem 2rem', minHeight: 220 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 60, ...st(60) }} aria-hidden="true">
        {bars.map((h, i) => <div key={i} style={{ width: 5, height: h, borderRadius: 2, background: 'var(--foreground-subtle)' }} />)}
      </div>
      <div style={{ position: 'absolute', bottom: 60, left: '34%', ...st(220) }}><CommentPin x={0} y={0} author="Marc Dupont" unread count={1} /></div>
      <div style={{ marginTop: '1.5rem', display: 'flex', gap: '0.5rem', alignItems: 'center', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--foreground-tertiary)', ...st(140) }}>
        <span>0:42</span><span style={{ color: 'var(--foreground-subtle)' }}>— "Trim the intro here"</span>
      </div>
    </div>
  );
}
function WhiteboardPreview(){
  const st = useSceneStagger();
  return (
    <div style={{ position: 'relative', minHeight: 220, backgroundImage: 'radial-gradient(var(--foreground-subtle) 1px, transparent 1px)', backgroundSize: '20px 20px', ...st(40) }}>
      <div style={{ position: 'absolute', left: 70, top: 50, ...st(200) }}><CommentPin x={0} y={0} author="Sana Kudrow" count={1} /></div>
      <div style={{ position: 'absolute', left: 210, top: 30, width: 260, ...st(260) }}><FloatingThread comments={[{ author: 'Sana Kudrow', date: Date.now() - 90000, body: 'Move this shape 8px left.' }]} /></div>
    </div>
  );
}
function WebsitePreview(){
  const st = useSceneStagger();
  return (
    <div style={{ position: 'relative', padding: '2rem', minHeight: 220 }}>
      <div style={{ border: '1px solid var(--border-subtle)', borderRadius: 10, padding: '1rem', maxWidth: 320, ...st(60) }}>
        <div style={{ height: 10, width: '70%', borderRadius: 5, background: 'var(--foreground-subtle)', marginBottom: 8 }} />
        <div style={{ height: 10, width: '90%', borderRadius: 5, background: 'var(--foreground-subtle)', opacity: 0.6 }} />
      </div>
      <div style={{ position: 'absolute', right: 40, top: 60, width: 260, ...st(240) }}><FloatingThread comments={[{ author: 'Marc Dupont', date: Date.now() - 60000, body: 'This CTA copy could be shorter.' }]} /></div>
    </div>
  );
}
function VideoEditorPreview(){
  const st = useSceneStagger();
  return (
    <div style={{ position: 'relative', padding: '2rem', minHeight: 220 }}>
      <div style={{ position: 'relative', height: 10, borderRadius: 5, background: 'var(--foreground-subtle)', ...st(60) }}>
        {[18, 46, 74].map((pct, i) => <div key={i} style={{ position: 'absolute', left: pct + '%', top: -4, width: 2, height: 18, background: 'var(--uc-video-editor)' }} />)}
      </div>
      <div style={{ marginTop: '1.5rem', ...st(220) }}><Thread comments={[
        { author: 'Sana Kudrow', date: Date.now() - 240000, body: 'Cut needs to land on the beat at 0:12.' },
        { author: 'Marc Dupont', date: Date.now() - 60000, body: 'Fixed — new export is up.' },
      ]} /></div>
    </div>
  );
}
const HERO_PREVIEWS = {
  'text-editor': <TextEditorPreview/>, 'media-player': <MediaPlayerPreview/>, 'whiteboard': <WhiteboardPreview/>,
  'website': <WebsitePreview/>, 'video-editor': <VideoEditorPreview/>,
};

function useReducedMotionLocal(){
  const [reduced, setReduced] = React.useState(false);
  React.useEffect(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
    setReduced(mq.matches);
    const onChange = () => setReduced(mq.matches);
    mq.addEventListener('change', onChange);
    return () => mq.removeEventListener('change', onChange);
  }, []);
  return reduced;
}

// Reserves height for the longest phrase so switching contexts never reflows the hero. At most two
// headline nodes ever exist in the DOM — the incoming one crossfades in while the outgoing one fades
// out, then the outgoing node is unmounted entirely so no stale/ghosted text can remain.
function HeroCarouselHeadline({ options, activeId, reduced }){
  const longest = options.reduce((a, b) => b.headline.length > a.headline.length ? b : a, options[0]);
  const base = { margin: 0, fontFamily: 'var(--font-sans)', fontSize: '1.75rem', fontWeight: 600, lineHeight: 1.3, textAlign: 'center', textWrap: 'balance' };
  const current = options.find(o => o.id === activeId) || options[0];
  const [layers, setLayers] = React.useState([{ id: current.id, headline: current.headline }]);
  const prevId = React.useRef(current.id);
  const timerRef = React.useRef(null);
  React.useEffect(() => {
    if (current.id === prevId.current) return;
    const outgoingId = prevId.current;
    prevId.current = current.id;
    if (timerRef.current) clearTimeout(timerRef.current);
    if (reduced) { setLayers([{ id: current.id, headline: current.headline }]); return; }
    // At most two layers ever: the outgoing one (about to be removed) and the incoming one — replaced
    // wholesale, never appended, so rapid re-selection can't accumulate duplicate-id ghost nodes.
    setLayers([{ id: outgoingId, headline: options.find(o => o.id === outgoingId)?.headline || '' }, { id: current.id, headline: current.headline }]);
    timerRef.current = setTimeout(() => setLayers([{ id: current.id, headline: current.headline }]), 450);
    return () => clearTimeout(timerRef.current);
  }, [current.id, current.headline, reduced, options]);
  return (
    <div style={{ position: 'relative', width: '100%', maxWidth: 640, margin: '0 auto 1.5rem' }}>
      <div aria-hidden="true" style={{ ...base, visibility: 'hidden' }}>{longest.headline}</div>
      {layers.map(l => {
        const isActive = l.id === current.id;
        return (
          <h2 key={l.id} aria-hidden={isActive ? undefined : true} style={{
            ...base, position: 'absolute', inset: 0, color: 'var(--marketing)',
            opacity: isActive ? 1 : 0,
            transform: reduced ? 'none' : (isActive ? 'translateY(0)' : 'translateY(6px)'),
            transition: reduced ? 'none' : 'opacity 0.4s var(--ease-out-cubic), transform 0.4s var(--ease-out-cubic)',
          }}>{l.headline}</h2>
        );
      })}
    </div>
  );
}

// Persistent chrome that never crossfades — keeps the stage from reading as an empty black rectangle
// with one isolated card while the principal preview swaps underneath it.
function HeroSkeletonChrome(){
  return (
    <div aria-hidden="true" style={{ position: 'absolute', inset: '8%', border: '1px solid rgb(255 255 255/6%)', borderRadius: 16, opacity: 0.5 }}>
      <div style={{ position: 'absolute', top: 18, left: 18, display: 'flex', gap: 8 }}>
        <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'rgb(255 255 255/8%)' }} />
        <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'rgb(255 255 255/8%)' }} />
        <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'rgb(255 255 255/8%)' }} />
      </div>
      <div style={{ position: 'absolute', top: 18, left: 60, right: 18, height: 10, borderRadius: 5, background: 'rgb(255 255 255/6%)' }} />
    </div>
  );
}
function HeroContextCarousel({ options = HERO_CONTEXTS, previews = HERO_PREVIEWS, label = 'Comments context' }){
  const [active, setActive] = React.useState(options[0]);
  const reduced = useReducedMotionLocal();
  return (
    <div style={{ padding: '2.5rem 1.5rem 2rem' }}>
      <HeroCarouselHeadline options={options} activeId={active.id} reduced={reduced} />
      <HeroStage accent={active.accent} halo={1} demoKey={active.id} demo={previews[active.id]} skeleton={<HeroSkeletonChrome/>}
        label={active.headline} panelId={'hero-panel-' + active.id} tabId={'uc-tab-' + active.id} />
      <div style={{ maxWidth: 640, margin: '2rem auto 0' }}>
        <UseCaseCarousel options={options} label={label} hidePanels tablistStyle={{ justifyContent: 'center' }} onChange={(id, opt) => setActive(opt)} />
      </div>
      <style>{'@keyframes lb-uc-scene-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}'}</style>
    </div>
  );
}

// Built lazily (not at module scope) so its ProductIcon elements are constructed only when SiteNav
// actually renders — avoids referencing the design-system namespace before it's fully populated.
function getNavMenus() { return [
  { id: 'product', label: 'Product', variant: 'grouped', groups: [
    { label: 'Collaboration', items: [
      { title: 'Sync', description: 'Persistent shared data that stays consistent across every client.', icon: <ProductIcon variant="multiplayer" size={22} />, iconBare: true, href: 'Sync.html' },
      { title: 'Comments', description: 'Threaded discussion anchored anywhere in your product.', icon: <ProductIcon variant="comments" size={22} />, iconBare: true, href: 'Comments.html' },
    ] },
    { label: 'Realtime', items: [
      { title: 'Notifications', description: 'Keep everyone in the loop, automatically.', icon: <ProductIcon variant="notifications" size={22} />, iconBare: true, href: 'Notifications.html' },
      { title: 'Presence', description: 'Live cursors and avatars, out of the box.', icon: <ProductIcon variant="presence" size={22} />, iconBare: true, href: '#' },
      { title: 'AI Copilots', description: 'Ship collaborative AI features fast.', icon: <ProductIcon variant="ai" size={22} />, iconBare: true, href: '#' },
    ] },
  ] },
  { id: 'solutions', label: 'Solutions', variant: 'flat', groups: [{ items: [
    { title: 'Realtime infrastructure', description: 'The room, sync, and conflict resolution layer.', icon: <I.globe />, href: 'RealtimeInfrastructure.html' },
    { title: 'Agentic apps', description: 'Give AI agents a seat at the same shared table.', icon: <I.ai />, href: '#' },
  ] }] },
  { id: 'resources', label: 'Resources', variant: 'grouped', groups: [
    { label: 'Learn', items: [{ title: 'Docs', description: 'Guides and API reference.', icon: <I.book />, href: '../docs/Documentation.html' }, { title: 'Blog', description: 'Product updates and engineering notes.', icon: <I.book />, href: '#' }] },
    { label: 'Community', items: [{ title: 'Discord', description: 'Chat with the team and other builders.', icon: <I.people />, href: '#' }] },
  ] },
]; }
const NAV_LINKS = [{ label: 'Docs', href: '../docs/Documentation.html' }, { label: 'Pricing', href: 'Pricing.html' }];

const FOOTER_COLUMNS = [
  { title: 'Product', links: [{ label: 'Sync', href: 'Sync.html' }, { label: 'Comments', href: 'Comments.html' }, { label: 'Notifications', href: 'Notifications.html' }, { label: 'Presence', href: '#' }, { label: 'AI Copilots', href: '#' }] },
  { title: 'Solutions', links: [{ label: 'Realtime infrastructure', href: 'RealtimeInfrastructure.html' }, { label: 'Agentic apps', href: '#' }] },
  { title: 'Resources', links: [{ label: 'Docs', href: '../docs/Documentation.html' }, { label: 'Pricing', href: 'Pricing.html' }, { label: 'Blog', href: '#' }, { label: 'Changelog', href: '#' }] },
  { title: 'Company', links: [{ label: 'About', href: '#' }, { label: 'Careers', href: '#' }, { label: 'Contact', href: '#' }] },
];
const XIcon = () => <svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 4l16 16M20 4L4 20" /></svg>;
const SOCIAL_LINKS = [{ label: 'X (Twitter)', href: '#', icon: <XIcon /> }];
const COMPLIANCE_LINKS = [{ label: 'Privacy', href: '#' }, { label: 'Terms', href: '#' }];

function SiteNav() {
  return <MarketingNav menus={getNavMenus()} links={NAV_LINKS} />;
}

function SiteFooter() {
  return <MarketingFooter columns={FOOTER_COLUMNS} socialLinks={SOCIAL_LINKS} complianceLinks={COMPLIANCE_LINKS} statusLabel="All systems operational" statusHref="#" />;
}

function ClosingCta() {
  return (
    <section aria-labelledby="closing-cta-heading">
      <CTABand
        heading={<span id="closing-cta-heading">Turn your product into the space where people and AI collaborate</span>}
        primaryAction={{ label: 'Get started for free', href: '#' }}
        secondaryAction={{ label: 'Contact sales', href: '#' }}
      />
    </section>
  );
}

// Shared trust-and-scale block — identical composition reused by both pages.
function TrustSection({ headingId = 'trust-heading' }) {
  return (
    <section data-marketing style={{ background: '#0a0a0a', padding: 'var(--section-pad-desktop) 1.5rem' }}>
      <div style={{ maxWidth: 'var(--container)', margin: '0 auto' }}>
        <h2 id={headingId} style={{ fontFamily: 'var(--font-sans)', fontSize: '2.25rem', fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--marketing)', margin: '0 0 3rem', textAlign: 'center', textWrap: 'balance' }}>
          A platform you can trust at scale.
        </h2>
        <FeatureGrid items={[
          { title: 'Effortless scaling', description: 'Rooms scale from a handful of users to thousands without re-architecting.', icon: <I.trend /> },
          { title: 'Minimal configuration', description: 'Sensible defaults get a room running in minutes.', icon: <I.sliders /> },
          { title: 'No maintenance required', description: 'Liveblocks operates and upgrades the infrastructure for you.', icon: <I.check /> },
          { title: 'Enterprise-ready security', description: 'Role-based permissions, audit logging, and dedicated support.', icon: <I.shield /> },
          { title: '99.99% uptime', description: 'A global edge network keeps rooms connected and responsive.', icon: <I.activity /> },
        ]} />
        <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'center', flexWrap: 'wrap', marginTop: '3rem', fontFamily: 'var(--font-sans)', fontSize: '0.8125rem', color: 'var(--marketing-subtler)' }}>
          <span style={{ padding: '0.375rem 0.875rem', borderRadius: 9999, boxShadow: 'inset 0 0 0 1px var(--marketing-divider-bold)' }}>SOC 2 Type II</span>
          <span style={{ padding: '0.375rem 0.875rem', borderRadius: 9999, boxShadow: 'inset 0 0 0 1px var(--marketing-divider-bold)' }}>HIPAA compliant</span>
          <span style={{ alignSelf: 'center', color: 'var(--marketing-subtlest)' }}>Shown as text only — no approved compliance badge artwork exists in this project.</span>
        </div>
        <div style={{ marginTop: 'var(--section-pad-desktop)' }}>
          <Testimonial quotes={[
            { pre: 'We replaced ', emphasis: 'three separate tools', post: ' with one Liveblocks integration.', name: 'Priya Ramaswami', role: 'Engineering Lead', company: 'Acme' },
            { quote: 'Shipping realtime collaboration used to take us a quarter. Now it takes a week.', name: 'Marc Dupont', role: 'CTO', company: 'Northwind' },
          ]} />
        </div>
      </div>
    </section>
  );
}

function PlaceholderLogo(label) {
  const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='120' height='28' viewBox='0 0 120 28'><rect x='0.5' y='0.5' width='119' height='27' rx='6' fill='none' stroke='%23ffffff' stroke-opacity='0.5'/><text x='60' y='18' text-anchor='middle' font-family='monospace' font-size='11' fill='%23ffffff' fill-opacity='0.6'>LOGO</text></svg>`;
  return 'data:image/svg+xml,' + svg.replace(/#/g, '%23');
}

// Shared cross-sell row — same Card/cross-sell grammar as Homepage & Realtime Infrastructure, callers just pick which 2 products to show.
const CROSS_SELL_CATALOG = {
  sync: { title: 'Sync', description: 'Persistent shared data with automatic conflict resolution.', href: 'Sync.html', variant: 'multiplayer' },
  comments: { title: 'Comments', description: 'Threaded discussion anchored anywhere in your product.', href: 'Comments.html', variant: 'comments' },
  notifications: { title: 'Notifications', description: 'Mentions, replies, and agent activity in one inbox.', href: 'Notifications.html', variant: 'notifications' },
};
function CrossSellSection({ headingId, products, icons }) {
  const { Card } = window.LiveblocksDesignSystem_ad32b9;
  return (
    <section aria-labelledby={headingId} data-marketing style={{ background: 'var(--marketing-surface-base)', padding: 'var(--section-pad-desktop) 1.5rem' }}>
      <div style={{ maxWidth: 'var(--container)', margin: '0 auto' }}>
        <h2 id={headingId} style={{ fontFamily: 'var(--font-sans)', fontSize: '2.25rem', fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--marketing)', margin: '0 0 2.5rem', textAlign: 'center' }}>More than one way to collaborate.</h2>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${products.length},minmax(0,1fr))`, gap: '1.5rem' }} className="lb-crosssell-grid">
          {products.map(p => {
            const c = CROSS_SELL_CATALOG[p];
            return <Card key={p} variant="cross-sell" title={c.title} description={c.description} icon={(icons && icons[p]) || <ProductIcon variant={c.variant} size={26} />} href={c.href} />;
          })}
        </div>
      </div>
      <style>{'@media (max-width:800px){.lb-crosssell-grid{grid-template-columns:1fr !important}}'}</style>
    </section>
  );
}

Object.assign(window, { SiteNav, SiteFooter, ClosingCta, TrustSection, PlaceholderLogo, CrossSellSection, NAV_LINKS, FOOTER_COLUMNS, SOCIAL_LINKS, COMPLIANCE_LINKS, MktIcons: I, HeroContextCarousel, HERO_CONTEXTS, HERO_PREVIEWS });
