// ─────────────────────────────────────────────────────────────
// Section D · Folk + DM integration.
//
// The brief: today, a user message lives inside the Forests tab as
// "Personal · marina_k" — that pollutes Forests. We want the Folk tab
// to carry DM context, but the profile view must remain intact.
//
// Three variants — they overlap in spirit, they trade in mechanics:
//   D1 · Inline accordion   — tap row, it expands in place: latest DM,
//                              quick-reply, "open thread", profile below.
//   D2 · Stacked sheet      — the existing ConnectSheet gets a "Letters"
//                              section pinned to the top; messages are
//                              full-bleed cards; profile lives below.
//   D3 · Swipe-peek         — leftward swipe on a Folk row reveals the
//                              DM thread without losing list position.
//
// All three: the Forests tab loses the "Personal · marina_k" block.
// DMs live entirely in Folk.
// ─────────────────────────────────────────────────────────────


// ─── Shared: the new Folk landing (without the personal-forest list) ───
// The Folk tab gets a small "Letters" section at the top showing
// folk with unread DMs. Beats the v1 ConnectSheet path for surfacing
// fresh messages.

function FolkLandingShell({ children, dmStripe = true, expandedHandle = null }) {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, background: '#0B1306' }}>
      <div style={{ padding: '14px 18px 6px', flexShrink: 0 }}>
        <div style={{ font: '500 10px var(--font-sans)', color: '#8A9678',
                      letterSpacing: '0.10em', textTransform: 'uppercase' }}>FOLK</div>
        <div style={{ font: '500 26px var(--font-mono)', color: '#F2EDE4',
                      letterSpacing: '-0.01em', marginTop: 2 }}>folk</div>
        <div style={{ font: '400 italic 13px var(--font-serif)', color: '#8A9678', marginTop: 4 }}>
          Letters and lattices.
        </div>
      </div>

      {dmStripe && (
        <div style={{ padding: '6px 14px 10px', flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, padding: '4px 4px 8px' }}>
            <span style={{ font: '500 10.5px var(--font-sans)', color: '#F4DCA0',
                           letterSpacing: '0.12em', textTransform: 'uppercase' }}>Letters</span>
            <span style={{ font: 'italic 400 11px var(--font-serif)', color: '#586552' }}>· 2 unread</span>
            <span style={{ flex: 1 }}/>
            <span style={{ font: '400 11px var(--font-sans)', color: '#A8C5A0' }}>open all →</span>
          </div>
          <div style={{ display: 'flex', gap: 8, overflowX: 'auto',
                        scrollbarWidth: 'none', paddingBottom: 4 }}>
            {Object.values(DM_THREADS).filter(t => t.unread > 0).map(t => (
              <DmPill key={t.handle} thread={t}/>
            ))}
            {Object.values(DM_THREADS).filter(t => t.unread === 0).map(t => (
              <DmPill key={t.handle} thread={t}/>
            ))}
          </div>
        </div>
      )}

      <PhoneBody style={{ padding: '6px 14px 90px' }}>
        {children}
      </PhoneBody>

      <BottomNavFolk active="folk" hasNewSunlight={true}/>
    </div>
  );
}


function DmPill({ thread }) {
  const accent = thread.unread ? '#D4960C' : '#5E8048';
  return (
    <button style={{
      flexShrink: 0, padding: '8px 12px 9px',
      background: '#111D0A', border: `0.5px solid ${thread.unread ? 'rgba(212,150,12,0.36)' : '#1F2B16'}`,
      borderRadius: 12, cursor: 'pointer', textAlign: 'left', minWidth: 200, maxWidth: 240,
      display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <Avatar handle={thread.handle} size={26} accent={accent}/>
        <span style={{ font: '500 12.5px var(--font-mono)', color: '#F2EDE4',
                       overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {thread.handle}
        </span>
        <span style={{ flex: 1 }}/>
        {thread.unread > 0 && (
          <span style={{
            font: '500 10px var(--font-mono)', color: '#0B1306',
            background: '#D4960C', borderRadius: 999, padding: '1px 6px',
          }}>{thread.unread}</span>
        )}
        <span style={{ font: '400 10px var(--font-sans)', color: '#586552' }}>{thread.lastAge}</span>
      </div>
      <div style={{ font: '400 11.5px/1.4 var(--font-sans)', color: '#8A9678',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {thread.lastSenderIsThem ? '' : 'you: '}{thread.preview}
      </div>
    </button>
  );
}


// ──────────────────────────────────────────────────────────────
// D1 · Inline accordion.
// Tap a Folk row → it grows down inline to show DM preview + quick
// reply + the rest of the profile (mutual forests, stage). No modal.
// ──────────────────────────────────────────────────────────────
function FolkD1_Accordion() {
  const [open, setOpen] = React.useState('marina_k');
  return (
    <FolkLandingShell expandedHandle={open}>
      <div style={{ font: '500 10.5px var(--font-sans)', color: '#76AB78',
                    letterSpacing: '0.12em', textTransform: 'uppercase',
                    margin: '6px 4px 8px' }}>
        Friends · 3
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { handle: 'marina_k', stage: 'acquaintance', mutuals: 3, lastTouch: 'branched on your tree' },
          { handle: 'samh',     stage: 'friend',       mutuals: 7, lastTouch: 'planted in Philosophy' },
          { handle: 'leaf-902', stage: 'acquaintance', mutuals: 1, lastTouch: 'sent you a letter' },
        ].map(u => (
          <FolkAccordionRow key={u.handle} user={u}
            isOpen={open === u.handle}
            onToggle={() => setOpen(open === u.handle ? null : u.handle)}/>
        ))}
      </div>
    </FolkLandingShell>
  );
}


function FolkAccordionRow({ user, isOpen, onToggle }) {
  const thread = DM_THREADS[user.handle];
  const accent = user.stage === 'friend' ? '#5E8048'
              : user.stage === 'acquaintance' ? '#A8C5A0' : '#586552';
  return (
    <div style={{
      background: '#111D0A', border: `0.5px solid ${isOpen ? '#2D3A22' : '#1F2B16'}`,
      borderRadius: 12, overflow: 'hidden',
      transition: 'border-color 220ms var(--ease-organic)',
    }}>
      {/* Row */}
      <button onClick={onToggle} style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '11px 12px', background: 'transparent',
        border: 'none', cursor: 'pointer', width: '100%', textAlign: 'left',
      }}>
        <Avatar handle={user.handle} size={36} accent={accent} online={user.handle === 'samh'}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ font: '500 14px var(--font-mono)', color: '#F2EDE4' }}>{user.handle}</span>
            <StageBadge stage={user.stage}/>
            {thread && thread.unread > 0 && (
              <span style={{
                font: '500 10px var(--font-mono)', color: '#0B1306',
                background: '#D4960C', borderRadius: 999, padding: '1px 6px',
                animation: 'flBeadGrow 360ms var(--ease-organic) both',
              }}>{thread.unread}</span>
            )}
          </div>
          <div style={{ font: '400 11.5px var(--font-sans)', color: '#8A9678', marginTop: 2 }}>
            {user.mutuals} mutual forests · {user.lastTouch}
          </div>
        </div>
        <span style={{
          color: '#586552', transition: 'transform 220ms var(--ease-organic)',
          transform: isOpen ? 'rotate(90deg)' : 'rotate(0)',
        }}>
          <FLIcons.ChevronLeft size={16}/>
        </span>
      </button>

      {/* Expanded content */}
      {isOpen && (
        <div style={{ animation: 'flSlideDown 360ms var(--ease-organic) both' }}>
          {/* Letters preview */}
          {thread && (
            <div style={{
              margin: '0 12px 10px', padding: '12px 12px',
              background: '#0F1A09', border: '0.5px solid #1F2B16', borderRadius: 10,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <span style={{ font: '500 10px var(--font-sans)', color: '#F4DCA0',
                               letterSpacing: '0.14em', textTransform: 'uppercase' }}>
                  Letters · {thread.unread > 0 ? `${thread.unread} new` : 'quiet'}
                </span>
                <span style={{ flex: 1 }}/>
                <span style={{ font: '400 11px var(--font-sans)', color: '#586552' }}>open thread →</span>
              </div>
              <LeafStagger staggerMs={50}
                style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {thread.messages.slice(-2).map(m => (
                  <DmBubble key={m.id} m={m}/>
                ))}
              </LeafStagger>
              <div style={{
                marginTop: 10, height: 38, padding: '0 10px',
                background: '#0B1306', border: '0.5px solid #243319', borderRadius: 19,
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <span style={{ flex: 1, font: 'italic 400 13px var(--font-serif)', color: '#586552' }}>
                  Write back to {user.handle}…
                </span>
                <span style={{
                  width: 28, height: 28, borderRadius: '50%', background: '#1B3A1D',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#A8C5A0', border: '0.5px solid #2C5F2E',
                }}>
                  <FLIcons.ArrowUp size={14}/>
                </span>
              </div>
            </div>
          )}
          {/* Profile mini */}
          <div style={{
            display: 'flex', gap: 8, padding: '0 12px 12px', flexWrap: 'wrap',
          }}>
            <ProfileTile label="Mutual forests" value="3" sub="Philosophy + 2" accent="#5E8048"/>
            <ProfileTile label="Identity stage" value={user.stage} sub="propose closer →" accent="#A8C5A0"/>
            <ProfileTile label="Last branch" value="2h ago" sub="in BART Riders" accent="#D4960C"/>
          </div>
        </div>
      )}
    </div>
  );
}


function DmBubble({ m }) {
  const them = m.who === 'them';
  return (
    <div style={{
      display: 'flex', justifyContent: them ? 'flex-start' : 'flex-end',
    }}>
      <div style={{
        maxWidth: '78%',
        padding: '8px 11px', borderRadius: them ? '11px 11px 11px 4px' : '11px 11px 4px 11px',
        background: them ? '#111D0A' : '#1B3A1D',
        border: `0.5px solid ${them ? '#1F2B16' : '#2C5F2E'}`,
        font: '400 12.5px/1.5 var(--font-sans)', color: '#F2EDE4',
      }}>
        {m.body}
        <div style={{ font: '400 10px var(--font-sans)',
                      color: them ? '#586552' : '#A8C5A0',
                      marginTop: 4, textAlign: them ? 'left' : 'right' }}>{m.age}</div>
      </div>
    </div>
  );
}


function ProfileTile({ label, value, sub, accent }) {
  return (
    <div style={{
      flex: '1 1 100px', minWidth: 96,
      padding: 10, background: '#0F1A09',
      border: '0.5px solid #1F2B16', borderRadius: 10,
    }}>
      <div style={{ font: '500 10px var(--font-sans)', color: accent,
                    letterSpacing: '0.10em', textTransform: 'uppercase' }}>{label}</div>
      <div style={{ font: '500 14px var(--font-sans)', color: '#F2EDE4', marginTop: 2, textTransform: 'capitalize' }}>
        {value}
      </div>
      <div style={{ font: 'italic 400 11px var(--font-serif)', color: '#8A9678', marginTop: 2 }}>
        {sub}
      </div>
    </div>
  );
}


// ──────────────────────────────────────────────────────────────
// D2 · Stacked sheet.
// The existing ConnectSheet (bottom-sheet) gains a Letters section at
// the top that contains a full DM thread; profile remains below.
// ──────────────────────────────────────────────────────────────
function FolkD2_StackedSheet() {
  return (
    <div style={{ position: 'relative', height: '100%' }}>
      <FolkLandingShell>
        <div style={{ font: '500 10.5px var(--font-sans)', color: '#76AB78',
                      letterSpacing: '0.12em', textTransform: 'uppercase', margin: '6px 4px 8px' }}>
          Around now
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, opacity: 0.5 }}>
          <FlatFolkRow handle="marina_k" sub="branched on your tree" stage="acquaintance"/>
          <FlatFolkRow handle="samh" sub="planted in Philosophy" stage="friend"/>
          <FlatFolkRow handle="leaf-902" sub="sent you a letter" stage="acquaintance"/>
          <FlatFolkRow handle="oakling" sub="quiet · 2d" stage="acquaintance"/>
        </div>
      </FolkLandingShell>

      {/* The stacked sheet */}
      <StackedConnectSheet handle="marina_k"/>
    </div>
  );
}


function FlatFolkRow({ handle, sub, stage }) {
  const accent = stage === 'friend' ? '#5E8048' : stage === 'acquaintance' ? '#A8C5A0' : '#586552';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '11px 12px',
      background: '#111D0A', border: '0.5px solid #1F2B16', borderRadius: 12,
    }}>
      <Avatar handle={handle} size={32} accent={accent}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '500 13px var(--font-mono)', color: '#F2EDE4' }}>{handle}</div>
        <div style={{ font: '400 11.5px var(--font-sans)', color: '#8A9678' }}>{sub}</div>
      </div>
      <StageBadge stage={stage}/>
    </div>
  );
}


function StackedConnectSheet({ handle = 'marina_k' }) {
  const thread = DM_THREADS[handle];
  const [tab, setTab] = React.useState('letters');
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0, top: 90,
      background: '#0F1A09',
      borderRadius: '24px 24px 0 0',
      border: '0.5px solid #2D3A22', borderBottom: 'none',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
      boxShadow: '0 -20px 60px rgba(0,0,0,0.55)',
      animation: 'flSheetEnter 360ms var(--ease-organic) both',
      zIndex: 5,
    }}>
      <div style={{ flexShrink: 0, display: 'flex', justifyContent: 'center', padding: '10px 0 4px' }}>
        <span style={{ width: 36, height: 4, background: '#445239', borderRadius: 2 }}/>
      </div>

      {/* Header */}
      <div style={{ padding: '4px 18px 12px', display: 'flex', alignItems: 'center', gap: 12,
                    flexShrink: 0, borderBottom: '0.5px solid #1F2B16' }}>
        <Avatar handle={handle} size={44} accent="#A8C5A0"/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ font: '500 18px var(--font-mono)', color: '#F2EDE4', letterSpacing: '-0.01em' }}>
              {handle}
            </span>
            <StageBadge stage="acquaintance"/>
          </div>
          <div style={{ font: 'italic 400 12px var(--font-serif)', color: '#A8C5A0', marginTop: 2 }}>
            3 mutual forests · met in Philosophy
          </div>
        </div>
        <FLIcons.More size={18} color="#586552"/>
      </div>

      {/* Tab toggle */}
      <div style={{ padding: '12px 16px 8px', display: 'flex', gap: 4, flexShrink: 0 }}>
        <SheetTab id="letters" active={tab} onSelect={setTab} label="Letters" badge={thread.unread}/>
        <SheetTab id="profile" active={tab} onSelect={setTab} label="Profile"/>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }} className="phone-scroll">
        {tab === 'letters' && (
          <div style={{ padding: '8px 16px 14px',
                        animation: 'flSheetEnter 280ms var(--ease-organic) both' }}>
            <LeafStagger staggerMs={50}
              style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {thread.messages.map(m => <DmBubble key={m.id} m={m}/>)}
            </LeafStagger>
          </div>
        )}
        {tab === 'profile' && (
          <div style={{ padding: '8px 16px 14px',
                        animation: 'flSheetEnter 280ms var(--ease-organic) both' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <ProfileTile label="Stage" value="Acquaintance" sub="propose closer →" accent="#A8C5A0"/>
              <ProfileTile label="Recent" value="Branched on your tree" sub="14 minutes ago, Philosophy" accent="#D4960C"/>
              <ProfileTile label="Mutual forests" value="3" sub="Philosophy · BART · Slow Reading" accent="#5E8048"/>
              <ProfileTile label="Joined ForestLynk" value="11 months ago" sub="planted 42 roots" accent="#A8C5A0"/>
            </div>
          </div>
        )}
      </div>

      {/* Sticky composer at bottom for Letters tab */}
      {tab === 'letters' && (
        <div style={{ padding: '10px 14px 16px', flexShrink: 0,
                      borderTop: '0.5px solid #1F2B16', background: '#0F1A09' }}>
          <div style={{
            height: 40, padding: '0 12px',
            background: '#0B1306', border: '0.5px solid #243319', borderRadius: 20,
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <span style={{ flex: 1, font: 'italic 400 13px var(--font-serif)', color: '#586552' }}>
              Write a letter…
            </span>
            <span style={{
              width: 28, height: 28, borderRadius: '50%', background: '#2C5F2E',
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#F2EDE4',
            }}>
              <FLIcons.ArrowUp size={14} color="#F2EDE4"/>
            </span>
          </div>
        </div>
      )}
    </div>
  );
}


function SheetTab({ id, active, label, onSelect, badge = 0 }) {
  const isActive = active === id;
  return (
    <button onClick={() => onSelect(id)} style={{
      padding: '8px 14px', background: isActive ? '#1B3A1D' : 'transparent',
      border: 'none', color: isActive ? '#F2EDE4' : '#586552',
      borderRadius: 10, cursor: 'pointer',
      font: '500 12.5px var(--font-sans)',
      display: 'inline-flex', alignItems: 'center', gap: 6,
      transition: 'background 160ms var(--ease-organic), color 160ms var(--ease-organic)',
    }}>
      {label}
      {badge > 0 && (
        <span style={{
          font: '500 10px var(--font-mono)', color: '#0B1306',
          background: '#D4960C', borderRadius: 999, padding: '0 6px',
        }}>{badge}</span>
      )}
    </button>
  );
}


// ──────────────────────────────────────────────────────────────
// D3 · Swipe-peek.
// Folk rows live in the list as in v1; swiping a row leftward reveals
// the latest DM thread behind it (like Mail/iMessage). No screen
// transition. We render the row mid-swipe so the gesture is legible
// at design-canvas read-time.
// ──────────────────────────────────────────────────────────────
function FolkD3_SwipePeek() {
  return (
    <FolkLandingShell dmStripe={false}>
      <div style={{ font: '500 10.5px var(--font-sans)', color: '#76AB78',
                    letterSpacing: '0.12em', textTransform: 'uppercase', margin: '6px 4px 8px' }}>
        Friends
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <PeekRow handle="marina_k" stage="acquaintance" peeked={true}/>
        <PeekRow handle="samh" stage="friend" peeked={false}/>
        <PeekRow handle="leaf-902" stage="acquaintance" peeked={false}/>
      </div>
      <div style={{ marginTop: 18, padding: 12, background: 'transparent',
                    border: '0.5px dashed #2D3A22', borderRadius: 10,
                    font: 'italic 400 12px/1.55 var(--font-serif)', color: '#586552' }}>
        Tip · swipe a folk left to peek the last letter without leaving your list.
      </div>
    </FolkLandingShell>
  );
}


function PeekRow({ handle, stage, peeked }) {
  const thread = DM_THREADS[handle];
  const accent = stage === 'friend' ? '#5E8048'
              : stage === 'acquaintance' ? '#A8C5A0' : '#586552';
  const shift = peeked ? 200 : 0;
  return (
    <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 12 }}>
      {/* Letter background (revealed) */}
      <div style={{
        position: 'absolute', inset: 0, padding: '10px 14px',
        background: 'linear-gradient(90deg, #1B3A1D 0%, #1B3A1D 70%, transparent 100%)',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ font: '500 10px var(--font-sans)', color: '#F4DCA0',
                        letterSpacing: '0.14em', textTransform: 'uppercase' }}>
            Letter · {thread.lastAge}
          </div>
          <div style={{ font: 'italic 400 13px var(--font-serif)', color: '#F2EDE4',
                        marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap', maxWidth: '92%' }}>
            {thread.preview}
          </div>
        </div>
        <span style={{
          width: 36, height: 36, borderRadius: '50%', background: '#2C5F2E',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#F2EDE4', flexShrink: 0,
        }}>
          <FLIcons.ArrowUp size={16}/>
        </span>
      </div>
      {/* Foreground row (slides left when peeked) */}
      <div style={{
        position: 'relative', transform: `translateX(-${shift}px)`,
        transition: 'transform 320ms var(--ease-organic)',
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '11px 12px', background: '#111D0A',
        border: '0.5px solid #1F2B16',
      }}>
        <Avatar handle={handle} size={32} accent={accent}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ font: '500 13px var(--font-mono)', color: '#F2EDE4' }}>{handle}</div>
          <div style={{ font: '400 11.5px var(--font-sans)', color: '#8A9678' }}>
            {thread.unread ? `${thread.unread} new · ${thread.lastAge}` : `quiet · ${thread.lastAge}`}
          </div>
        </div>
        <StageBadge stage={stage}/>
      </div>
    </div>
  );
}


Object.assign(window, {
  FolkD1_Accordion, FolkD2_StackedSheet, FolkD3_SwipePeek,
});
