// ─────────────────────────────────────────────────────────────
// Section A · Forests landing — discovery & search variants.
//
// The screenshot the user sent is the v1 of this screen. It shows
// PERSONAL → PUBLIC → DISCOVER stacked vertically, and Request/Join
// buttons inline. That collapses at scale.
//
// Three variants here:
//   A1 · Tabbed       — Yours / Discover / Search, clear modes.
//   A2 · Continuous   — sticky filter chips; one rich scroll.
//   A3 · Compass      — discover is anchored geographically; map-card.
//
// All three reuse the same row component so the visual language is
// consistent and we're trading information architecture, not styling.
// ─────────────────────────────────────────────────────────────


// ─── Shared header chrome ─────────────────────────────────────
function LandingHeader({ subtitle = '2 spaces growing.', leavesCount = 47, onOpenLeaves, children }) {
  return (
    <div style={{ flexShrink: 0, padding: '14px 18px 0' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ font: '500 10px var(--font-sans)', color: '#8A9678',
                        letterSpacing: '0.10em', textTransform: 'uppercase' }}>FORESTS</div>
          <div style={{ font: '500 26px var(--font-mono)', color: '#F2EDE4',
                        letterSpacing: '-0.01em', marginTop: 2 }}>forests</div>
          <div style={{ font: '400 italic 13px var(--font-serif)', color: '#8A9678', marginTop: 4 }}>
            {subtitle}
          </div>
        </div>
        <LeavesPill count={leavesCount} onClick={onOpenLeaves}/>
      </div>
      {children}
    </div>
  );
}


// Small in-header CTA — the entry point into the Viral Leaves feed.
// Persistent across all three Landing variants. The count animates
// when new leaves catch sunlight.
function LeavesPill({ count = 47, onClick }) {
  return (
    <button onClick={onClick} aria-label="Open viral leaves"
      style={{
        flexShrink: 0, marginTop: 4,
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '7px 11px 7px 9px',
        background: 'rgba(212,150,12,0.08)',
        border: '0.5px solid rgba(212,150,12,0.34)',
        borderRadius: 999, cursor: 'pointer',
        color: '#F4DCA0',
        font: '500 11.5px var(--font-mono)',
        transition: 'background 140ms var(--ease-organic), border-color 140ms var(--ease-organic)',
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'rgba(212,150,12,0.14)'}
      onMouseLeave={e => e.currentTarget.style.background = 'rgba(212,150,12,0.08)'}>
      <span style={{ position: 'relative', display: 'inline-flex' }}>
        <FLIcons.Sun size={13} color="#D4960C"/>
        <span style={{
          position: 'absolute', inset: -3, borderRadius: '50%',
          border: '1px solid #D4960C',
          animation: 'flCanopyRipple 2.4s var(--ease-organic) infinite',
          pointerEvents: 'none',
        }}/>
      </span>
      <CountUp value={count}/>
      <span style={{ color: '#A8C5A0', font: 'italic 400 11px var(--font-serif)' }}>leaves →</span>
    </button>
  );
}


// Universal forest row — used in all three variants.
function ForestRow({ f, mode = 'yours', onJoin = () => {}, onOpen = () => {} }) {
  const isPrivate = f.kind === 'private';
  const intensity = forestIntensity(f);
  const hot = intensity === 'hot' || (f.activeNow || 0) > 5;
  const Action = () => {
    if (mode === 'yours') return null;
    const stop = (fn) => (e) => { e.stopPropagation(); fn && fn(f); };
    if (f.join === 'open')      return <Btn kind="primary" size="sm" onClick={stop(onJoin)}>Join</Btn>;
    if (f.join === 'moderated') return <Btn kind="secondary" size="sm" onClick={stop(onJoin)}>Request</Btn>;
    if (f.join === 'referral')  return <Btn kind="ghost" size="sm" onClick={stop(onJoin)}>Referral →</Btn>;
    return null;
  };
  return (
    <RowAmbience seed={f.id} intensity={intensity} borderRadius={12}>
    <div role="button" tabIndex={0} onClick={() => onOpen(f)} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 12px',
      background: '#111D0A',
      border: '0.5px solid #1F2B16',
      borderLeft: isPrivate ? '2px solid #7A4F2D' : '0.5px solid #1F2B16',
      borderRadius: 12, textAlign: 'left', cursor: 'pointer',
      width: '100%', boxSizing: 'border-box',
      transition: 'background 140ms var(--ease-organic), transform 140ms var(--ease-organic)',
    }}
      onMouseEnter={e => e.currentTarget.style.background = '#162310'}
      onMouseLeave={e => e.currentTarget.style.background = '#111D0A'}>
      <BreathingForestGlyph size={32} hot={hot} intensity={intensity}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          <span style={{ font: '500 15px var(--font-sans)', color: '#F2EDE4' }}>{f.name}</span>
          <KindChip kind={f.kind}/>
          {f.join && f.join !== 'open' && <JoinChip mode={f.join}/>}
        </div>
        <div style={{ font: 'italic 400 12.5px var(--font-serif)', color: '#8A9678',
                      marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {f.blurb}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8,
                      font: '400 11px var(--font-sans)', color: '#586552', marginTop: 6 }}>
          <span>{fmtBig(f.members)} members</span>
          {f.growing != null && <><span>·</span><span>{f.growing} growing</span></>}
          {f.distanceMi != null && <><span>·</span><span>{f.distanceMi} mi</span></>}
          {f.mutualFolk > 0 && <><span>·</span><span style={{ color: '#A8C5A0' }}>{f.mutualFolk} folk</span></>}
          {f.activeNow > 0 && <><span style={{ flex: 1 }}/>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <SignalDot signal={f.signal}/>
              <LiveCounter baseline={f.activeNow} range={2}
                style={{ font: '500 11px var(--font-mono)', color: '#A8C5A0' }}/>
            </span>
          </>}
        </div>
      </div>
      {f.unread > 0 && (
        <span style={{
          font: '500 11px var(--font-mono)', color: '#0B1306',
          background: '#D4960C', borderRadius: 999,
          padding: '1px 7px', minWidth: 18, textAlign: 'center',
          alignSelf: 'flex-start', marginTop: 4,
        }}>{f.unread}</span>
      )}
      <span style={{ marginLeft: 8 }} onClick={e => e.stopPropagation()}><Action/></span>
    </div>
    </RowAmbience>
  );
}


// ──────────────────────────────────────────────────────────────
// A1 · Tabbed landing — Yours / Discover / Search.
// Tab switch is a 220ms cross-fade.
// ──────────────────────────────────────────────────────────────
function LandingA1_Tabbed() {
  const [tab, setTab] = React.useState('discover');
  const [view, setView] = React.useState('forests');

  if (view === 'leaves') {
    return <ViralE1_VelocityFeed onBack={() => setView('forests')}/>;
  }

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0,
                  background: '#0B1306' }}>
      <LandingHeader subtitle="where strangers grow into something."
        onOpenLeaves={() => setView('leaves')}>
        <div style={{ marginTop: 12, display: 'flex', gap: 4, padding: 3,
                      background: '#111D0A', border: '0.5px solid #2D3A22', borderRadius: 10 }}>
          {['yours', 'discover', 'search'].map(t => (
            <button key={t} onClick={() => setTab(t)} style={{
              flex: 1, height: 32, padding: '0 10px', border: 'none',
              background: tab === t ? '#1B3A1D' : 'transparent',
              color: tab === t ? '#F2EDE4' : '#586552',
              borderRadius: 8, cursor: 'pointer',
              font: '500 12px var(--font-sans)',
              transition: 'background 160ms var(--ease-organic), color 160ms var(--ease-organic)',
            }}>{t === 'yours' ? 'yours · 2' : t === 'discover' ? `discover · ${fmtBig(DISCOVER_COUNT_TOTAL)}` : 'search'}</button>
          ))}
        </div>
      </LandingHeader>

      <PhoneBody style={{ padding: '12px 14px 80px' }}>
        {tab === 'yours' && <YoursPane/>}
        {tab === 'discover' && <DiscoverPane/>}
        {tab === 'search' && <SearchPane/>}
      </PhoneBody>

      <BottomNavFolk active="forests" hasNewSunlight={false}/>
    </div>
  );
}


function YoursPane() {
  const list = YOUR_FORESTS.slice(0, 4);
  return (
    <LeafStagger staggerMs={45} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <SectionLabel label="Personal" right="private" />
      {list.filter(f => f.kind === 'private').map(f => <ForestRow key={f.id} f={f}/>)}
      <SectionLabel label="Public" right={`${list.filter(f => f.kind !== 'private').length}`} />
      {list.filter(f => f.kind !== 'private').map(f => <ForestRow key={f.id} f={f}/>)}
    </LeafStagger>
  );
}


function DiscoverPane() {
  const [topic, setTopic] = React.useState(null);
  const filtered = topic ? DISCOVER_FORESTS.filter(f => f.topic === topic) : DISCOVER_FORESTS;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {/* Topic chips */}
      <div style={{ overflowX: 'auto', overflowY: 'hidden', margin: '0 -14px 0 -14px', padding: '0 14px' }}>
        <div style={{ display: 'flex', gap: 6, whiteSpace: 'nowrap' }}>
          <TopicChip label="All" active={!topic} onClick={() => setTopic(null)}/>
          {DISCOVER_TOPICS.map(t => (
            <TopicChip key={t.id} label={t.label}
              active={topic === t.id} onClick={() => setTopic(t.id === topic ? null : t.id)}/>
          ))}
        </div>
      </div>

      <SectionLabel label="Near you · now" right="signal" sub="rising in the last 6h"/>
      <LeafStagger staggerMs={50} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {filtered.map(f => <ForestRow key={f.id} f={f} mode="discover" />)}
      </LeafStagger>

      <button style={{
        marginTop: 8, padding: '12px 14px', background: 'transparent',
        border: '0.5px dashed #2D3A22', borderRadius: 12,
        font: 'italic 400 12.5px var(--font-serif)', color: '#8A9678',
        cursor: 'pointer', textAlign: 'left',
      }}>
        {fmtBig(DISCOVER_COUNT_TOTAL)} forests in the directory — browse by topic →
      </button>
    </div>
  );
}


function SearchPane({ onPlantNew }) {
  return (
    <div style={{ margin: '0 -14px' }}>
      <ForestSearchBar value="cycling" onChange={() => {}} onClear={() => {}}/>
      <ForestSearchResults query="cycling" onPlantNew={onPlantNew || (() => {})}/>
    </div>
  );
}


function TopicChip({ label, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      padding: '6px 11px', border: '0.5px solid',
      borderColor: active ? '#4F8E51' : '#2D3A22',
      background: active ? '#1B3A1D' : 'transparent',
      color: active ? '#F2EDE4' : '#8A9678',
      borderRadius: 999, cursor: 'pointer',
      font: '500 12px var(--font-sans)',
      transition: 'all 140ms var(--ease-organic)',
    }}>{label}</button>
  );
}


function SectionLabel({ label, right, sub }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 6 }}>
      <span style={{ font: '500 10.5px var(--font-sans)', color: '#76AB78',
                     letterSpacing: '0.12em', textTransform: 'uppercase' }}>{label}</span>
      {sub && <span style={{ font: 'italic 400 11px var(--font-serif)', color: '#586552' }}>· {sub}</span>}
      <span style={{ flex: 1 }}/>
      {right && <span style={{ font: '400 11px var(--font-sans)', color: '#586552' }}>{right}</span>}
    </div>
  );
}


// ──────────────────────────────────────────────────────────────
// A2 · Continuous — single scroll, sticky filter chips.
// Closest to the current screen but keeps signal sane at scale.
// ──────────────────────────────────────────────────────────────
function LandingA2_Continuous() {
  const [filter, setFilter] = React.useState('all');
  const [view, setView] = React.useState('forests');
  if (view === 'leaves') return <ViralE1_VelocityFeed onBack={() => setView('forests')}/>;
  if (view === 'search') return <ForestSearchScreen onBack={() => setView('forests')} autoFocus/>;

  const filtered = filter === 'rising'
      ? DISCOVER_FORESTS.filter(f => f.signal === 'rising')
    : filter === 'open'
      ? DISCOVER_FORESTS.filter(f => f.join === 'open')
    : filter === 'near'
      ? DISCOVER_FORESTS.filter(f => f.distanceMi != null)
    : DISCOVER_FORESTS;

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0,
                  background: '#0B1306' }}>
      <LandingHeader subtitle="2 growing. tens of thousands more."
        onOpenLeaves={() => setView('leaves')}>
        <div onClick={() => setView('search')}
             role="button" tabIndex={0} aria-label="Search forests"
             style={{ marginTop: 12, height: 42, padding: '0 12px',
                      background: '#111D0A', border: '0.5px solid #2D3A22', borderRadius: 10,
                      display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
                      transition: 'border-color 160ms var(--ease-organic)' }}
             onMouseEnter={e => e.currentTarget.style.borderColor = '#4F8E51'}
             onMouseLeave={e => e.currentTarget.style.borderColor = '#2D3A22'}>
          <FLIcons.Search size={16} color="#586552"/>
          <span style={{ flex: 1, font: 'italic 400 14px var(--font-serif)', color: '#586552' }}>
            Find a forest, leaf, or folk…
          </span>
        </div>
      </LandingHeader>

      <PhoneBody style={{ padding: '12px 14px 80px' }}>
        <LeafStagger staggerMs={40} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <SectionLabel label="Yours" right="2"/>
          {YOUR_FORESTS.slice(0, 2).map(f => <ForestRow key={f.id} f={f}/>)}
        </LeafStagger>

        <div style={{ marginTop: 16, marginBottom: 8, position: 'sticky', top: 0,
                      background: 'linear-gradient(180deg, #0B1306 0%, #0B1306 80%, transparent 100%)',
                      paddingBottom: 8, paddingTop: 4, zIndex: 2 }}>
          <SectionLabel label="Discover" sub={`${fmtBig(DISCOVER_COUNT_TOTAL)} forests`}/>
          <div style={{ display: 'flex', gap: 6, marginTop: 8, overflowX: 'auto' }}>
            {[
              ['all', 'All'], ['rising', 'Rising'], ['near', 'Near you'],
              ['open', 'Open join'], ['mods', 'Moderated'],
            ].map(([k, l]) =>
              <TopicChip key={k} label={l}
                active={filter === k}
                onClick={() => setFilter(k)}/>
            )}
          </div>
        </div>

        <LeafStagger key={filter} staggerMs={45}
          style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {filtered.map(f => <ForestRow key={f.id} f={f} mode="discover" />)}
        </LeafStagger>

        <button style={{
          marginTop: 14, padding: '12px 14px', background: 'transparent',
          border: '0.5px dashed #2D3A22', borderRadius: 12, width: '100%',
          font: 'italic 400 12.5px var(--font-serif)', color: '#8A9678',
          cursor: 'pointer', textAlign: 'left',
        }}>
          + Have a referral code?
        </button>
      </PhoneBody>

      <BottomNavFolk active="forests" hasNewSunlight={false}/>
    </div>
  );
}


// ──────────────────────────────────────────────────────────────
// A3 · Compass — discover is geographic + interest-anchored.
// Hero card shows the user's "neighbourhood of forests" as a small
// rendered map. Then list rolls in by signal.
// ──────────────────────────────────────────────────────────────
function LandingA3_Compass() {
  const [view, setView] = React.useState('forests');
  if (view === 'leaves') return <ViralE1_VelocityFeed onBack={() => setView('forests')}/>;
  if (view === 'search') return <ForestSearchScreen onBack={() => setView('forests')} autoFocus/>;
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0,
                  background: '#0B1306' }}>
      <LandingHeader subtitle="forests around you, growing now."
        onOpenLeaves={() => setView('leaves')}>
        <div onClick={() => setView('search')}
             role="button" tabIndex={0} aria-label="Search forests"
             style={{ marginTop: 12, height: 42, padding: '0 12px',
                      background: '#111D0A', border: '0.5px solid #2D3A22', borderRadius: 10,
                      display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
          <FLIcons.Search size={16} color="#586552"/>
          <span style={{ flex: 1, font: 'italic 400 14px var(--font-serif)', color: '#586552' }}>
            Find a forest…
          </span>
        </div>
      </LandingHeader>

      <PhoneBody style={{ padding: '12px 14px 80px' }}>
        <CompassMap/>

        <SectionLabel label="Within walking distance" right="signal" sub="3 forests"/>
        <LeafStagger staggerMs={50} style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 6 }}>
          {DISCOVER_FORESTS.filter(f => f.distanceMi != null).map(f =>
            <ForestRow key={f.id} f={f} mode="discover"/>
          )}
        </LeafStagger>

        <div style={{ marginTop: 18 }}>
          <SectionLabel label="By interest" sub="from your folk"/>
          <LeafStagger staggerMs={50} style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 6 }}>
            {DISCOVER_FORESTS.filter(f => f.distanceMi == null).slice(0, 3).map(f =>
              <ForestRow key={f.id} f={f} mode="discover"/>
            )}
          </LeafStagger>
        </div>
      </PhoneBody>

      <BottomNavFolk active="forests" hasNewSunlight={false}/>
    </div>
  );
}


// Tiny "you-are-here" compass card. SVG only.
function CompassMap() {
  return (
    <div style={{ position: 'relative', overflow: 'hidden',
                  borderRadius: 14, border: '0.5px solid #2D3A22',
                  background: '#0F1A09', padding: 14, marginBottom: 14 }}>
      <SunbeamSweep/>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ font: '500 10.5px var(--font-sans)', color: '#76AB78',
                       letterSpacing: '0.14em', textTransform: 'uppercase' }}>You are here</span>
        <span style={{ font: 'italic 400 11.5px var(--font-serif)', color: '#A8C5A0' }}>
          Mission, SF · 0.4 mi
        </span>
      </div>
      <svg viewBox="0 0 320 140" style={{ width: '100%', height: 140, marginTop: 6 }}>
        {/* grid */}
        {Array.from({ length: 7 }).map((_, i) => (
          <line key={'h' + i} x1="0" y1={i * 22} x2="320" y2={i * 22}
                stroke="#1F2B16" strokeWidth="0.5"/>
        ))}
        {Array.from({ length: 10 }).map((_, i) => (
          <line key={'v' + i} x1={i * 36} y1="0" x2={i * 36} y2="140"
                stroke="#1F2B16" strokeWidth="0.5"/>
        ))}
        {/* park overlay — soft moss */}
        <path d="M 200 30 Q 250 20 280 50 Q 290 90 240 100 Q 200 95 200 30 Z"
              fill="#1B3A1D" fillOpacity="0.6" stroke="#2C5F2E" strokeWidth="0.5"/>
        {/* you */}
        <circle cx="120" cy="80" r="6" fill="#D4960C">
          <animate attributeName="r" values="6;8;6" dur="2.4s" repeatCount="indefinite"/>
        </circle>
        <circle cx="120" cy="80" r="12" fill="none" stroke="#D4960C" strokeWidth="0.5" opacity="0.45"/>
        {/* nearby forest nodes */}
        {[[60,40,'Mission Bay Walks'],[180,55,'Slow Cooking'],[155,110,'Long-distance Cycling']].map(([x,y,n],i) => (
          <g key={i}>
            <circle cx={x} cy={y} r="4" fill="#5E8048"/>
            <circle cx={x} cy={y} r="9" fill="none" stroke="#5E8048" strokeOpacity="0.35" strokeWidth="0.5"/>
            <text x={x + 10} y={y + 3} fill="#A8C5A0" fontSize="9"
                  fontFamily="JetBrains Mono, monospace">{n}</text>
            <line x1="120" y1="80" x2={x} y2={y}
                  stroke="#5E8048" strokeOpacity="0.25" strokeWidth="0.4"/>
          </g>
        ))}
      </svg>
    </div>
  );
}


Object.assign(window, {
  LandingA1_Tabbed, LandingA2_Continuous, LandingA3_Compass,
  ForestRow, LandingHeader, SectionLabel, TopicChip, CompassMap,
});
