// Home page: expressive hero + value props + live demo + customer marquee + CTA
const { useState: useStateHome, useEffect: useEffectHome, useRef: useRefHome } = React;

function HomePage({ go }) {
  useReveal();

  return (
    <main>
      {/* ===== HERO ===== */}
      <section className="home-hero" style={{ position: 'relative', overflow: 'hidden' }}>
        <DecorBlobs />
        <div className="page" style={{ paddingTop: 72, paddingBottom: 64 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '.9fr 1.1fr', gap: 44, alignItems: 'center' }} className="hero-grid">
            <div>
              <h1 className="display-1" style={{ marginBottom: 24 }}>
                Meet your members<br/>
                <em>where they already are.</em>
              </h1>
              <p style={{ fontSize: 19, lineHeight: 1.5, color: 'var(--site-ink-soft)', maxWidth: 540, marginBottom: 32 }}>
                Slack, email, and your online community, wherever your members choose to participate. Synchronize keeps every post, reply, and reaction in sync, so one conversation reaches the whole community.
              </p>
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <a href="#/get-started" onClick={e=>{e.preventDefault();go('get-started');}} className="btn btn-primary btn-lg">Book a demo →</a>
                <a href="#/how-it-works" onClick={e=>{e.preventDefault();go('how-it-works');}} className="btn btn-soft btn-lg">See how it works</a>
              </div>
            </div>
            <div style={{ position: 'relative', display: 'flex', justifyContent: 'center' }}>
              <HeroAnimation/>
            </div>
          </div>
        </div>
      </section>

      {/* ===== CUSTOMER MARQUEE ===== */}
      <section style={{ padding: '32px 0 48px', borderTop: '1px solid var(--site-line)', borderBottom: '1px solid var(--site-line)' }}>
        <div className="page center" style={{ marginBottom: 24 }}>
          <span className="eyebrow-ink" style={{ fontSize: 12, fontWeight: 500, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--site-ink-soft)' }}>
            Trusted by professional communities built on meaningful participation
          </span>
        </div>
        <CustomerMarquee/>
      </section>

      {/* ===== VALUE PROPS ===== */}
      <section className="section">
        <div className="page">
          <div style={{ maxWidth: 780, marginBottom: 64 }} className="reveal">
            <div className="eyebrow" style={{ marginBottom: 16 }}>Why Synchronize</div>
            <h2 className="display-2">
              Stop forcing members to <em>pick a platform.</em>
            </h2>
            <p style={{ fontSize: 17, color: 'var(--site-ink-soft)', marginTop: 24, maxWidth: 620 }}>
              Your members already have communication habits. Synchronize works with those habits instead of against them, bringing one community conversation to the channels people actually use.
            </p>
          </div>

          <div className="grid-3">
            <ValueCard accent="brand" num="01" title="Keep one conversation everywhere"
              body="Posts, replies, edits, and reactions stay aligned across Slack, email, and your community home without duplicate threads or manual reposting." />
            <ValueCard accent="coral" num="02" title="Give every member a way in"
              body="Members participate from the surface they prefer while everyone sees the same people, context, and conversation." />
            <ValueCard accent="mint" num="03" title="Operate from one place"
              body="Onboarding, broadcasts, analytics, search, and member management give your team one place to run the community behind the scenes." />
          </div>
        </div>
      </section>

      {/* ===== LIVE FLOW DEMO ===== */}
      <section className="section" style={{ background: 'var(--site-bg-alt)' }}>
        <div className="page">
          <div style={{ maxWidth: 780, marginBottom: 48 }} className="reveal">
            <div className="eyebrow" style={{ marginBottom: 16 }}>One connected thread</div>
            <h2 className="display-2">One conversation, <em>three surfaces.</em></h2>
            <p style={{ fontSize: 17, color: 'var(--site-ink-soft)', marginTop: 20, maxWidth: 620 }}>
              A member can post from Slack, email, or your online community. Everyone sees the same conversation, with every reply, reaction, author, and timestamp kept in sync.
            </p>
          </div>
          <MirrorMotif/>
        </div>
      </section>

      {/* ===== FEATURE GLIMPSES ===== */}
      <section className="section">
        <div className="page">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: 48, marginBottom: 80 }} className="reveal feature-showcase">
            <div className="feature-showcase-copy">
              <div className="eyebrow" style={{ marginBottom: 16 }}>Analytics</div>
              <h2 className="display-2">See who's <em>actually</em> showing up.</h2>
              <p style={{ fontSize: 16, color: 'var(--site-ink-soft)', marginTop: 20 }}>
                See participation across every connected surface, understand which members are gaining or losing momentum, and know where a thoughtful nudge can make a difference.
              </p>
              <a href="#/how-it-works" onClick={e=>{e.preventDefault();go('how-it-works');}} className="btn btn-soft" style={{ marginTop: 24 }}>Explore member analytics →</a>
            </div>
            <AnalyticsPreview/>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 48, alignItems: 'center' }} className="reveal feature-showcase">
            <OnboardingPreview/>
            <div className="feature-showcase-copy">
              <div className="eyebrow" style={{ marginBottom: 16 }}>Onboarding sequences</div>
              <h2 className="display-2">Welcome every new member, <em>automatically.</em></h2>
              <p style={{ fontSize: 16, color: 'var(--site-ink-soft)', marginTop: 20 }}>
                Build a welcome journey once, then deliver the right introduction, reminder, or next step in Slack, email, or your community based on what each member has actually done.
              </p>
              <a href="#/how-it-works" onClick={e=>{e.preventDefault();go('how-it-works');}} className="btn btn-soft" style={{ marginTop: 24 }}>See automated onboarding →</a>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: 48, alignItems: 'center', marginTop: 80 }} className="reveal feature-showcase">
            <div className="feature-showcase-copy">
              <div className="eyebrow" style={{ marginBottom: 16 }}>Ask · AI-powered search</div>
              <h2 className="display-2">Ask your community <em>anything.</em></h2>
              <p style={{ fontSize: 16, color: 'var(--site-ink-soft)', marginTop: 20 }}>
                Ask turns years of conversations and resources into a clear, cited answer, then surfaces members with relevant experience. Available from Slack, email, or the web.
              </p>
              <a href="#/how-it-works" onClick={e=>{e.preventDefault();go('how-it-works');}} className="btn btn-soft" style={{ marginTop: 24 }}>See how Ask works →</a>
            </div>
            <AskPreview/>
          </div>
        </div>
      </section>

      {/* ===== FINAL CTA ===== */}
      <section className="section-tight">
        <div className="page">
          <div className="structured-cta" style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '48px 56px', background: '#fff',
            border: '1px solid var(--site-line)', borderRadius: 24, gap: 24, flexWrap: 'wrap',
          }}>
            <div>
              <h2 className="display-2" style={{ fontSize: 36 }}>See how Synchronize fits your community.</h2>
              <p style={{ color: 'var(--site-ink-soft)', marginTop: 8 }}>We’ll map your current platforms, member habits, and the fastest path to one connected experience.</p>
            </div>
            <a href="#/get-started" onClick={e=>{e.preventDefault();go('get-started');}} className="btn btn-primary btn-lg">Book a demo →</a>
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 1100px) {
          .hero-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </main>
  );
}

// ---------- Decorative blobs behind hero ----------
function DecorBlobs() {
  return (
    <div className="hero-grid-lines" aria-hidden />
  );
}

// ---------- Value card ----------
function ValueCard({ num, title, body, accent }) {
  const bg = accent === 'brand' ? 'var(--brand-tint)'
           : accent === 'coral' ? 'var(--accent-coral-bg)'
           : accent === 'mint' ? 'var(--accent-mint-bg)'
           : 'var(--accent-amber-bg)';
  const fg = accent === 'brand' ? 'var(--brand)'
           : accent === 'coral' ? 'var(--accent-coral)'
           : accent === 'mint' ? 'var(--accent-mint)'
           : '#B87900';
  return (
    <div className="m-card reveal" style={{ background: '#fff' }}>
      <div style={{
        display: 'inline-block', padding: '4px 10px', borderRadius: 6,
        background: bg, color: fg, fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700, letterSpacing: '.04em',
        marginBottom: 20,
      }}>{num}</div>
      <h3 style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 21, lineHeight: 1.25, marginBottom: 12, letterSpacing: '-0.01em' }}>{title}</h3>
      <p style={{ color: 'var(--site-ink-soft)', fontSize: 15 }}>{body}</p>
    </div>
  );
}

// ---------- Customer marquee ----------
function CustomerMarquee() {
  const customers = [
    'Operators Guild',
    'VC Platform Global Community',
    'Battery Ventures',
    'Workspace 6',
    'Transform',
    'Balderton Capital',
    'The People People Group',
    'Scale Venture Partners',
    'Foundation Capital',
  ];
  return (
    <div className="marquee" aria-label="Customer communities">
      <div className="marquee-track">
        {[0, 1].map(group => (
          <div className="marquee-group" aria-hidden={group === 1} key={group}>
            {customers.map(c => (
              <div className="marquee-name" key={c}>
                <span>{c}</span>
                <i aria-hidden="true"></i>
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

function ProductHeaderIcon({ kind }) {
  const outer = {
    width: 26, height: 26, borderRadius: 8, flexShrink: 0,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    background: 'var(--brand-tint)', color: 'var(--brand)',
  };
  if (kind === 'analytics') {
    return (
      <span style={outer} aria-hidden="true">
        <span style={{ width: 14, height: 13, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', gap: 2 }}>
          {[6, 10, 13].map((height, i) => (
            <span key={height} style={{ width: 3, height, borderRadius: '2px 2px 1px 1px', background: 'var(--brand)', opacity: [.5, .72, 1][i] }}/>
          ))}
        </span>
      </span>
    );
  }
  return (
    <span style={outer} aria-hidden="true">
      <span style={{ position: 'relative', width: 14, height: 15 }}>
        <span style={{ position: 'absolute', left: 3, top: 2, bottom: 2, width: 2, borderRadius: 2, background: 'var(--brand)', opacity: .35 }}/>
        {[1, 7, 13].map((top, i) => (
          <span key={top} style={{ position: 'absolute', left: i === 1 ? 2 : 1, top, width: i === 1 ? 5 : 4, height: i === 1 ? 5 : 4, borderRadius: '50%', background: i === 1 ? '#21C089' : 'var(--brand)', boxShadow: '0 0 0 2px var(--brand-tint)' }}/>
        ))}
        <span style={{ position: 'absolute', left: 8, top: 3, width: 5, height: 2, borderRadius: 2, background: 'var(--brand)', opacity: .75 }}/>
        <span style={{ position: 'absolute', left: 8, top: 9, width: 5, height: 2, borderRadius: 2, background: 'var(--brand)', opacity: .75 }}/>
      </span>
    </span>
  );
}

function MemberCategoryIcon({ kind, color, symbol }) {
  const tile = {
    width: 26, height: 26, borderRadius: 7, flexShrink: 0,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    border: '1px solid ' + color + '30', background: color + '12', color,
  };
  if (kind === 'super') {
    return (
      <span style={tile} aria-hidden="true">
        <span style={{ position: 'relative', width: 17, height: 17 }}>
          <span style={{ position: 'absolute', inset: 0, background: 'currentColor', clipPath: 'polygon(20% 0, 80% 0, 100% 32%, 50% 100%, 0 32%)' }}/>
          <span style={{ position: 'absolute', top: 2, left: 2, width: 13, height: 12, background: '#fff', clipPath: 'polygon(20% 0, 80% 0, 100% 32%, 50% 100%, 0 32%)' }}/>
          <span style={{
            position: 'absolute', top: 3, left: 5, width: 7, height: 7, background: 'currentColor',
            clipPath: 'polygon(50% 0, 61% 35%, 98% 35%, 68% 57%, 79% 92%, 50% 70%, 21% 92%, 32% 57%, 2% 35%, 39% 35%)',
          }}/>
        </span>
      </span>
    );
  }
  if (kind === 'rising') {
    return (
        <span style={tile} aria-hidden="true">
          <span style={{ position: 'relative', width: 17, height: 17 }}>
          <span style={{
            position: 'absolute', right: 0, top: 0, width: 11, height: 11, background: 'currentColor', zIndex: 2,
            clipPath: 'polygon(50% 0, 61% 35%, 98% 35%, 68% 57%, 79% 92%, 50% 70%, 21% 92%, 32% 57%, 2% 35%, 39% 35%)',
          }}/>
          <span style={{ position: 'absolute', left: 0, bottom: 4, width: 12, height: 3, borderRadius: 4, background: 'currentColor', transform: 'rotate(-42deg)', transformOrigin: 'left center', opacity: .92 }}/>
          <span style={{ position: 'absolute', left: 0, bottom: 0, width: 8, height: 2, borderRadius: 4, background: 'currentColor', transform: 'rotate(-42deg)', transformOrigin: 'left center', opacity: .48 }}/>
        </span>
      </span>
    );
  }
  if (kind === 'active') {
    return (
      <span style={tile} aria-hidden="true">
        <span style={{ position: 'relative', width: 14, height: 11, borderRadius: 4, background: 'currentColor' }}>
          <span style={{ position: 'absolute', left: 3, bottom: -3, width: 5, height: 5, background: 'currentColor', clipPath: 'polygon(0 0, 100% 0, 0 100%)' }}/>
        </span>
      </span>
    );
  }
  return (
    <span style={{ ...tile, fontFamily: 'var(--font-sans)', fontSize: kind === 'inactive' ? 10 : 13, fontWeight: 800, lineHeight: 1 }} aria-hidden="true">
      {symbol}
    </span>
  );
}

// ---------- Analytics preview: top metrics → platform engagement → categories ----------
function AnalyticsPreview() {
  const scopes = [
    { name: 'All spaces', total: 1284, active: 892, fresh: 47, platforms: [54,62,39], categories: [38,104,286,57,407,392] },
    { name: 'Member asks', total: 412, active: 327, fresh: 18, platforms: [61,55,46], categories: [24,48,117,26,112,85] },
    { name: 'AI in practice', total: 286, active: 238, fresh: 14, platforms: [58,67,51], categories: [21,38,86,17,76,48] },
  ];
  const [scopeIndex, setScopeIndex] = useStateHome(0);
  const reducedMotion = window.useReducedMotion();
  useEffectHome(() => {
    if (reducedMotion) {
      setScopeIndex(0);
      return undefined;
    }
    const timer = setInterval(() => setScopeIndex(index => (index + 1) % scopes.length), 2800);
    return () => clearInterval(timer);
  }, [reducedMotion]);
  const scope = scopes[scopeIndex];
  const totalMembers = scope.total;
  const activeMembers = scope.active;
  const inactiveMembers = totalMembers - activeMembers;
  const newMembers = scope.fresh;
  const activePct = Math.round((activeMembers / totalMembers) * 100);

  const topMetrics = [
    { k: 'Total',    v: totalMembers.toLocaleString(),   sub: 'members',   color: 'var(--site-ink)' },
    { k: 'Active',   v: activeMembers.toLocaleString(),  sub: 'last 30d',  color: '#4242F0' },
    { k: 'Inactive', v: inactiveMembers.toLocaleString(),sub: '30d+ idle', color: '#8B8B8B' },
    { k: 'New',      v: '+' + newMembers,                sub: 'this week', color: '#21C089' },
    { k: 'Active %', v: activePct + '%',                 sub: 'of total',  color: '#4242F0' },
  ];

  // Platform engagement
  const platforms = [
    { k: 'Slack', kind: 'slack', active: scope.platforms[0], color: '#611F69' },
    { k: 'Email', kind: 'email', active: scope.platforms[1], color: '#315EFB' },
    { k: 'Community', kind: 'circle', active: scope.platforms[2], color: '#2F7CFF' },
  ];

  // Six member categories
  const categories = [
    { key: 'super',      icon: '★', label: 'Super Users',            count: scope.categories[0], desc: 'Daily active, cross-posting',    color: '#4242F0' },
    { key: 'rising',     icon: '↗', label: 'Rising Stars',           count: scope.categories[1], desc: 'Trending up this month',         color: '#21C089' },
    { key: 'active',     icon: '✎', label: 'Active Contributors',    count: scope.categories[2], desc: 'Posting weekly',                 color: '#2F7CFF' },
    { key: 'declining',  icon: '↘', label: 'Declining Contributors', count: scope.categories[3], desc: 'Engagement dropped 3w',          color: '#F5B820' },
    { key: 'spectators', icon: '◉', label: 'Spectators',             count: scope.categories[4], desc: 'Reading, never posted',          color: '#8B8B8B' },
    { key: 'inactive',   icon: 'Ⅱ', label: 'Inactive Users',         count: scope.categories[5], desc: 'No activity in 30d+', color: '#B24848' },
  ];
  const catTotal = categories.reduce((s, c) => s + c.count, 0);

  return (
    <div className="product-preview analytics-preview" style={{
      background: '#fff', border: '1px solid var(--site-line)', borderRadius: 20,
      padding: 20, boxShadow: '0 8px 30px rgba(26,27,58,0.06)',
    }}>
      {/* Header */}
      <div className="analytics-preview-header" style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, fontSize: 13, fontWeight: 600 }}>
        <ProductHeaderIcon kind="analytics"/>
        <span className="analytics-preview-heading">
          <span style={{ color: 'var(--site-ink)' }}>Community Analytics</span>
          <span style={{ color: 'var(--site-ink-soft)', fontWeight: 500, fontSize: 12 }}>· Leadership Exchange</span>
        </span>
        <span className="analytics-preview-controls">
          <span style={{ fontSize: 10, color: 'var(--site-ink-soft)' }}>last 30 days</span>
          <span key={scope.name} style={{ minWidth: 92, display: 'inline-flex', alignItems: 'center', justifyContent: 'space-between', gap: 7, padding: '5px 8px', border: '1px solid var(--site-line)', borderRadius: 7, background: scopeIndex ? 'var(--brand-tint)' : '#fff', color: scopeIndex ? 'var(--brand)' : 'var(--site-ink)', fontSize: 9.5, fontWeight: 700, animation: 'analytics-filter-in .35s both' }}><span>≡</span>{scope.name}<span>⌄</span></span>
        </span>
      </div>

      {/* Top metrics row */}
      <div className="analytics-preview-metrics" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8, marginBottom: 16 }}>
        {topMetrics.map((m, index) => (
          <div className="analytics-preview-metric" key={`${scope.name}-${m.k}`} style={{
            border: '1px solid var(--site-line)', borderRadius: 10,
            padding: '10px 10px', background: '#fff', animation: `analytics-metric-in .4s ${index * .045}s both`,
          }}>
            <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--site-ink-soft)', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 4 }}>
              {m.k}
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 23, lineHeight: 1, color: m.color }}>
              {m.v}
            </div>
            <div style={{ fontSize: 10, color: 'var(--site-ink-soft)', marginTop: 4 }}>{m.sub}</div>
          </div>
        ))}
      </div>

      {/* Platform Engagement */}
      <div style={{ padding: '14px 0', borderTop: '1px solid var(--site-line)', borderBottom: '1px solid var(--site-line)', marginBottom: 16 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--site-ink-soft)', marginBottom: 10, letterSpacing: '0.04em', textTransform: 'uppercase' }}>
          Platform Engagement
        </div>
        {platforms.map((r, index) => (
          <div key={r.k} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
            <span style={{ display: 'flex', width: 86, alignItems: 'center', gap: 7, fontSize: 11, color: 'var(--site-ink)', fontWeight: 650 }}>
              {r.kind === 'slack' ? (
                <span style={{ width: 20, height: 20, borderRadius: 5, background: 'var(--c-slack-bg)', border: '1px solid #D9C9DC', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <PlatformIcon kind="slack" size={16}/>
                </span>
              ) : <PlatformIcon kind={r.kind} size={20}/>} {r.k}
            </span>
            <div style={{ flex: 1, height: 10, borderRadius: 4, background: 'var(--site-line)', overflow: 'hidden', display: 'flex' }}>
              <div style={{ width: r.active+'%', background: r.color, transition: 'width .8s cubic-bezier(.2,.8,.2,1)' }}/>
              <div style={{ width: (100-r.active)+'%', background: r.color+'55', transition: 'width .8s cubic-bezier(.2,.8,.2,1)' }}/>
            </div>
            <span key={`${scope.name}-${r.k}`} style={{ fontSize: 12, fontWeight: 750, color: r.color, width: 34, textAlign: 'right', animation: `analytics-metric-in .35s ${index * .06}s both` }}>{r.active}%</span>
          </div>
        ))}
      </div>

      {/* Member categories */}
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--site-ink-soft)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>
            Member Categories
          </div>
          <div style={{ fontSize: 10, color: 'var(--site-ink-soft)', fontWeight: 650 }}>{catTotal.toLocaleString()} segmented</div>
        </div>

        {/* proportional bar */}
        <div style={{ display: 'flex', height: 6, borderRadius: 3, overflow: 'hidden', marginBottom: 12, background: 'var(--site-line)' }}>
          {categories.map(c => (
            <div key={c.key} title={`${c.label}: ${c.count}`}
              style={{ width: `${(c.count / catTotal) * 100}%`, background: c.color, transition: 'width .8s cubic-bezier(.2,.8,.2,1)' }}/>
          ))}
        </div>

        {/* category rows */}
        <div className="analytics-preview-categories" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {categories.map((cat, index) => (
            <div key={`${scope.name}-${cat.key}`} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              border: '1px solid var(--site-line)', borderRadius: 10,
              padding: '8px 10px', background: '#fff', animation: `analytics-metric-in .4s ${index * .04}s both`,
            }}>
              <MemberCategoryIcon kind={cat.key} color={cat.color} symbol={cat.icon}/>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--site-ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {cat.label}
                </div>
                <div style={{ fontSize: 10, color: 'var(--site-ink-soft)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {cat.desc}
                </div>
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: cat.color, lineHeight: 1 }}>
                {cat.count}
              </div>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @keyframes analytics-filter-in { from { opacity: .4; transform: translateY(-3px); } to { opacity: 1; transform: none; } }
        @keyframes analytics-metric-in { from { opacity: .35; transform: translateY(4px); } to { opacity: 1; transform: none; } }
      `}</style>
    </div>
  );
}

// ---------- Ask preview: AI natural-language search ----------
const ASK_SCENARIOS = [
  {
    query: 'How have teams handled SOC 2 on a tight timeline?',
    answer: 'Members who moved fastest treated SOC 2 as an operating project, not a security-only task: assign one owner, complete a readiness review, automate evidence collection, and agree on control owners before the audit. Most planned for 8–12 weeks.',
    sources: [
      { title: 'How we completed SOC 2 without slowing the roadmap', meta: 'Member asks · 24 replies' },
      { title: 'SOC 2 readiness: owners, evidence, and timeline', meta: 'Security · 16 replies' },
    ],
    people: {
      home: [
        { name: 'Aisha Patel', color: '#4242F0', why: 'Led two SOC 2 Type II programs', tags: ['Compliance', 'Audit prep'] },
        { name: 'Ethan Cole', color: '#B24848', why: 'Built controls at three growth-stage teams', tags: ['Controls', 'Security'] },
      ],
      features: [
        { name: 'Nadia Khan', color: '#4242F0', why: 'Led two SOC 2 Type II programs', tags: ['Compliance', 'Audit prep'] },
        { name: 'Ben Carter', color: '#B24848', why: 'Built controls at three growth-stage teams', tags: ['Controls', 'Security'] },
      ],
    },
  },
  {
    query: 'How are teams evaluating AI tools before a company-wide rollout?',
    answer: 'Teams are using a lightweight first pass for data handling, model training, retention, SSO, and a named business owner. Low-risk tools enter a 30-day pilot; broader approval follows only when usage and value are clear.',
    sources: [
      { title: 'AI tool review: the five questions we ask first', meta: 'AI in practice · 31 replies' },
      { title: 'What we learned from a 30-day AI pilot', meta: 'Operations · 19 replies' },
    ],
    people: {
      home: [
        { name: 'Leah Morgan', color: '#4242F0', why: 'Created a company-wide AI review process', tags: ['AI policy', 'Legal'] },
        { name: 'Caleb Foster', color: '#B24848', why: 'Runs security reviews for new vendors', tags: ['Security', 'Procurement'] },
      ],
      features: [
        { name: 'Rachel Kim', color: '#4242F0', why: 'Created a company-wide AI review process', tags: ['AI policy', 'Legal'] },
        { name: 'Samuel Ortiz', color: '#B24848', why: 'Runs security reviews for new vendors', tags: ['Security', 'Procurement'] },
      ],
    },
  },
  {
    query: 'What is actually improving attendance at virtual member events?',
    answer: 'Member-led sessions are outperforming broad webinars. The strongest format is one practical question, a 45-minute cap, personal reminders, and a useful recap for people who could not attend.',
    sources: [
      { title: 'Why member-led sessions beat webinars for us', meta: 'Community programs · 18 replies' },
      { title: 'Our reminder sequence for virtual events', meta: 'Events · 12 replies' },
    ],
    people: {
      home: [
        { name: 'Mina Alvarez', color: '#4242F0', why: 'Runs a 2,000-member peer program', tags: ['Events', 'Programming'] },
        { name: 'Jonah Brooks', color: '#B24848', why: 'Doubled attendance with member-led formats', tags: ['Engagement', 'Events'] },
      ],
      features: [
        { name: 'Clara Wilson', color: '#4242F0', why: 'Runs a 2,000-member peer program', tags: ['Events', 'Programming'] },
        { name: 'Isaac Mensah', color: '#B24848', why: 'Doubled attendance with member-led formats', tags: ['Engagement', 'Events'] },
      ],
    },
  },
];

function AskPreview({ variant = 'home' }) {
  const [scenarioIndex, setScenarioIndex] = useStateHome(0);
  const [phase, setPhase] = useStateHome(1); // 1 typing, 2 thinking, 3 answer, 4 people
  const [typed, setTyped] = useStateHome('');
  const reducedMotion = window.useReducedMotion();

  useEffectHome(() => {
    if (reducedMotion) {
      setScenarioIndex(0);
      setTyped(ASK_SCENARIOS[0].query);
      setPhase(4);
      return undefined;
    }
    const timers = [];
    let cancelled = false;
    const later = (fn, delay) => {
      const timer = setTimeout(() => { if (!cancelled) fn(); }, delay);
      timers.push(timer);
    };
    const run = index => {
      const scenario = ASK_SCENARIOS[index];
      setScenarioIndex(index);
      setTyped('');
      setPhase(1);
      let character = 0;
      const typeNext = () => {
        character += 1;
        setTyped(scenario.query.slice(0, character));
        if (character < scenario.query.length) {
          later(typeNext, 28);
          return;
        }
        later(() => setPhase(2), 350);
        later(() => setPhase(3), 1650);
        later(() => setPhase(4), 2850);
        later(() => run((index + 1) % ASK_SCENARIOS.length), 9000);
      };
      later(typeNext, 140);
    };
    run(0);
    return () => { cancelled = true; timers.forEach(clearTimeout); };
  }, [reducedMotion]);

  const scenario = ASK_SCENARIOS[scenarioIndex];
  const experts = scenario.people[variant] || scenario.people.home;

  return (
    <div className={`product-preview ask-preview ask-preview--${variant}`} style={{
      background: '#fff', border: '1px solid var(--site-line)', borderRadius: 20,
      padding: 20, boxShadow: '0 8px 30px rgba(26,27,58,0.06)',
      height: variant === 'features' ? 560 : 'auto', overflow: 'hidden',
    }}>
      {/* header */}
      <div className="ask-preview-header" style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <span className="ask-preview-heading" style={{
          display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, fontWeight: 700, color: 'var(--site-ink)',
        }}>
          <SparkIcon/> Ask
        </span>
        <span style={{ fontSize: 11, color: 'var(--site-ink-soft)' }}>· Leadership Exchange</span>
        <span className="ask-preview-surfaces" style={{ marginLeft: 'auto', display: 'flex', gap: 5 }}>
          {[
            { label: 'Slack', kind: 'slack', bg: 'var(--c-slack-bg)', fg: 'var(--c-slack)' },
            { label: 'Email', kind: 'email', bg: 'var(--c-email-bg)', fg: 'var(--c-email)' },
            { label: 'Community', kind: 'circle', bg: 'var(--c-circle-bg)', fg: 'var(--c-circle)' },
          ].map(surface => (
            <span key={surface.label} style={{ display: 'inline-flex', minHeight: 24, alignItems: 'center', gap: 4, fontSize: 9, fontWeight: 700, padding: '2px 6px 2px 3px', border: '1px solid ' + surface.fg, borderRadius: 4, background: surface.bg, color: surface.fg, letterSpacing: '.02em' }}>
              <PlatformIcon kind={surface.kind} size={15}/>{surface.label}
            </span>
          ))}
        </span>
      </div>

      {/* search bar */}
      <div className="ask-preview-query" style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '11px 14px', border: phase === 1 ? '1.5px solid var(--brand)' : '1px solid var(--site-line)', borderRadius: 12,
        background: '#FBFBFF', marginBottom: 14, minHeight: 58,
      }}>
        <SparkIcon color="var(--brand)"/>
        <span className="ask-preview-query-text" style={{ fontSize: 13, color: 'var(--site-ink)', flex: 1, lineHeight: 1.3 }}>
          {typed || '\u00a0'}
          {phase === 1 && <span style={{ display: 'inline-block', width: 2, height: 15, background: 'var(--brand)', marginLeft: 1, verticalAlign: 'middle', animation: 'ask-blink 1s infinite' }}/>} 
        </span>
      </div>

      {/* answer */}
      <div className="ask-preview-answer-slot" style={{ minHeight: 202, marginBottom: 14 }}>
        {phase === 2 && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0 0 36px', color: 'var(--site-ink-soft)', fontSize: 11.5 }}>
            <span style={{ display: 'flex', gap: 4 }}>
              {[0,1,2].map(i => (
                <span key={i} style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--brand)', opacity: .4, animation: `ask-bounce 1s ${i*0.15}s infinite` }}/>
              ))}
            </span>
            Searching conversations and resources…
          </div>
        )}
        {phase >= 3 && (
          <div style={{ animation: 'ask-in .5s both' }}>
            <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
              <div style={{
                width: 26, height: 26, borderRadius: 8, background: 'var(--brand-tint)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}><SparkIcon color="var(--brand)" size={14}/></div>
              <div className="ask-preview-answer-copy" style={{ fontSize: 12.5, color: 'var(--site-ink)', lineHeight: 1.5 }}>
                {scenario.answer}
                <span style={{ whiteSpace: 'nowrap', marginLeft: 3 }}>
                  {scenario.sources.map((source, i) => (
                    <sup key={source.title} style={{ color: 'var(--brand)', fontSize: 8.5, fontWeight: 700, marginLeft: 2 }}>[{i + 1}]</sup>
                  ))}
                </span>
              </div>
            </div>
            {/* Source posts */}
            <div style={{ marginTop: 12, marginLeft: 36 }}>
              <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--site-ink-soft)', marginBottom: 6 }}>
                Sources from your community
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                {scenario.sources.map((source, i) => (
                  <div className="ask-preview-source" key={source.title} style={{
                    display: 'grid', gridTemplateColumns: '20px 1fr auto', alignItems: 'center', gap: 7,
                    padding: '6px 8px', border: '1px solid var(--site-line)', borderRadius: 8, background: '#FBFBFF',
                  }}>
                    <span style={{ width: 18, height: 18, borderRadius: 5, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'var(--brand-tint)', color: 'var(--brand)', fontSize: 9, fontWeight: 800 }}>{i + 1}</span>
                    <span style={{ minWidth: 0 }}>
                      <span style={{ display: 'block', fontSize: 10.5, fontWeight: 650, color: 'var(--site-ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{source.title}</span>
                      <span style={{ display: 'block', fontSize: 9.5, color: 'var(--site-ink-soft)', marginTop: 1 }}>{source.meta}</span>
                    </span>
                    <span style={{ color: 'var(--brand)', fontSize: 11 }} aria-label="Read original post">↗</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* experts */}
      <div style={{ minHeight: 138 }}>
        {phase >= 4 && (
          <div style={{ borderTop: '1px solid var(--site-line)', paddingTop: 12, animation: 'ask-in .5s both' }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--site-ink-soft)', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
              <span>People who can help</span>
              <span style={{ fontSize: 9, fontWeight: 700, padding: '1px 6px', borderRadius: 999, background: 'var(--accent-mint-bg)', color: 'var(--accent-mint)' }}>experience match</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {experts.map((e, i) => (
                <div className="ask-preview-expert" key={e.name} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '8px 10px', border: '1px solid var(--site-line)', borderRadius: 12, background: '#fff',
                  animation: `ask-in .5s ${i*0.12}s both`,
                }}>
                  <PortraitAvatar name={e.name} color={e.color} size={32}/>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--site-ink)' }}>{e.name}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--site-ink-soft)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.why}</div>
                  </div>
                  <div className="ask-preview-expert-tags" style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-end', gap: 4, flexShrink: 0 }}>
                    {e.tags.map(t => (
                      <span key={t} style={{ fontSize: 9, fontWeight: 600, padding: '2px 6px', borderRadius: 999, background: e.color + '12', color: e.color }}>{t}</span>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      <style>{`
        @keyframes ask-blink { 50% { opacity: 0; } }
        @keyframes ask-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
        @keyframes ask-bounce { 0%,100% { transform: translateY(0); opacity: 0.4; } 50% { transform: translateY(-4px); opacity: 1; } }
      `}</style>
    </div>
  );
}

function SparkIcon({ color = 'var(--site-ink)', size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" style={{ flexShrink: 0 }}>
      <path d="M12 2l1.8 5.6a4 4 0 0 0 2.6 2.6L22 12l-5.6 1.8a4 4 0 0 0-2.6 2.6L12 22l-1.8-5.6a4 4 0 0 0-2.6-2.6L2 12l5.6-1.8a4 4 0 0 0 2.6-2.6L12 2z" fill={color}/>
    </svg>
  );
}

// ---------- Onboarding preview ----------
function OnboardingPreview() {
  const steps = [
    { when: 'Immediately after approval', via: 'slack', title: 'Welcome to Leadership Exchange, {FIRST_NAME}',
      preview: "Start with #member-asks, add your operating focus to the directory, and choose which conversations you want to follow." },
    { when: 'Day 2 · if Slack is not connected', via: 'email', title: 'Choose how you want to participate',
      preview: "You can join from email, the community home, or Slack. Set your preferred cadence and we’ll deliver the right conversations." },
    { when: 'Day 5 · if profile is incomplete', via: 'circle', title: 'Help the right members find you',
      preview: "Add your current role, operating experience, and the topics where you’re happy to help another member." },
    { when: 'Day 14', via: 'email', title: 'A useful first-two-weeks recap',
      preview: "Three conversations matched to your interests, two upcoming events, and one member whose experience overlaps with yours." },
  ];
  const [sequenceTick, setSequenceTick] = useStateHome(0);
  const reducedMotion = window.useReducedMotion();

  useEffectHome(() => {
    if (reducedMotion) {
      setSequenceTick(steps.length);
      return undefined;
    }
    const first = setTimeout(() => setSequenceTick(1), 400);
    const timer = setInterval(() => setSequenceTick(step => step >= 7 ? 0 : step + 1), 1100);
    return () => { clearTimeout(first); clearInterval(timer); };
  }, [reducedMotion]);

  const visibleCount = Math.min(sequenceTick, steps.length);

  return (
    <div className="product-preview onboarding-preview" style={{
      background: '#fff', border: '1px solid var(--site-line)', borderRadius: 20,
      padding: 24, boxShadow: '0 8px 30px rgba(26,27,58,0.06)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <ProductHeaderIcon kind="onboarding"/>
        <span style={{ fontSize: 13, fontWeight: 600 }}>Leadership Exchange · New Member Welcome</span>
        <span style={{ fontSize: 10, fontWeight: 600, padding: '2px 8px', borderRadius: 4,
          background: 'var(--accent-mint-bg)', color: 'var(--accent-mint)', marginLeft: 'auto' }}>Live</span>
      </div>
      {steps.map((m, i) => {
        const isVisible = visibleCount > i;
        return (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '30px 28px 1fr', gap: 10, padding: '14px 0',
          borderTop: i === 0 ? 'none' : '1px solid var(--site-line)',
          alignItems: 'flex-start',
          opacity: isVisible ? 1 : 0,
          transform: isVisible ? 'translateY(0)' : 'translateY(5px)',
          transition: 'opacity .55s ease, transform .55s ease',
        }}>
          <div style={{ position: 'relative', width: 30, alignSelf: 'stretch', minHeight: 64 }} aria-hidden="true">
            <span style={{
              position: 'absolute', left: 4, top: 1, width: 20, height: 20, borderRadius: '50%', zIndex: 2,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: `2px solid ${isVisible ? 'var(--brand)' : 'var(--site-line)'}`,
              background: isVisible ? 'var(--brand)' : '#fff', color: '#fff',
              fontSize: 9, fontWeight: 800, transition: 'all .45s ease',
            }}>{i + 1}</span>
            {i < steps.length - 1 && (
              <span style={{ position: 'absolute', left: 13, top: 22, bottom: -15, width: 2, background: 'var(--site-line)', overflow: 'hidden' }}>
                <span style={{
                  display: 'block', width: '100%', height: '100%', background: 'var(--brand)',
                  transformOrigin: 'top', transform: isVisible ? 'scaleY(1)' : 'scaleY(0)',
                  transition: 'transform .85s ease',
                }}/>
              </span>
            )}
          </div>
          <div style={{ width: 28, flexShrink: 0, paddingTop: 1 }}>
            <PlatformIcon kind={m.via} size={28}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4, flexWrap: 'wrap' }}>
              <span style={{ fontSize: 13, fontWeight: 600 }}>{m.title}</span>
            </div>
            <div style={{ fontSize: 11, color: 'var(--site-ink-soft)', marginBottom: 6 }}>Trigger · {m.when}</div>
            <div style={{ fontSize: 12, color: 'var(--site-ink)', lineHeight: 1.45 }}>{m.preview}</div>
          </div>
        </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { HomePage, AskPreview });
