/* home-screens.jsx — Feed (For You/Stakeout/Wire/Kettle), Whispers list, Whisper thread.
   Exports to window. */

/* scrollable body that clears the bottom tab bar */
function FeedBody({ children, bodyRef }) {
  return (
    <div ref={bodyRef} className="scroll-area page-in" style={{ flex: '1 1 auto', minHeight: 0, padding: '8px 16px 110px' }}>
      {children}
    </div>
  );
}

/* ============================================================
   HOME (For You / Stakeout)
   ============================================================ */
function HomeFeed({ feed, onWhispers, onSearch, unread, onOpen, initialSub }) {
  const [sub, setSub] = React.useState(initialSub || 'foryou');
  const list = sub === 'foryou' ? feed : feed.filter((p) => p.following);
  return (
    <div className="pscreen" style={{ height: '100%' }}>
      <HomeHeader onWhispers={onWhispers} onSearch={onSearch} unread={unread} />
      <div style={{ flex: '0 0 auto', padding: '4px 16px 8px' }}>
        <SubTabs value={sub} onChange={setSub} options={[{ id: 'foryou', label: 'For You' }, { id: 'stakeout', label: 'Stakeout' }]} />
      </div>
      <FeedBody>
        {sub === 'stakeout' && list.length > 0 && (
          <div className="feednote postit" style={{ ...wobbly.md, ...tilt(-0.8) }}>
            <span style={{ fontSize: 20 }}>👀</span>
            <span className="font-body" style={{ fontSize: 15, color: 'var(--postit-ink)' }}>Only the {list.length} accounts in your <b>Stakeout</b> — people you follow.</span>
          </div>
        )}
        {list.length > 0
          ? list.map((p) => <FeedCard key={p.id} post={p} onOpen={() => onOpen(p)} />)
          : sub === 'stakeout'
            ? <EmptyState fill emoji="🫥" title="your Stakeout is quiet" body="You're not following anyone yet — or they haven't brewed. Search for people to add to your Stakeout." action="Find people" onAction={onSearch} />
            : <EmptyState fill emoji="🍵" title="all caught up" body="No Brews in your For You right now. Check back soon — the kettle never stays quiet for long." />}
      </FeedBody>
    </div>
  );
}

/* ============================================================
   THE WIRE (verified only)
   ============================================================ */
function WireFeed({ feed, onWhispers, onSearch, unread, onOpen }) {
  const list = feed.filter((p) => p.kind === 'wire');
  return (
    <div className="pscreen" style={{ height: '100%' }}>
      <HomeHeader title={null} onWhispers={onWhispers} onSearch={onSearch} unread={unread}
        left={<span className="font-head" style={{ fontWeight: 700, fontSize: 22, display: 'inline-flex', alignItems: 'center', gap: 7 }}><IconSparkle size={20} style={{ color: 'var(--secondary)' }} /> The Wire</span>} />
      <FeedBody>
        <div className="feednote" style={{ ...wobbly.md, ...tilt(-0.6), background: 'var(--surface)' }}>
          <span style={{ fontSize: 20 }}>✦</span>
          <span className="font-body" style={{ fontSize: 15, color: 'var(--ink)' }}>Real news, rewritten in your language. Every headline is <b>sourced &amp; verified</b> — tap to read the original.</span>
        </div>
        {list.map((p) => <FeedCard key={p.id} post={p} onOpen={() => onOpen(p)} />)}
      </FeedBody>
    </div>
  );
}

/* ============================================================
   THE KETTLE (unverified only)
   ============================================================ */
function KettleFeed({ feed, onWhispers, onSearch, unread, onOpen }) {
  const list = feed.filter((p) => p.kind === 'tea');
  return (
    <div className="pscreen" style={{ height: '100%' }}>
      <HomeHeader title={null} onWhispers={onWhispers} onSearch={onSearch} unread={unread}
        left={<span className="font-head" style={{ fontWeight: 700, fontSize: 22, display: 'inline-flex', alignItems: 'center', gap: 7 }}>🫖 The Kettle</span>} />
      <FeedBody>
        <div className="feednote postit" style={{ ...wobbly.md, ...tilt(0.6) }}>
          <span style={{ fontSize: 20 }}>🫖</span>
          <span className="font-body" style={{ fontSize: 15, color: 'var(--postit-ink)' }}>Hot takes &amp; gossip — <b>always unverified</b> &amp; pseudonymous. Read for fun, not facts.</span>
        </div>
        {list.map((p) => <FeedCard key={p.id} post={p} onOpen={() => onOpen(p)} />)}
      </FeedBody>
    </div>
  );
}

/* ============================================================
   WHISPERS list
   ============================================================ */
function WhispersList({ items, onBack, onOpen }) {
  return (
    <div className="pscreen" style={{ height: '100%' }}>
      <HomeHeader title="Whispers"
        left={<button onClick={onBack} aria-label="Back" className="font-body" style={{ width: 46, height: 46, ...wobbly.sm, ...tilt(-2), border: '2px dashed var(--ink-muted)', background: 'transparent', color: 'var(--ink)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IconBack size={22} /></button>} />
      <div className="scroll-area page-in" style={{ flex: '1 1 auto', minHeight: 0, padding: '6px 16px 110px' }}>
        {items.length > 0 ? (
          <React.Fragment>
            <div className="slist" style={{ padding: '0 14px' }}>
              {items.map((w) => <WhisperRow key={w.id} w={w} onOpen={() => onOpen(w)} />)}
            </div>
            <div className="font-body" style={{ textAlign: 'center', color: 'var(--ink-muted)', fontSize: 14, marginTop: 16 }}>
              🔒 Whispers are private &amp; pseudonymous
            </div>
          </React.Fragment>
        ) : (
          <EmptyState fill emoji="✉️" title="no whispers yet" body="When you slide into someone's DMs (or they slide into yours), your private chats live here. Pseudonymous, always." />
        )}
      </div>
    </div>
  );
}

/* ============================================================
   WHISPER thread
   ============================================================ */
function WhisperThread({ w, onBack }) {
  return (
    <div className="pscreen" style={{ height: '100%' }}>
      <HomeHeader title={null}
        left={
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <button onClick={onBack} aria-label="Back" className="font-body" style={{ width: 42, height: 42, ...wobbly.sm, ...tilt(-2), border: '2px dashed var(--ink-muted)', background: 'transparent', color: 'var(--ink)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}><IconBack size={20} /></button>
            <span className="wrow__av" style={{ width: 40, height: 40, ...tilt(-2) }}><img src={w.avatar} alt="" />{w.online && <span className="wrow__dot" style={{ width: 12, height: 12 }} />}</span>
            <span style={{ minWidth: 0 }}>
              <span className="font-head" style={{ fontWeight: 700, fontSize: 18, display: 'block', lineHeight: 1 }}>{w.name}</span>
              <span className="font-body" style={{ fontSize: 13, color: w.online ? 'var(--secondary)' : 'var(--ink-muted)' }}>{w.online ? 'online now' : 'last seen ' + w.time}</span>
            </span>
          </div>
        } />
      <div className="scroll-area page-in" style={{ flex: '1 1 auto', minHeight: 0, padding: '12px 16px 16px', display: 'flex', flexDirection: 'column' }}>
        <div className="font-body" style={{ textAlign: 'center', color: 'var(--ink-muted)', fontSize: 13, margin: '0 0 14px' }}>🔒 end-to-end · pseudonymous</div>
        {w.thread.map((m, i) => (
          <div key={i} className={`bubble ${m.from === 'me' ? 'bubble--me' : 'bubble--them'}`}>
            {m.text}
            <div className="bubble__t">{m.t}</div>
          </div>
        ))}
      </div>
      {/* composer */}
      <div style={{ flex: '0 0 auto', padding: '8px 16px 30px' }}>
        <div className="card" style={{ ...wobbly.pill, display: 'flex', alignItems: 'center', gap: 8, padding: '6px 6px 6px 16px', boxShadow: 'var(--sh-soft)' }}>
          <span className="font-body" style={{ flex: 1, color: 'var(--ink-muted)', fontSize: 17 }}>send a Whisper…</span>
          <button className="attach" aria-label="Add photo" style={{ width: 42, height: 42 }}><IconCamera size={20} /></button>
          <Button variant="accent" style={{ minHeight: 42, fontSize: 16, padding: '6px 16px' }}>Send</Button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { FeedBody, HomeFeed, WireFeed, KettleFeed, WhispersList, WhisperThread, FeedDetail });

/* ============================================================
   FEED DETAIL — full Brew opened from a feed card
   ============================================================ */
function FeedDetail({ post, onBack }) {
  const [sipped, setSipped] = React.useState(false);
  const [splashed, setSplashed] = React.useState(false);
  const isTea = post.kind === 'tea';
  const isClaw = post.kind === 'claw';
  const comments = commentsFor(post);
  const sips = post.sips + (sipped ? 1 : 0);
  const splash = post.splash + (splashed ? 1 : 0);

  const bannerBg = isTea ? 'var(--postit)' : 'var(--surface)';
  return (
    <div className="pscreen" style={{ height: '100%' }}>
      <HomeHeader title="Brew"
        left={<button onClick={onBack} aria-label="Back" className="font-body" style={{ width: 46, height: 46, ...wobbly.sm, ...tilt(-2), border: '2px dashed var(--ink-muted)', background: 'transparent', color: 'var(--ink)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IconBack size={22} /></button>} />
      <div className="scroll-area page-in" style={{ flex: '1 1 auto', minHeight: 0, padding: '6px 18px 16px' }}>
        {/* author */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div className="fcard__av" style={{ width: 50, height: 50, ...tilt(-3) }}><img src={post.author.avatar} alt="" /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="fcard__name" style={{ fontSize: 19 }}>{post.author.name}{post.kind === 'wire' && <IconSparkle size={15} style={{ color: 'var(--secondary)' }} />}</div>
            <div className="fcard__handle" style={{ fontSize: 15 }}>{post.author.handle} · {post.time}</div>
          </div>
          <KindBadge kind={post.kind} />
        </div>

        {/* banner */}
        <div className="postit" style={{ ...wobbly.sm, ...tilt(isTea ? 1 : -1), padding: '9px 13px', margin: '14px 0 0', display: 'flex', gap: 8, alignItems: 'center', background: bannerBg, border: '2px solid var(--ink)' }}>
          <span style={{ fontSize: 17 }}>{isTea ? '👀' : isClaw ? '🤖' : '🔗'}</span>
          <span className="font-body" style={{ fontSize: 15, color: isTea ? 'var(--postit-ink)' : 'var(--ink)' }}>
            {isTea ? 'From the Kettle — unverified. Read for fun, not facts.'
              : isClaw ? 'Posted by a disclosed Claw Bot (AI) — never posing as human.'
              : <>Verified on The Wire — sourced from <b>{post.source}</b>. Tap to read the original.</>}
          </span>
        </div>

        {/* body */}
        <p className="font-body" style={{ fontSize: 22, lineHeight: 1.42, margin: '16px 2px 0' }}>{post.body}</p>

        {/* image */}
        {post.image && (
          <div style={{ position: 'relative', margin: '22px 6px 2px', ...tilt(isTea ? -1 : 1) }}>
            <span style={{ position: 'absolute', top: -13, left: '50%', transform: 'translateX(-50%) rotate(-3deg)', zIndex: 3 }}>
              <Tape label={isTea ? '📷 photo' : '📰 from the article'} rotate={-3} />
            </span>
            <div className="pimg"><img src={post.image} alt="" />{!isTea && post.source && <div className="pimg__cap">🔗 {post.source}</div>}</div>
          </div>
        )}

        {/* reactions */}
        <div className="rbar" style={{ flexWrap: 'wrap', gap: 9, margin: '18px 0 2px' }}>
          <ReactionPill icon={<IconSip size={19} />} n={sips} on={sipped} onClick={() => setSipped((s) => !s)} />
          <ReactionPill icon={<IconSplash size={19} />} n={splash} on={splashed} onClick={() => setSplashed((s) => !s)} />
          <ReactionPill icon={<IconTake size={19} />} n={post.takes} />
          <ReactionPill icon={<IconWhisper size={19} />} n={post.whispers} />
        </div>

        <div style={{ margin: '20px 0 6px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="font-head" style={{ fontWeight: 700, fontSize: 20 }}>Takes</span>
          <span className="font-body" style={{ color: 'var(--ink-muted)', fontSize: 16 }}>{fmtN(post.takes)}</span>
          <span style={{ flex: 1 }}><WavyDivider /></span>
        </div>

        {comments.map((t, i) => (
          <div className="take" key={i}>
            <span className="take__av" style={tilt((i % 2 ? 1 : -1) * 2)}><img src={t.av} alt="" /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
                <span className="font-body" style={{ color: 'var(--secondary)', fontSize: 16 }}>{t.by}</span>
                <span className="font-body" style={{ color: 'var(--ink-muted)', fontSize: 14 }}>{t.t}</span>
              </div>
              <p className="font-body" style={{ fontSize: 17, lineHeight: 1.35, margin: '2px 0 6px' }}>{t.text}</p>
              {t.image && <div className="take__img" style={tilt(-1.2)}><img src={t.image} alt="" /></div>}
              <button className="font-body" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-muted)', fontSize: 15, padding: 0 }}>
                <IconSip size={15} /> {fmtN(t.sips)}
              </button>
            </div>
          </div>
        ))}
        <div style={{ height: 6 }} />
      </div>
      {/* reply composer */}
      <div style={{ flex: '0 0 auto', padding: '8px 16px 30px' }}>
        <TakeComposer me={typeof ME !== 'undefined' ? ME : { avatar: post.author.avatar }} />
      </div>
    </div>
  );
}
