// thread-view.jsx — Thread view with newest-first sort.
// Each reply is its own card with the parent attached below as a quoted card.
// Thread starter (oldest) sits at the bottom of the feed.

function ThreadView({ dark }) {
  const t = useTheme(dark);

  // Thread starter — original prediction post
  const starter = {
    id: 'p1', name: 'PapaSmurf', acc: '78%', when: '2h ago', badge: 'TOP 1%',
    prediction: { dir: 'Buy', tp: 268, conf: 9 },
    body: 'AWS revenue growth re-accelerating + ad business compounding. Q2 setup looks like a blowout vs sandbagged guidance. Holding through earnings, adding on any pullback under €220.',
    likes: 47, replies: 12, isStarter: true,
  };

  // Replies, newest first
  const replies = [
    {
      id: 'st', name: 'Stefan', acc: '52%', when: '2m', replyTo: 'PapaSmurf',
      body: 'You might be underweighting FX on AWS — but if the dollar keeps weakening, that\'s actually a tailwind for next quarter. Bullish in disguise?',
      likes: 0, isYou: true,
    },
    {
      id: 'in', name: 'Investorin_DE', acc: '49%', when: '8m', replyTo: 'PapaSmurf',
      body: 'Macht hier jemand covered calls vor den Earnings? IV ist gerade richtig hoch.',
      likes: 2,
    },
    {
      id: 'b', name: 'Bankster', acc: '64%', when: '24m', replyTo: 'fenjal',
      prediction: { dir: 'Sell', tp: 195, conf: 6 },
      body: 'Disagree on the margin story. Ad business is decelerating QoQ, multiple is still stretched vs historical average.',
      likes: 4,
    },
    {
      id: 'f', name: 'fenjal', acc: '71%', when: '34m', replyTo: 'PapaSmurf',
      prediction: { dir: 'Buy', tp: 255, conf: 7 },
      body: 'Adding my view: cost discipline + ad business is the real story here. Stop watching FTC, watch NA retail margins.',
      likes: 9,
    },
    {
      id: 'p2', name: 'PapaSmurf', acc: '78%', when: '40m', replyTo: 'Lisa_K', isOP: true,
      body: 'Fair question. My view: even if they lose, structural separation would take 5+ years to litigate. We hold through Q2 first, then re-assess.',
      likes: 12,
    },
    {
      id: 'm', name: 'Mike_T', acc: '61%', when: '52m', replyTo: 'Lisa_K',
      body: 'The ruling is more nuanced than headlines suggest. Even a worst-case outcome is fines + behavioral remedies, not a structural breakup.',
      likes: 3,
    },
    {
      id: 'l', name: 'Lisa_K', acc: '54%', when: '1h 12m', replyTo: 'PapaSmurf',
      body: 'How are you thinking about the FTC overhang? Feels like a real risk before the EOY ruling — could compress the multiple even if fundamentals deliver.',
      likes: 8,
    },
  ];

  // Lookup parent by name for the attached-quote rendering
  const allPosts = [starter, ...replies];
  const byName = {};
  allPosts.forEach(p => { if (!byName[p.name]) byName[p.name] = p; });

  return (
    <div style={{ background: t.bg, color: t.text, height: '100%', display: 'flex', flexDirection: 'column',
      fontFamily: SW_FONT, position: 'relative' }}>
      {/* Header */}
      <div style={{ padding: '54px 16px 6px', display: 'flex', alignItems: 'center', gap: 12 }}>
        {Icon.back(t.text, 22)}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
          <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em' }}>Thread</div>
          <div style={{ fontSize: 11, color: t.textDim, fontFamily: SW_MONO, letterSpacing: '0.01em' }}>
            12 replies · started by @PapaSmurf
          </div>
        </div>
        <div style={{ width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {ActIcon.more(t.text, 20)}
        </div>
      </div>

      {/* AMZN context strip */}
      <div style={{ margin: '6px 12px 10px', padding: '10px 12px', borderRadius: 12,
        background: t.surface, border: `0.5px solid ${t.border}`,
        display: 'flex', alignItems: 'center', gap: 10 }}>
        <Ticker symbol="AMZN" size={26} />
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: '-0.005em' }}>Amazon.com</span>
          <span style={{ fontFamily: SW_MONO, fontSize: 10.5, color: t.textDim }}>AMZN · NASDAQ</span>
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontFamily: SW_MONO, fontSize: 13, fontWeight: 600 }}>€227.35</span>
          <span style={{ fontFamily: SW_MONO, fontSize: 11.5, color: t.down, fontWeight: 600 }}>−1.50%</span>
        </div>
      </div>

      {/* Sort header */}
      <div style={{ padding: '4px 18px 10px', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 11, color: t.textDim, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>
          Activity
        </span>
        <span style={{ fontSize: 11.5, color: t.text, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
          Sort: Newest first
          <svg width="10" height="10" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="m3 4.5 3 3 3-3" />
          </svg>
        </span>
      </div>

      <div style={{ flex: 1, overflow: 'auto', paddingBottom: 100 }}>
        {/* Newest-first feed: replies, then thread starter at the bottom */}
        <div style={{ padding: '0 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {replies.map(r => (
            <ReplyCard key={r.id} t={t} reply={r} parent={byName[r.replyTo]} />
          ))}
          {/* Thread starter, anchored at the end (oldest) */}
          <ThreadStarterCard t={t} post={starter} />
        </div>
      </div>

      {/* Sticky composer at bottom */}
      <div style={{
        position: 'absolute', bottom: 80, left: 12, right: 12,
        padding: '10px 12px', borderRadius: 14, background: t.surface,
        border: `0.5px solid ${t.borderStrong}`,
        boxShadow: t.name === 'dark'
          ? '0 8px 24px rgba(0,0,0,0.4)' : '0 8px 24px rgba(0,0,0,0.08)',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <Avatar name="St" size={28} color={t.accent} />
        <div style={{ flex: 1, fontSize: 13, color: t.textDim, letterSpacing: '-0.005em' }}>
          Reply to the thread…
        </div>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          padding: '6px 10px', borderRadius: 999,
          background: t.text, color: t.bg,
          fontSize: 11, fontWeight: 700, letterSpacing: '0.02em',
        }}>{Icon.plus(t.bg, 11)}Predict</span>
      </div>

      <BottomTabs t={t} active="community" />
    </div>
  );
}

// ───────────────────────── Reply card with attached parent quote ─────────────────────────
function ReplyCard({ t, reply, parent }) {
  const r = reply;
  const hasPred = !!r.prediction;
  const up = hasPred && r.prediction.dir === 'Buy';
  const dn = hasPred && r.prediction.dir === 'Sell';
  const predColor = up ? t.up : dn ? t.down : t.text;
  const delta = hasPred ? ((r.prediction.tp - 227.35) / 227.35 * 100).toFixed(1) : null;

  return (
    <div style={{
      padding: 14, borderRadius: 16, background: t.surface,
      border: `0.5px solid ${t.border}`,
      // Subtle highlight if "you" wrote it
      boxShadow: r.isYou ? `inset 0 0 0 1px ${t.accent}33` : 'none',
    }}>
      {/* Author row */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <Avatar name={r.name} size={32} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 13.5, fontWeight: 600, letterSpacing: '-0.005em' }}>
              {r.isYou ? 'You' : r.name}
            </span>
            {r.isOP && (
              <span style={{ padding: '1px 6px', borderRadius: 4, background: t.accentSoft, color: t.accent,
                fontSize: 9.5, fontWeight: 700, letterSpacing: '0.05em' }}>OP</span>
            )}
            <span style={{ fontFamily: SW_MONO, fontSize: 10.5, color: t.textDim, marginLeft: 'auto' }}>{r.when}</span>
          </div>
          <div style={{ fontSize: 11, color: t.textDim, fontFamily: SW_MONO, marginTop: 1 }}>
            {r.acc} accuracy
          </div>
        </div>
      </div>

      {/* "Replying to @X" indicator */}
      {r.replyTo && (
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 5,
          fontSize: 11, color: t.textMuted, marginBottom: 8, marginLeft: 2,
        }}>
          {ActIcon.reply(t.textDim, 11)}
          <span>Replying to <span style={{ color: t.accent, fontWeight: 700 }}>@{r.replyTo}</span></span>
        </div>
      )}

      {/* Optional prediction pill */}
      {hasPred && (
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 8,
          padding: '4px 10px 4px 7px', borderRadius: 999,
          background: up ? t.upSoft : t.downSoft,
        }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 2,
            fontFamily: SW_FONT, fontWeight: 700, fontSize: 11, color: predColor, letterSpacing: '0.02em' }}>
            {up ? Icon.arrowUp(predColor, 10) : Icon.arrowDown(predColor, 10)}
            {r.prediction.dir.toUpperCase()}
          </span>
          <span style={{ fontFamily: SW_MONO, fontSize: 11.5, color: t.text, fontWeight: 700 }}>€{r.prediction.tp}</span>
          <span style={{ fontFamily: SW_MONO, fontSize: 11, color: predColor, fontWeight: 700 }}>
            {delta > 0 ? '+' : ''}{delta}%
          </span>
        </div>
      )}

      {/* Reply body */}
      <div style={{ fontSize: 13.5, color: t.text, lineHeight: 1.55, letterSpacing: '-0.005em', textWrap: 'pretty' }}>
        {r.body}
      </div>

      {/* Attached parent quote */}
      {parent && <QuotedParent t={t} parent={parent} />}

      {/* Actions */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginTop: 12,
        color: t.textDim, fontSize: 12, fontWeight: 500 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          {Icon.heart(t.textDim, 14)}
          <span style={{ fontFamily: SW_MONO }}>{r.likes}</span>
        </span>
        <span style={{ color: t.accent, fontWeight: 600 }}>Reply</span>
        <span style={{ marginLeft: 'auto', color: t.textDim }}>{ActIcon.share2(t.textDim, 13)}</span>
      </div>
    </div>
  );
}

// ───────────────────────── Attached parent quote — compact ─────────────────────────
function QuotedParent({ t, parent }) {
  const p = parent;
  const hasPred = !!p.prediction;
  const up = hasPred && p.prediction.dir === 'Buy';
  const predColor = up ? t.up : t.down;
  const delta = hasPred ? ((p.prediction.tp - 227.35) / 227.35 * 100).toFixed(1) : null;

  return (
    <div style={{
      marginTop: 12,
      padding: 12, borderRadius: 12,
      background: t.bgSubtle,
      border: `0.5px solid ${t.border}`,
      borderLeft: hasPred ? `2px solid ${predColor}` : `0.5px solid ${t.border}`,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
        <Avatar name={p.name} size={20} />
        <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '-0.005em' }}>{p.name}</span>
        {p.badge && (
          <span style={{
            padding: '1px 5px', borderRadius: 4, background: t.accentSoft, color: t.accent,
            fontSize: 9, fontWeight: 700, letterSpacing: '0.05em',
          }}>{p.badge}</span>
        )}
        <span style={{ fontFamily: SW_MONO, fontSize: 10, color: t.textDim, marginLeft: 'auto' }}>{p.when}</span>
      </div>

      {hasPred && (
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 5, marginBottom: 5,
          fontFamily: SW_FONT,
        }}>
          <span style={{ fontWeight: 700, fontSize: 10.5, color: predColor, letterSpacing: '0.02em' }}>
            {p.prediction.dir.toUpperCase()}
          </span>
          <span style={{ fontFamily: SW_MONO, fontSize: 11, color: t.text, fontWeight: 700 }}>€{p.prediction.tp}</span>
          <span style={{ fontFamily: SW_MONO, fontSize: 10.5, color: predColor, fontWeight: 700 }}>
            {delta > 0 ? '+' : ''}{delta}%
          </span>
        </div>
      )}

      {/* Truncated body */}
      <div style={{
        fontSize: 12, color: t.textMuted, lineHeight: 1.45, letterSpacing: '-0.005em',
        display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
      }}>
        {p.body}
      </div>
    </div>
  );
}

// ───────────────────────── Thread starter card (oldest, at the bottom) ─────────────────────────
function ThreadStarterCard({ t, post: p }) {
  const hasPred = !!p.prediction;
  const up = hasPred && p.prediction.dir === 'Buy';
  const predColor = up ? t.up : t.down;
  const delta = hasPred ? ((p.prediction.tp - 227.35) / 227.35 * 100).toFixed(1) : null;
  return (
    <div style={{
      padding: 16, borderRadius: 16, background: t.surface,
      border: `0.5px solid ${t.border}`,
      borderLeft: hasPred ? `3px solid ${predColor}` : `0.5px solid ${t.border}`,
    }}>
      {/* "Thread starter" badge at top */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 12 }}>
        <span style={{
          padding: '3px 8px', borderRadius: 6,
          background: t.chip, color: t.textMuted,
          fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
        }}>Thread starter</span>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        <Avatar name={p.name} size={36} />
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.005em' }}>{p.name}</span>
            {p.badge && (
              <Chip t={t} size="xs" color={t.accent} bg={t.accentSoft}>{p.badge}</Chip>
            )}
          </div>
          <div style={{ fontSize: 11, color: t.textDim, fontFamily: SW_MONO, marginTop: 2, display: 'flex', gap: 6 }}>
            <span>{p.acc} accuracy</span>
            <span>·</span>
            <span>{p.when}</span>
          </div>
        </div>
        <div style={{ padding: '5px 10px', borderRadius: 999,
          border: `0.5px solid ${t.borderStrong}`,
          fontSize: 11, fontWeight: 600, color: t.text }}>＋ Follow</div>
      </div>

      {hasPred && (
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 12,
          padding: '7px 12px 7px 10px', borderRadius: 999,
          background: up ? t.upSoft : t.downSoft,
        }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3,
            fontFamily: SW_FONT, fontWeight: 700, fontSize: 11.5, color: predColor, letterSpacing: '0.02em' }}>
            {up ? Icon.arrowUp(predColor, 11) : Icon.arrowDown(predColor, 11)}
            {p.prediction.dir.toUpperCase()}
          </span>
          <span style={{ fontFamily: SW_MONO, fontSize: 12.5, color: t.text, fontWeight: 700 }}>€{p.prediction.tp}</span>
          <span style={{ fontFamily: SW_MONO, fontSize: 11.5, color: predColor, fontWeight: 700 }}>
            {delta > 0 ? '+' : ''}{delta}%
          </span>
          <span style={{ fontFamily: SW_MONO, fontSize: 11, color: t.textDim }}>· conf {p.prediction.conf}/10</span>
        </div>
      )}

      <div style={{ fontSize: 14, lineHeight: 1.55, color: t.text, marginBottom: 14, textWrap: 'pretty', letterSpacing: '-0.005em' }}>
        {p.body}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 18, color: t.textDim, fontSize: 12.5 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontWeight: 600 }}>
          {Icon.heart(t.textDim, 14)}
          <span style={{ fontFamily: SW_MONO }}>{p.likes}</span>
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontWeight: 600, color: t.text }}>
          {ActIcon.reply(t.text, 14)}
          <span style={{ fontFamily: SW_MONO }}>{p.replies}</span>
        </span>
        <span style={{ marginLeft: 'auto' }}>{ActIcon.share2(t.textDim, 14)}</span>
      </div>
    </div>
  );
}

Object.assign(window, { ThreadView });
