/* global React, CRYPTOLIVE_DATA, Coin, Icon, fmtPrice, fmtPct, useT */

function ChatMessage({ msg }) {
  const u = msg.u || '';
  const hash = (u.charCodeAt(0) || 65) * 7 % 360;
  return (
    <div style={{ padding: '12px 0', borderBottom: '1px solid var(--line-soft)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
        <div className="coin coin--sm" style={{ background: `linear-gradient(135deg, hsl(${hash}, 60%, 65%), hsl(${(hash + 40) % 360}, 60%, 50%))` }}>
          {u.charAt(0)}
        </div>
        <span style={{ fontWeight: 700, fontSize: 14 }}>{u}</span>
        <span className="t-meta">{msg.t}</span>
      </div>
      <div className="t-body" style={{ paddingLeft: 40 }}>{msg.m}</div>
    </div>
  );
}

function SystemEvent({ event }) {
  const t = useT();
  const sevPill = event.sev === 'danger' ? 'pill--danger' : event.sev === 'warn' ? 'pill--warn' : 'pill--blue';
  return (
    <div style={{ padding: '12px 14px', margin: '10px 0', borderRadius: 12, background: 'var(--bg-muted)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
        <span className={`pill ${sevPill}`}>{t('system')}</span>
        <span className="t-meta">{typeof event.t === 'number' ? t('minsAgo', event.t.toFixed(0)) : t('justNow')}</span>
      </div>
      <div style={{ fontWeight: 700, fontSize: 15 }}>{event.title}</div>
      <div className="t-body-sm" style={{ marginTop: 2 }}>{event.msg}</div>
    </div>
  );
}

// Synthesize plausible chat for each asset room
function chatsForAsset(asset) {
  const up = asset.change24h >= 0;
  return [
    { u: '온체인러버', t: '2분 전', m: `${asset.symbol} 프리미엄 ${fmtPct(asset.premium)} 정도면 진입해도 괜찮을까요?` },
    { u: 'Hodler.eth', t: '4분 전', m: up ? `방금 거래량 늘면서 ${fmtPct(asset.change24h)} 갔네요. 추세 이어갈지 관전 중` : `${fmtPct(asset.change24h)} 조정 중인데 매수 타이밍 보고 있어요` },
    { u: 'RWA_Trader', t: '7분 전', m: `${asset.name} 펀더멘털 보면 ${asset.shortDesc}. 장기로는 포지티브 봅니다.` },
    { u: 'YieldHunter', t: '11분 전', m: asset.yield ? `연 ${asset.yield.toFixed(2)}% 분배라 베이스 포지션으로 가져가는 중` : '환매 조건 다시 확인해보세요' },
  ];
}

const GENERAL_CHATS = [
  { u: '시장관찰자', t: '1분 전', m: '오늘 미국장 프리마켓부터 RWA 섹터 강한 흐름이네요' },
  { u: 'kimchi_dev', t: '3분 전', m: 'sDAI랑 OUSG 같은 채권형 자산이 안정적으로 잘 가는 듯' },
  { u: 'BlockchainBae', t: '6분 전', m: '토큰화 주식 거래대금이 한 달 새 3배 가까이 늘었어요' },
  { u: 'OnchainOps', t: '9분 전', m: '연준 발언 이후 변동성 커진 종목 모니터링 중 — 알림 켜두세요' },
  { u: 'DeFiDad', t: '13분 전', m: '주말에도 24/7 거래 가능한 게 RWA 토큰화 최대 장점인 듯' },
];

function RoomHeaderCard({ asset }) {
  const t = useT();
  const up = asset.change24h >= 0;
  const premUp = asset.premium >= 0;
  const events = CRYPTOLIVE_DATA.liveEvents().filter(e =>
    (e.title && e.title.toLowerCase().includes(asset.symbol.toLowerCase())) ||
    (e.msg && e.msg.toLowerCase().includes(asset.symbol.toLowerCase()))
  ).slice(0, 2);
  const fallbackEvents = events.length === 0 ? [
    { sev: premUp ? 'info' : 'warn', t: 4, title: `${asset.symbol} ${premUp ? '프리미엄' : '디스카운트'} ${fmtPct(asset.premium)}`, msg: `기초자산 ${asset.name} 대비 ${premUp ? '+' : ''}${fmtPct(asset.premium)} 차이. ${Math.abs(asset.premium) > 1 ? '평소보다 가격차가 크게 벌어진 상태입니다.' : '근접한 가격대에서 거래되는 중입니다.'}` },
    { sev: up ? 'info' : 'warn', t: 11, title: `24시간 거래대금 ${fmtUSDshort(asset.vol24h)}`, msg: `최근 24시간 동안 ${asset.symbol} ${up ? '매수' : '매도'}세가 우위입니다.` },
  ] : events;

  return (
    <div className="card card-pad-lg" style={{ marginBottom: 16, background: 'var(--hero-grad)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
        <Coin id={asset.id} symbol={asset.symbol} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 18, letterSpacing: '-0.01em' }}>{t('roomHeader', asset.symbol)}</div>
          <div className="t-meta">{asset.name} · {t('roomHeaderSub')}</div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: 12, marginBottom: 12 }}>
        <div>
          <div className="t-meta">{t('roomPriceLabel')}</div>
          <div className="t-h3 t-num">${fmtPrice(asset.tokenPrice)}</div>
        </div>
        <div>
          <div className="t-meta">{t('roomChangeLabel')}</div>
          <div className={`t-h3 t-num ${up ? 'c-up' : 'c-down'}`}>{fmtPct(asset.change24h)}</div>
        </div>
        <div>
          <div className="t-meta">{t('roomPremiumLabel')}</div>
          <div className={`t-h3 t-num ${premUp ? 'c-up' : 'c-down'}`}>{fmtPct(asset.premium)}</div>
        </div>
      </div>
      <div>
        {fallbackEvents.map((e, i) => <SystemEvent key={i} event={e} />)}
      </div>
    </div>
  );
}

function fmtUSDshort(n) {
  if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
  if (n >= 1e6) return `$${(n / 1e6).toFixed(1)}M`;
  if (n >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;
  return `$${n.toFixed(0)}`;
}

function LiveScreen({ goto, initialRoom }) {
  const t = useT();
  const [room, setRoom] = React.useState(initialRoom || 'all');
  const [input, setInput] = React.useState('');
  const [byRoom, setByRoom] = React.useState(() => {
    const map = { all: [...CRYPTOLIVE_DATA.chats()], general: [...GENERAL_CHATS] };
    CRYPTOLIVE_DATA.assets().forEach(a => { map[a.id] = chatsForAsset(a); });
    return map;
  });

  React.useEffect(() => {
    if (initialRoom && initialRoom !== room) setRoom(initialRoom);
  }, [initialRoom]);

  const rooms = [
    { id: 'all', label: t('allFeed') },
    { id: 'system', label: t('systemFeed') },
    { id: 'general', label: t('generalRoom') },
    ...CRYPTOLIVE_DATA.assets().slice(0, 6).map(a => ({ id: a.id, label: a.symbol })),
  ];

  const currentAsset = CRYPTOLIVE_DATA.assets().find(a => a.id === room);
  const canChat = room !== 'system';
  const currentRoomLabel = rooms.find(r => r.id === room)?.label || '';

  const send = () => {
    if (!input.trim() || !canChat) return;
    const key = room;
    setByRoom(prev => ({ ...prev, [key]: [{ u: t('me'), t: t('justNowChat'), m: input.trim() }, ...(prev[key] || [])] }));
    setInput('');
  };

  // Build feed items based on selected room
  const items = React.useMemo(() => {
    if (room === 'all') {
      const arr = [];
      CRYPTOLIVE_DATA.liveEvents().forEach(e => arr.push({ kind: 'event', ...e }));
      (byRoom.all || []).forEach((c, i) => arr.push({ kind: 'chat', ...c, _i: i }));
      return arr;
    }
    if (room === 'system') {
      return CRYPTOLIVE_DATA.liveEvents().map(e => ({ kind: 'event', ...e }));
    }
    return (byRoom[room] || []).map((c, i) => ({ kind: 'chat', ...c, _i: i }));
  }, [room, byRoom]);

  const composerPlaceholder = !canChat
    ? ''
    : room === 'all'
      ? t('chatPlaceholderAll')
      : t('chatPlaceholderRoom', currentRoomLabel);

  return (
    <div className="container page" data-screen-label="Live">
      <div style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div className="pulse-dot" style={{ background: 'var(--up)' }} />
          <div className="t-h1">{t('liveTitle')}</div>
        </div>
        <div className="t-meta" style={{ marginTop: 4 }}>{t('liveSub')}</div>
      </div>

      <div className="chips" style={{ marginBottom: 16 }}>
        {rooms.map(r => (
          <button key={r.id} className={`chip ${room === r.id ? 'chip--active' : ''}`} onClick={() => setRoom(r.id)}>
            {r.label}
          </button>
        ))}
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1fr 320px', gap: 16 }}>
        <div>
          {/* Room header for asset rooms */}
          {currentAsset && <RoomHeaderCard asset={currentAsset} />}

          {/* System feed intro card */}
          {room === 'system' && (
            <div className="card" style={{ marginBottom: 16 }}>
              <div style={{ fontWeight: 700, fontSize: 16, marginBottom: 4 }}>{t('systemFeed')}</div>
              <div className="t-meta">{t('systemFeedSub')}</div>
            </div>
          )}

          {/* General room intro card */}
          {room === 'general' && (
            <div className="card" style={{ marginBottom: 16 }}>
              <div style={{ fontWeight: 700, fontSize: 16, marginBottom: 4 }}>{t('generalRoom')}</div>
              <div className="t-meta">{t('generalRoomSub')}</div>
            </div>
          )}

          <div className="card">
            {canChat && (
              <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
                <input
                  className="input"
                  placeholder={composerPlaceholder}
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && send()}
                />
                <button className="btn btn--primary" onClick={send}>{t('sendBtn')}</button>
              </div>
            )}

            {items.map((it, i) => {
              if (it.kind === 'event') return <SystemEvent key={'e' + i} event={it} />;
              return <ChatMessage key={'c' + i} msg={it} />;
            })}
          </div>
        </div>

        {/* Side: trending rooms — clicking goes to room */}
        <div className="card" style={{ alignSelf: 'flex-start' }}>
          <div style={{ fontWeight: 700, marginBottom: 4 }}>{t('activeRooms')}</div>
          <div className="t-meta" style={{ marginBottom: 8 }}>{t('activeRoomsSub')}</div>
          {CRYPTOLIVE_DATA.assets().slice(0, 6).map((a, i) => (
            <div key={a.id} className="row" onClick={() => setRoom(a.id)}>
              <Coin id={a.id} symbol={a.symbol} size="sm" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{a.symbol}</div>
                <div className="t-meta">{t('participantsCount', 200 - i * 28)}</div>
              </div>
              <div className={`pill ${a.change24h > 0 ? 'pill--up' : 'pill--down'}`}>{fmtPct(a.change24h)}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.LiveScreen = LiveScreen;
