// ─────────────────────────────────────────────────────────────
// Section E · Viral leaves.
//
// The brief: a separate view inside Forests that surfaces "viral
// leaves" — high-velocity replies across forests. Think reddit/hn
// but in forest grammar. The challenge: leaves are *deep* — they
// only make sense in context (forest → tree → branch → leaf).
//
// Three variants:
//   E1 · Velocity feed     — chronological by velocity, full-card
//                            "branch in context" with root tease.
//   E2 · Compact cards     — denser hn-style list with quick votes
//                            (sunlight) and inline reveal of context.
//   E3 · Galaxy view       — leaves drawn as glowing nodes orbiting
//                            forest-rings, sized by velocity. Tap a
//                            node opens its card.
//
// All three are reachable from the Forests tab as a sibling view
// (toggle in the header) or a new bottom-nav slot in some variants.
// ─────────────────────────────────────────────────────────────


// ─── Shared header for the viral feed ───
function ViralHeader({ sort = 'velocity', onSetSort, onBack }) {
  return (
    <div style={{ flexShrink: 0, padding: '14px 18px 8px' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
        {onBack && (
          <button onClick={onBack}
            style={{ background: 'transparent', border: 'none', padding: '6px 6px 6px 0',
                     marginTop: 18, color: '#A8C5A0', cursor: 'pointer', display: 'flex' }}
            aria-label="Back to forests">
            <FLIcons.ChevronLeft size={22}/>
          </button>
        )}
        <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 }}>
            <span style={{ color: '#F4DCA0' }}>leaves</span>
            <span style={{ color: '#586552', fontSize: 18, marginLeft: 8 }}>· growing fast</span>
          </div>
          <div style={{ font: '400 italic 13px var(--font-serif)', color: '#8A9678', marginTop: 4 }}>
            What's catching sunlight across your forests.
          </div>
        </div>
      </div>
      <div style={{ marginTop: 12, display: 'flex', gap: 4, padding: 3,
                    background: '#111D0A', border: '0.5px solid #2D3A22', borderRadius: 10 }}>
        {[['velocity','Velocity'],['new','New'],['week','This week'],['near','Near you']].map(([k,l]) => (
          <button key={k} onClick={() => onSetSort && onSetSort(k)} style={{
            flex: 1, height: 30, padding: '0 8px', border: 'none',
            background: sort === k ? '#1B3A1D' : 'transparent',
            color: sort === k ? '#F2EDE4' : '#586552',
            borderRadius: 8, cursor: 'pointer',
            font: '500 11.5px var(--font-sans)',
            transition: 'background 160ms var(--ease-organic), color 160ms var(--ease-organic)',
          }}>{l}</button>
        ))}
      </div>
    </div>
  );
}


// ──────────────────────────────────────────────────────────────
// E1 · Velocity feed
// Full cards. Each shows the root above (compressed) and the actual
// branch/leaf that's getting sunlight, with a forest pip and live
// activity. Sunlight count animates as you watch.
// ──────────────────────────────────────────────────────────────
function ViralE1_VelocityFeed({ onBack }) {
  const [sort, setSort] = React.useState('velocity');
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, background: '#0B1306' }}>
      <ViralHeader sort={sort} onSetSort={setSort} onBack={onBack}/>
      {/* Live ticker just below the header. The pulse of the whole feed. */}
      <div style={{ padding: '0 18px 8px', flexShrink: 0 }}>
        <LiveLeafTicker/>
      </div>
      <PhoneBody style={{ padding: '8px 14px 90px' }}>
        {/* First card gets a "new" bloom — simulates a fresh leaf landing */}
        <div data-fl-anim style={{
          animation: 'flNewLeafBloom 700ms var(--ease-organic) both',
          transformOrigin: 'top',
          overflow: 'hidden',
        }}>
          <ViralCard v={VIRAL_LEAVES[0]} isNew rank={1}/>
        </div>
        <LeafStagger staggerMs={70}
          style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 10 }}>
          {VIRAL_LEAVES.slice(1).map((v, i) => (
            <ViralCard key={v.id} v={v} rank={i + 2}/>
          ))}
        </LeafStagger>
      </PhoneBody>
      <BottomNavFolk active="forests" hasNewSunlight={true}/>
    </div>
  );
}


function ViralCard({ v, isNew, rank }) {
  const hot = v.signal === 'hot' || v.signal === 'rising';
  // Parse the +N/h number so the velocity badge can pulse with intent.
  const velNum = parseInt(String(v.velocity).replace(/[^0-9]/g, ''), 10) || 5;
  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      padding: '14px 14px', background: '#111D0A',
      border: '0.5px solid #1F2B16', borderRadius: 14,
    }}>
      <LeafDriftOverlay seed={v.id} count={hot ? 5 : v.signal === 'steady' ? 3 : 2}/>
      {v.signal === 'hot' && <SunbeamSweep/>}
      <div style={{ position: 'relative', zIndex: 1 }}>
      {/* Forest header pip */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {rank && (
          <span style={{
            font: '500 11px var(--font-mono)', color: '#586552',
            minWidth: 18, textAlign: 'right',
          }}>{rank}.</span>
        )}
        <ForestGlyph size={18} hot={hot} alive intensity={hot ? 'hot' : v.signal === 'quiet' ? 'quiet' : 'warm'}/>
        <span style={{ font: '500 12px var(--font-mono)', color: '#F2EDE4' }}>{v.forest}</span>
        <KindChip kind={v.kind}/>
        {isNew && <PositionDelta isNew/>}
        <span style={{ flex: 1 }}/>
        <VelocityBadge velocity={v.velocity} seed={v.id} velNum={velNum}/>
      </div>

      {/* Root tease */}
      <div style={{
        marginTop: 10, paddingLeft: 12,
        borderLeft: '2px solid #2D3A22',
        font: '400 12px/1.5 var(--font-sans)', color: '#8A9678',
      }}>
        <span style={{ font: '500 11.5px var(--font-mono)', color: '#A8C5A0' }}>{v.rootHandle}</span>
        <span style={{ color: '#586552' }}> · root</span>
        <div style={{ font: 'italic 400 12.5px/1.55 var(--font-serif)', color: '#8A9678',
                      marginTop: 3 }}>
          "{v.rootSnippet}"
        </div>
      </div>

      {/* Growing spur — dashes flow like sap toward the branch */}
      <div style={{ marginTop: 2, marginBottom: 2 }}>
        <GrowingSpur height={22}/>
      </div>

      {/* The viral branch itself */}
      <div style={{
        marginLeft: 16,
        padding: '11px 13px',
        background: '#0F1A09',
        border: '0.5px solid #2D3A22', borderRadius: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <NodeDot depth={v.depth} active/>
          <span style={{ font: '500 13px var(--font-mono)', color: '#F2EDE4' }}>{v.branchHandle}</span>
          <span style={{ font: '400 11px var(--font-sans)', color: '#586552' }}>· {v.branchAge}</span>
        </div>
        <div style={{ font: '400 14px/1.5 var(--font-sans)', color: '#F2EDE4', marginTop: 8 }}>
          {v.branch}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 12 }}>
          <PullSunlight count={v.sunlight}/>
          <span style={{ font: '400 11.5px var(--font-sans)', color: '#8A9678',
                          display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <FLIcons.Branch size={12} color="#8A9678"/> {v.branches}
          </span>
          <span style={{ font: '400 11.5px var(--font-sans)', color: '#8A9678' }}>· {v.leaves} leaves</span>
          <span style={{ flex: 1 }}/>
          <span style={{ font: '500 11.5px var(--font-sans)', color: '#76AB78' }}>Branch →</span>
        </div>
      </div>
      </div>
    </div>
  );
}


// Velocity badge — sparkline + the +N/h number.  The sparkline gives
// the velocity number a *shape*, not just a value.
function VelocityBadge({ velocity, seed, velNum }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '3px 10px 3px 7px',
      background: 'rgba(212,150,12,0.10)',
      border: '0.5px solid rgba(212,150,12,0.30)',
      borderRadius: 999,
    }}>
      <VelocitySpark seed={seed} velocity={velNum} height={14} width={36} color="#D4960C"/>
      <span style={{ font: '500 11px var(--font-mono)', color: '#F4DCA0' }}>
        {velocity}
      </span>
    </span>
  );
}


// ──────────────────────────────────────────────────────────────
// E2 · Compact cards
// Denser HN-style. Each row is one branch; tap reveals root + thread
// tease inline. Designed for quick scanning of dozens at once.
// ──────────────────────────────────────────────────────────────
function ViralE2_Compact() {
  const [sort, setSort] = React.useState('velocity');
  const [open, setOpen] = React.useState('v1');
  // Fake position-change so the list reads as alive.
  const deltas = [3, -1, 5, 0, -2, 0];
  const isNew = (i) => i === 0;
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, background: '#0B1306' }}>
      <ViralHeader sort={sort} onSetSort={setSort}/>
      <div style={{ padding: '0 18px 8px', flexShrink: 0 }}>
        <LiveLeafTicker/>
      </div>
      <PhoneBody style={{ padding: '6px 14px 90px' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {VIRAL_LEAVES.map((v, i) => (
            <CompactViralRow key={v.id} v={v} index={i + 1}
              delta={deltas[i] || 0} isNew={isNew(i)}
              isOpen={open === v.id}
              onToggle={() => setOpen(open === v.id ? null : v.id)}/>
          ))}
        </div>
      </PhoneBody>
      <BottomNavFolk active="forests" hasNewSunlight={true}/>
    </div>
  );
}


function CompactViralRow({ v, index, isOpen, onToggle, delta = 0, isNew = false }) {
  const velNum = parseInt(String(v.velocity).replace(/[^0-9]/g, ''), 10) || 5;
  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      background: '#111D0A',
      border: `0.5px solid ${isOpen ? '#2D3A22' : '#1F2B16'}`,
      borderRadius: 12,
      transition: 'border-color 220ms var(--ease-organic)',
    }}>
      <LeafDriftOverlay seed={v.id} count={isNew ? 4 : 2} borderRadius={12}/>
      <button onClick={onToggle} style={{
        display: 'flex', alignItems: 'flex-start', gap: 10,
        padding: '11px 12px', background: 'transparent', border: 'none',
        width: '100%', cursor: 'pointer', textAlign: 'left',
        position: 'relative', zIndex: 1,
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center',
                       gap: 4, width: 26, flexShrink: 0, paddingTop: 2 }}>
          <span style={{ font: '500 13px var(--font-mono)', color: '#586552' }}>{index}</span>
          <PositionDelta delta={delta} isNew={isNew}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ font: '400 13.5px/1.45 var(--font-sans)', color: '#F2EDE4' }}>
            {v.branch}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6,
                        font: '400 11px var(--font-sans)', color: '#586552', flexWrap: 'wrap' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <FLIcons.Sun size={11} color="#D4960C"/>
              <LiveSunlightCount baseline={v.sunlight} intervalMs={3500 + index * 600}
                style={{ color: '#F4DCA0', fontFamily: 'var(--font-mono)' }}/>
            </span>
            <span>·</span>
            <VelocitySpark seed={v.id} velocity={velNum} height={10} width={32} color="#D4960C"/>
            <span style={{ color: '#A8C5A0' }}>{v.velocity}</span>
            <span>·</span>
            <span>{v.branchHandle}</span>
            <span>·</span>
            <span>{v.branchAge}</span>
            <span style={{ flex: 1 }}/>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5,
                            color: '#A8C5A0' }}>
              <ForestGlyph size={12} hot alive intensity={v.signal === 'hot' ? 'hot' : 'warm'}/>
              {v.forest}
            </span>
          </div>
        </div>
      </button>
      {isOpen && (
        <div style={{ padding: '0 12px 12px 48px', position: 'relative', zIndex: 1,
                      animation: 'flSlideDown 320ms var(--ease-organic) both' }}>
          <div style={{
            padding: '10px 12px', background: '#0F1A09', borderRadius: 10,
            borderLeft: '2px solid #2D3A22',
            font: 'italic 400 12.5px/1.55 var(--font-serif)', color: '#8A9678',
          }}>
            <span style={{ font: '500 11.5px var(--font-mono)', color: '#A8C5A0',
                            fontStyle: 'normal' }}>{v.rootHandle}</span>
            <span style={{ color: '#586552' }}> · root → </span>
            "{v.rootSnippet}"
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
            <Btn kind="primary" size="sm">Open the tree →</Btn>
            <Btn kind="secondary" size="sm">Branch from here</Btn>
            <PullSunlight count={v.sunlight}/>
          </div>
        </div>
      )}
    </div>
  );
}


// ──────────────────────────────────────────────────────────────
// E3 · Galaxy view
// Visual mode — leaves drawn as glowing dots orbiting their forest's
// ring. Size = sunlight; brightness = velocity; tap reveals the
// branch card. This is the "signature" view the brief asked for.
// ──────────────────────────────────────────────────────────────
function ViralE3_Galaxy() {
  const [selected, setSelected] = React.useState('v1');
  const sel = VIRAL_LEAVES.find(v => v.id === selected);
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, background: '#0B1306' }}>
      <ViralHeader sort="velocity"/>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        {/* Galaxy canvas */}
        <div style={{
          position: 'relative', height: 360, margin: '8px 14px 0',
          borderRadius: 16, overflow: 'hidden',
          background: 'radial-gradient(ellipse at center, #0F1A09 0%, #07100A 70%)',
          border: '0.5px solid #1F2B16',
        }}>
          <GalaxySvg selected={selected} onSelect={setSelected}/>
          <ShootingStars count={3}/>
          <div style={{
            position: 'absolute', top: 10, left: 14, zIndex: 2,
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{ position: 'relative', display: 'inline-flex' }}>
              <FLIcons.Sun size={11} color="#D4960C"/>
              <span data-fl-anim style={{
                position: 'absolute', inset: -3, borderRadius: '50%',
                border: '1px solid #D4960C', opacity: 0.55,
                animation: 'flCanopyRipple 2.4s var(--ease-organic) infinite',
              }}/>
            </span>
            <span style={{
              font: '500 10px var(--font-sans)', color: '#F4DCA0',
              letterSpacing: '0.14em', textTransform: 'uppercase',
            }}>
              <LiveSunlightCount baseline={6} intervalMs={5000}/> leaves catching sun
            </span>
          </div>
          <div style={{
            position: 'absolute', bottom: 10, right: 14, zIndex: 2,
            font: 'italic 400 11px var(--font-serif)', color: '#586552',
          }}>
            tap a node →
          </div>
        </div>

        {/* Selected card */}
        <PhoneBody style={{ padding: '14px 14px 90px' }}>
          {sel && (
            <div key={sel.id} style={{ animation: 'flSheetEnter 320ms var(--ease-organic) both' }}>
              <ViralCard v={sel}/>
            </div>
          )}
        </PhoneBody>
      </div>
      <BottomNavFolk active="forests" hasNewSunlight={true}/>
    </div>
  );
}


function GalaxySvg({ selected, onSelect }) {
  const W = 362, H = 360;
  const cx = W / 2, cy = H / 2;
  // Group leaves by forest, lay each forest on a ring at radius based on
  // forest activity. Within a forest's ring, leaves are spread by angle.
  const forests = {};
  VIRAL_LEAVES.forEach(v => {
    if (!forests[v.forest]) forests[v.forest] = [];
    forests[v.forest].push(v);
  });
  const forestNames = Object.keys(forests);
  const rings = forestNames.map((name, i) => ({
    name, r: 80 + i * 35, leaves: forests[name],
  }));
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%">
      {/* Faint background dust */}
      {Array.from({ length: 40 }).map((_, i) => {
        const a = Math.random() * Math.PI * 2;
        const r = Math.random() * 160 + 20;
        return <circle key={i} cx={cx + Math.cos(a) * r} cy={cy + Math.sin(a) * r}
          r="0.6" fill="#445239" opacity={0.4 + Math.random() * 0.4}/>;
      })}
      {/* Forest rings */}
      {rings.map((ring, i) => (
        <g key={ring.name}>
          <circle cx={cx} cy={cy} r={ring.r}
                  fill="none" stroke="#4F8E51" strokeOpacity="0.18" strokeWidth="0.7"/>
          <text x={cx + ring.r + 6} y={cy + 3} fill="#586552" fontSize="9"
                fontFamily="JetBrains Mono, monospace">{ring.name}</text>
          {ring.leaves.map((v, j) => {
            const angle = (j / ring.leaves.length) * Math.PI * 2 - Math.PI / 2 + i * 0.4;
            const x = cx + Math.cos(angle) * ring.r;
            const y = cy + Math.sin(angle) * ring.r;
            const size = 4 + Math.min(12, v.sunlight / 12);
            const isSel = v.id === selected;
            return (
              <g key={v.id} onClick={() => onSelect(v.id)} style={{ cursor: 'pointer' }}>
                {isSel && (
                  <circle cx={x} cy={y} r={size + 8} fill="none"
                    stroke="#D4960C" strokeWidth="1" opacity="0.6">
                    <animate attributeName="r" values={`${size+6};${size+14};${size+6}`} dur="2s" repeatCount="indefinite"/>
                    <animate attributeName="opacity" values="0.7;0;0.7" dur="2s" repeatCount="indefinite"/>
                  </circle>
                )}
                <circle cx={x} cy={y} r={size}
                  fill={isSel ? '#D4960C' : '#A8C5A0'}
                  opacity={v.signal === 'hot' ? 1 : 0.85}>
                  {v.signal !== 'quiet' && (
                    <animate attributeName="opacity"
                      values={`${v.signal === 'hot' ? 1 : 0.7};1;${v.signal === 'hot' ? 1 : 0.7}`}
                      dur={`${v.signal === 'hot' ? 1.8 : 3.6}s`}
                      repeatCount="indefinite"/>
                  )}
                </circle>
                <text x={x + size + 5} y={y + 3} fill="#8A9678" fontSize="8"
                      fontFamily="JetBrains Mono, monospace">{v.branchHandle}</text>
              </g>
            );
          })}
        </g>
      ))}
      {/* You at center */}
      <circle cx={cx} cy={cy} r="5" fill="#4F8E51"/>
      <circle cx={cx} cy={cy} r="11" fill="none" stroke="#4F8E51" strokeOpacity="0.45" strokeWidth="0.6"/>
    </svg>
  );
}


Object.assign(window, {
  ViralE1_VelocityFeed, ViralE2_Compact, ViralE3_Galaxy,
});
