/* Club FRESH — Club (the conversation space) */
function CFClub({ go, avatar }) {
  const { CF_Icon: Icon } = window;
  const [room, setRoom] = React.useState('thread');
  const rooms = [
    { key:'thread', label:"Today's thread" },
    { key:'wins',   label:'Wins' },
    { key:'friday', label:'Freedom Friday' },
  ];
  return (
    <div className="cf-fade-in" style={{ minHeight: '100%' }}>
      {/* header */}
      <div className="cf-pad" style={{ paddingTop: 8, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <p className="cf-eyebrow" style={{ marginBottom: 8 }}>The club is awake</p>
          <h1 className="cf-display" style={{ fontSize: 42 }}>Club</h1>
        </div>
        <window.CFFreshMark size={26} />
      </div>

      {/* room switcher */}
      <div className="cf-pad" style={{ marginTop: 16 }}>
        <div style={{ display: 'flex', gap: 6, background: 'rgba(20,16,12,0.05)', borderRadius: 999, padding: 4 }}>
          {rooms.map(r => (
            <button key={r.key} className="cf-reset" onClick={() => setRoom(r.key)} style={{
              flex: 1, height: 38, borderRadius: 999, fontSize: 12.5, fontWeight: 600,
              color: room === r.key ? 'var(--ink-h)' : 'var(--ink-m)',
              background: room === r.key ? '#fff' : 'transparent',
              boxShadow: room === r.key ? '0 2px 8px rgba(20,16,12,0.1)' : 'none',
            }}>{r.label}</button>
          ))}
        </div>
      </div>

      {room === 'thread' && <ThreadRoom />}
      {room === 'wins' && <WinsRoom avatar={avatar} />}
      {room === 'friday' && <FridayRoom />}
    </div>
  );
}

/* ---------- Today's thread (live: real messages via the club backend) ---------- */
const LIVE_ANCHORS = ['fitness', 'relationships', 'environment', 'self', 'hustle'];
const liveAnchorFor = (who) => LIVE_ANCHORS[[...who].reduce((a, c) => a + c.charCodeAt(0), 0) % LIVE_ANCHORS.length];

function ThreadRoom() {
  const { CF_Icon: Icon, CF_Monogram: Mono, CF_THREAD: T } = window;
  const [live, setLive] = React.useState([]);
  const [newPill, setNewPill] = React.useState(false);
  const lastId = React.useRef(0);
  const boxRef = React.useRef(null);

  const scroller = () => boxRef.current && boxRef.current.closest('.cf-scroll');
  const nearBottom = () => {
    const el = scroller();
    return !el || el.scrollHeight - el.scrollTop - el.clientHeight < 160;
  };
  const toBottom = () => {
    const el = scroller();
    if (el) el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });
    setNewPill(false);
  };

  React.useEffect(() => {
    let on = true;
    const poll = async () => {
      try {
        const msgs = await window.CFLive.fetchMessages(lastId.current);
        if (!on || !msgs.length) return;
        const wasNear = nearBottom();
        lastId.current = msgs[msgs.length - 1].id;
        setLive(prev => [...prev, ...msgs.map(m => ({
          who: m.who, me: m.who === 'You',
          anchor: liveAnchorFor(m.who),
          group: [m.text],
          time: new Date(m.ts).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }),
        }))]);
        if (wasNear) setTimeout(toBottom, 80);
        else setNewPill(true);
      } catch { /* offline: thread stays as-is */ }
    };
    poll();
    const iv = setInterval(poll, 1500);
    return () => { on = false; clearInterval(iv); };
  }, []);

  const send = async (text) => {
    setLive(prev => [...prev, { who: 'You', me: true, anchor: 'self', group: [text], time: new Date().toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) }]);
    setTimeout(toBottom, 60);
    try { await window.CFLive.post('You', text); } catch { /* optimistic only */ }
  };

  return (
    <div ref={boxRef}>
      {/* pinned prompt */}
      <div className="cf-pad" style={{ marginTop: 14 }}>
        <div style={{ display: 'flex', gap: 11, alignItems: 'flex-start', background: 'color-mix(in srgb, var(--gold) 12%, #fff)', border: '1px solid color-mix(in srgb, var(--gold) 30%, transparent)', borderRadius: 16, padding: '13px 15px' }}>
          <Icon name="pin" size={16} style={{ color: 'var(--gold)', marginTop: 2, flexShrink: 0 }} />
          <div>
            <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', color: 'var(--gold)' }}>PINNED · Tracy</span>
            <p style={{ margin: '4px 0 0', fontSize: 13.5, color: 'var(--ink-b)', lineHeight: 1.45 }}>{T.pinned.text}</p>
          </div>
        </div>
      </div>

      {/* messages: the seeded room, then everything live from the backend */}
      <div className="cf-pad" style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
        {T.messages.map((m, i) => <Message key={'s' + i} m={m} />)}
        {live.map((m, i) => <Message key={'l' + i} m={m} />)}
        {/* typing */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, color: 'var(--ink-m)', fontSize: 12.5, marginTop: -4 }}>
          <Mono name={T.typing} pillar="environment" size={24} />
          <span style={{ display: 'inline-flex', gap: 3, alignItems: 'center' }}>
            <Dot /><Dot d={0.16} /><Dot d={0.32} />
          </span>
          {T.typing} is typing
        </div>
      </div>

      {/* floating new pill: appears when live messages land while scrolled up */}
      {newPill && (
        <div className="cf-pad" style={{ position: 'sticky', bottom: 96, display: 'flex', justifyContent: 'center', pointerEvents: 'none', marginTop: 10 }}>
          <button className="cf-reset" onClick={toBottom} style={{ pointerEvents: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6, height: 34, paddingInline: 14, borderRadius: 999, background: 'var(--cf-dark)', color: '#fff', fontSize: 12.5, fontWeight: 600, boxShadow: '0 8px 22px rgba(20,16,12,0.25)' }}>
            New messages <Icon name="chevD" size={14} />
          </button>
        </div>
      )}

      <Composer onSend={send} />
    </div>
  );
}

function Message({ m }) {
  const { CF_Icon: Icon, CF_Monogram: Mono } = window;
  const me = m.me;
  const accentName = m.lead || m.tracy;
  return (
    <div style={{ display: 'flex', flexDirection: me ? 'row-reverse' : 'row', gap: 9, alignItems: 'flex-end' }}>
      {!me && (
        <span style={{ borderRadius: '50%', boxShadow: accentName ? '0 0 0 2px var(--gold)' : 'none', flexShrink: 0 }}>
          <Mono name={m.who} pillar={m.anchor} size={32} />
        </span>
      )}
      <div style={{ maxWidth: '80%', display: 'flex', flexDirection: 'column', alignItems: me ? 'flex-end' : 'flex-start', gap: 4 }}>
        {!me && (
          <span style={{ fontSize: 11.5, fontWeight: 600, color: accentName ? 'var(--gold)' : 'var(--ink-m)', marginLeft: 4 }}>
            {m.who}{m.lead ? ' · Lead' : ''}
          </span>
        )}
        {/* quote reply */}
        {m.reply && (
          <div className={'cf-bubble' + (me ? ' cf-bubble--me' : '')} style={{ padding: 0, overflow: 'hidden', maxWidth: '100%' }}>
            <div style={{ borderLeft: '3px solid var(--cf-accent)', padding: '7px 11px', background: me ? 'rgba(255,255,255,0.1)' : 'rgba(20,16,12,0.03)', margin: 8, borderRadius: 8 }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: me ? 'rgba(255,255,255,0.8)' : 'var(--ink-h)' }}>{m.reply.who.split(' ')[0]}</div>
              <div style={{ fontSize: 12, color: me ? 'rgba(255,255,255,0.65)' : 'var(--ink-m)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 180 }}>{m.reply.text}</div>
            </div>
          </div>
        )}
        {m.group.map((g, i) => (
          <div key={i} className={'cf-bubble' + (me ? ' cf-bubble--me' : (i === 0 ? ' cf-bubble--first' : ''))}>{g}</div>
        ))}
        {/* reactions */}
        {m.react && (
          <div style={{ display: 'flex', gap: 5, marginTop: 1 }}>
            {m.react.map((r, i) => (
              <span key={i} className="cf-react">{r.e} {r.n}</span>
            ))}
          </div>
        )}
        <span style={{ fontSize: 10.5, color: 'var(--ink-m)', marginInline: 4 }}>{m.time}</span>
      </div>
    </div>
  );
}

function Dot({ d = 0 }) {
  return <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--ink-m)', display: 'inline-block', animation: `cfBlink 1.2s ${d}s infinite ease-in-out` }} />;
}

function Composer({ onSend }) {
  const { CF_Icon: Icon } = window;
  const [text, setText] = React.useState('');
  const fire = () => {
    const t = text.trim();
    if (!t) return;
    setText('');
    onSend && onSend(t);
  };
  return (
    <div className="cf-pad" style={{ position: 'sticky', bottom: 22, marginTop: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(14px)', borderRadius: 999, padding: '7px 8px 7px 16px', boxShadow: '0 8px 26px rgba(20,16,12,0.14)', border: '0.5px solid rgba(20,16,12,0.06)' }}>
        <button className="cf-reset" style={{ color: 'var(--ink-m)' }}><Icon name="leaf" size={20} /></button>
        <input value={text} onChange={e => setText(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') fire(); }}
          placeholder="Say something kind…"
          style={{ flex: 1, fontSize: 14, color: 'var(--ink-h)', background: 'transparent', border: 0, outline: 'none', fontFamily: 'inherit', minWidth: 0 }} />
        <button className="cf-reset" onClick={fire} style={{ width: 38, height: 38, borderRadius: '50%', background: 'var(--cf-dark)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="arrowUR" size={18} /></button>
      </div>
    </div>
  );
}

/* ---------- Wins wall ---------- */
function WinsRoom({ avatar }) {
  const { CF_Icon: Icon, CF_Monogram: Mono, CF_WINS } = window;
  const [mine, setMine] = React.useState(() => window.CFLive.loadWins());
  const WINS = [...mine, ...CF_WINS];
  const share = () => window.cfModal.open(close => <WinSheet avatar={avatar} onClose={(text) => {
    if (text) setMine(window.CFLive.addWin(text));
    close();
  }} />);
  return (
    <div className="cf-pad" style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <button className="cf-reset cf-tap" style={{ width: '100%' }} onClick={share}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, background: '#fff', borderRadius: 16, padding: '13px 15px', boxShadow: '0 2px 12px rgba(20,16,12,0.05)' }}>
          <Mono name={avatar.name} pillar={avatar.anchor} size={34} />
          <span style={{ flex: 1, textAlign: 'left', fontSize: 14, color: 'var(--ink-m)' }}>Share a win. Any size.</span>
          <Icon name="plus" size={18} style={{ color: 'var(--ink-h)' }} />
        </div>
      </button>
      {WINS.map((w, i) => (
        <div key={i} className="cf-card" style={{ padding: '16px 17px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
            <Mono name={w.who} pillar={w.anchor} size={36} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink-h)' }}>{w.who}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-m)' }}>{w.time}</div>
            </div>
          </div>
          <p style={{ margin: '13px 0 0', fontSize: 14.5, lineHeight: 1.5, color: 'var(--ink-b)', fontFamily: 'var(--cf-head)' }}>{w.text}</p>
          <div style={{ display: 'flex', gap: 6, marginTop: 14 }}>
            {w.react.map((r, j) => <span key={j} className="cf-react" style={{ fontSize: 12.5, padding: '4px 10px' }}>{r.e} {r.n}</span>)}
          </div>
        </div>
      ))}
    </div>
  );
}

/* share-a-win sheet */
function WinSheet({ avatar, onClose }) {
  const { CF_Monogram: Mono } = window;
  const [text, setText] = React.useState('');
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'rgba(20,16,12,0.35)', display: 'flex', alignItems: 'flex-end', zIndex: 90 }}
      onClick={() => onClose(null)}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', background: '#fff', borderRadius: '22px 22px 0 0', padding: '20px 20px 28px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 14 }}>
          <Mono name={avatar.name} pillar={avatar.anchor} size={34} />
          <div style={{ fontFamily: 'var(--cf-head)', fontSize: 19, color: 'var(--ink-h)' }}>Share a win. Any size.</div>
        </div>
        <textarea autoFocus value={text} onChange={e => setText(e.target.value)} rows={3}
          placeholder="Tiny counts. Brave counts double."
          style={{ width: '100%', boxSizing: 'border-box', border: '1px solid rgba(20,16,12,0.12)', borderRadius: 14, padding: '12px 14px', fontFamily: 'inherit', fontSize: 14.5, resize: 'none', outline: 'none', background: 'rgba(20,16,12,0.02)' }} />
        <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
          <button className="cf-reset" onClick={() => onClose(null)} style={{ flex: 1, height: 46, borderRadius: 999, border: '1px solid rgba(20,16,12,0.14)', fontSize: 14, fontWeight: 600, color: 'var(--ink-m)' }}>Not today</button>
          <button className="cf-reset" onClick={() => onClose(text.trim() || null)} style={{ flex: 2, height: 46, borderRadius: 999, background: 'var(--cf-dark)', color: '#fff', fontSize: 14, fontWeight: 600 }}>Post it</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Freedom Friday wall ---------- */
function FridayRoom() {
  const { CF_Icon: Icon, CF_Monogram: Mono, CF_FREEDOM: F, CF_RHYTHM: R } = window;
  return (
    <div className="cf-pad" style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div className="cf-card-dark" style={{ padding: '18px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <p style={{ margin: 0, fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.45)' }}>Your lifetime tally</p>
          <p style={{ margin: '7px 0 0', fontFamily: 'var(--cf-head)', fontStyle: 'italic', fontSize: 21, color: '#fff' }}>Freedom Fridays kept</p>
        </div>
        <span className="cf-num" style={{ fontSize: 46, color: '#fff' }}>{R.freedomFridays}</span>
      </div>
      {F.map((p, i) => (
        <div key={i} className="cf-card" style={{ overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '13px 15px' }}>
            <Mono name={p.who} pillar={p.anchor} size={34} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink-h)' }}>{p.who}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-m)' }}>Freedom Friday</div>
            </div>
            <Icon name="more" size={18} style={{ color: 'var(--ink-m)' }} />
          </div>
          <div style={{ height: 230, backgroundImage: `url(${p.img})`, backgroundSize: 'cover', backgroundPosition: 'center' }} />
          <div style={{ padding: '13px 15px 15px' }}>
            <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
              {p.react.map((r, j) => <span key={j} className="cf-react" style={{ fontSize: 12.5, padding: '4px 10px' }}>{r.e} {r.n}</span>)}
            </div>
            <p style={{ margin: 0, fontSize: 14, color: 'var(--ink-b)', lineHeight: 1.45 }}><span style={{ fontWeight: 600, color: 'var(--ink-h)' }}>{p.who.split(' ')[0]}</span> {p.cap}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { CFClub });
