// CHAT (group rooms only) + PROFILE (my clips / friend's clips in same group).

const { useState: useC } = React;
const TC = window.DAIL_TOKENS;
const cc = TC.colors, fsc = TC.fontSizes, fwc = TC.fontWeights, rsc = TC.radius;
const FRIENDS = window.DAIL_FRIENDS;
const GROUPS  = window.DAIL_GROUPS;
const CLIPS   = window.DAIL_CLIPS;
const baseTextC = { fontFamily: TC.fonts.primary, color: cc.textPrimary, lineHeight: 1.4 };

// Tiny avatar shared across these screens.
function Avatar({ initials = '?', size = 36, tone = 0 }) {
  // Tone gives variety without inventing palette
  const tones = [
    { bg:'rgba(61,90,128,0.12)',  fg:cc.accent },
    { bg:'rgba(74,124,89,0.14)',  fg:cc.success },
    { bg:'rgba(184,92,92,0.14)',  fg:cc.error },
    { bg:'rgba(0,0,0,0.06)',      fg:cc.textPrimary },
  ];
  const t = tones[tone % tones.length];
  return (
    <div style={{ width:size, height:size, borderRadius:size/2, background:t.bg, color:t.fg, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, ...baseTextC, fontWeight:fwc.bold, fontSize: Math.round(size*0.4) }}>
      {initials}
    </div>
  );
}

// Bottom tab bar — 지도 / 채팅. Used on Chat list and Profile screens.
function TabBar({ active = 'chat' }) {
  const items = [
    { k:'map', label:'지도',
      icon: (a) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M9 4 4 6v14l5-2 6 2 5-2V4l-5 2-6-2zM9 4v14M15 6v14" stroke={a ? cc.textPrimary : cc.textTertiary} strokeWidth="1.7" strokeLinejoin="round"/></svg> },
    { k:'chat', label:'채팅',
      icon: (a) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M4 6c0-1.1.9-2 2-2h12a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-7l-4 3v-3H6a2 2 0 0 1-2-2V6z" stroke={a ? cc.textPrimary : cc.textTertiary} strokeWidth="1.7" strokeLinejoin="round"/></svg> },
  ];
  return (
    <div style={{
      position:'absolute', left:0, right:0, bottom:0,
      background:cc.card, borderTop:`1px solid ${cc.divider}`,
      paddingTop:8, paddingBottom:24,
      display:'flex', alignItems:'center', justifyContent:'space-around',
    }}>
      {items.map(it => {
        const a = active === it.k;
        return (
          <button key={it.k} style={{ background:'none', border:'none', cursor:'pointer', display:'flex', flexDirection:'column', alignItems:'center', gap:3, padding:'4px 18px', minWidth:80 }}>
            {it.icon(a)}
            <span style={{ ...baseTextC, fontSize:11, fontWeight: a ? fwc.semibold : fwc.medium, color: a ? cc.textPrimary : cc.textTertiary }}>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ───────── CHAT — list of group rooms (groups = rooms, auto-created) ─────────
window.DAIL_ChatListScreen = function ChatListScreen() {
  // Build per-group last-message + unread (synthesized from clips for demo).
  const rooms = Object.entries(GROUPS).map(([k, g]) => {
    const groupClips = CLIPS.filter(c => c.group === k);
    const last = groupClips[0];
    const author = last ? FRIENDS[last.author] : null;
    return {
      key: k, name: g.name, members: g.members,
      lastAuthor: author?.name || null,
      lastText: last ? `${last.place} · ${last.title}` : '대화를 시작해보세요',
      lastTime: last ? last.when : '',
      unread: k === 'seongsu' ? 3 : (k === 'jachi' ? 1 : 0),
      hasVideo: Boolean(last),
    };
  });

  return (
    <div style={{ width:'100%', height:'100%', background:cc.bg, display:'flex', flexDirection:'column' }}>
      {/* Top bar */}
      <div style={{ paddingTop:60, paddingLeft:18, paddingRight:18, paddingBottom:10, background:cc.card, borderBottom:`1px solid ${cc.divider}`, display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <span style={{ ...baseTextC, fontSize:24, fontWeight:fwc.bold, letterSpacing:'-0.02em' }}>채팅</span>
        <button style={{ width:36, height:36, borderRadius:18, background:cc.bg, border:`1px solid ${cc.divider}`, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }} title="새 그룹">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M8 3v10M3 8h10" stroke={cc.textPrimary} strokeWidth="1.8" strokeLinecap="round"/></svg>
        </button>
      </div>

      {/* Rooms */}
      <div style={{ flex:1, overflowY:'auto', background:cc.card }}>
        {rooms.map((r, i) => (
          <button key={r.key} style={{
            width:'100%', display:'flex', alignItems:'center', gap:12,
            padding:'14px 16px', background:'none', border:'none',
            borderBottom: i === rooms.length-1 ? 'none' : `1px solid ${cc.divider}`,
            cursor:'pointer', textAlign:'left',
          }}>
            <Avatar initials={r.name[0]} size={48} tone={i}/>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', gap:8 }}>
                <div style={{ display:'flex', alignItems:'baseline', gap:6, minWidth:0 }}>
                  <span style={{ ...baseTextC, fontSize:fsc.body, fontWeight:fwc.semibold, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{r.name}</span>
                  <span style={{ ...baseTextC, fontSize:fsc.caption, color:cc.textTertiary, flexShrink:0 }}>{r.members}</span>
                </div>
                <span style={{ ...baseTextC, fontSize:fsc.caption, color: r.unread ? cc.accent : cc.textTertiary, flexShrink:0, fontWeight: r.unread ? fwc.semibold : fwc.medium }}>{r.lastTime}</span>
              </div>
              <div style={{ display:'flex', alignItems:'center', gap:6, marginTop:3 }}>
                {r.hasVideo ? <span style={{ fontSize:11, color:cc.accent }}>▶︎</span> : null}
                <span style={{ ...baseTextC, fontSize:fsc.caption, color: r.unread ? cc.textPrimary : cc.textSecondary, fontWeight: r.unread ? fwc.medium : fwc.regular, flex:1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
                  {r.lastAuthor ? <span style={{ color:cc.textTertiary }}>{r.lastAuthor} · </span> : null}{r.lastText}
                </span>
                {r.unread ? (
                  <span style={{ minWidth:20, height:20, padding:'0 6px', borderRadius:10, background:cc.accent, color:'#FFF', ...baseTextC, fontSize:11, fontWeight:fwc.bold, display:'flex', alignItems:'center', justifyContent:'center' }}>{r.unread}</span>
                ) : null}
              </div>
            </div>
          </button>
        ))}
      </div>

      <TabBar active="chat"/>
      <div style={{ height:74 }}/>{/* tabbar spacer (overlay) */}
    </div>
  );
};

// ───────── CHAT ROOM — single group room (Kakao-ish) ─────────
window.DAIL_ChatRoomScreen = function ChatRoomScreen({ groupKey = 'seongsu' } = {}) {
  const g = GROUPS[groupKey];
  const groupClips = CLIPS.filter(c => c.group === groupKey).slice(0, 2);

  // Scripted demo timeline.
  const messages = [
    { kind:'date', text:'오늘' },
    { kind:'msg', who:'minji', text:'성수 가는 사람?', t:'14:02' },
    { kind:'msg', who:'haru',  text:'나 갈건데 dail.coffee ㄱ?', t:'14:03' },
    { kind:'msg', who:'minji', text:'ㅇㅋㅇㅋ', t:'14:03' },
    groupClips[0] ? { kind:'video', clip: groupClips[0], t:'14:48' } : null,
    { kind:'msg', who:'jiwoo', text:'미쳤다 진짜', t:'14:50' },
    { kind:'msg', who:'me', text:'나도 갈래!!', t:'14:51' },
    groupClips[1] ? { kind:'video', clip: groupClips[1], t:'15:30' } : null,
  ].filter(Boolean);

  return (
    <div style={{ width:'100%', height:'100%', background:cc.bg, display:'flex', flexDirection:'column', overflow:'hidden' }}>
      {/* Header */}
      <div style={{ paddingTop:60, paddingLeft:14, paddingRight:14, paddingBottom:10, background:cc.card, borderBottom:`1px solid ${cc.divider}`, display:'flex', alignItems:'center', gap:10 }}>
        <button style={{ width:32, height:32, background:'none', border:'none', cursor:'pointer', color:cc.textPrimary, fontSize:22, lineHeight:1 }}>‹</button>
        <Avatar initials={g.name[0]} size={32} tone={0}/>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ ...baseTextC, fontSize:fsc.body, fontWeight:fwc.semibold }}>{g.name}</div>
          <div style={{ ...baseTextC, fontSize:fsc.caption, color:cc.textTertiary, marginTop:1 }}>{g.members}명</div>
        </div>
        <button style={{ width:32, height:32, background:'none', border:'none', cursor:'pointer', color:cc.textTertiary, fontSize:18, lineHeight:1 }}>≡</button>
      </div>

      {/* Messages */}
      <div style={{ flex:1, overflowY:'auto', padding:'14px 12px', display:'flex', flexDirection:'column', gap:8 }}>
        {messages.map((m, i) => {
          if (m.kind === 'date') {
            return (
              <div key={i} style={{ alignSelf:'center', padding:'4px 12px', borderRadius:12, background:'rgba(0,0,0,0.05)', margin:'4px 0' }}>
                <span style={{ ...baseTextC, fontSize:11, color:cc.textTertiary, fontWeight:fwc.medium }}>{m.text}</span>
              </div>
            );
          }
          const isMe = m.who === 'me';
          const author = !isMe && m.who ? FRIENDS[m.who] : null;
          if (m.kind === 'video') {
            const author2 = FRIENDS[m.clip.author];
            const meVid = m.clip.author === 'me'; // none currently
            return (
              <div key={i} style={{ display:'flex', flexDirection: meVid ? 'row-reverse' : 'row', alignItems:'flex-end', gap:8 }}>
                {!meVid ? <Avatar initials={author2?.initials || '?'} size={28} tone={i}/> : null}
                <div style={{ maxWidth:'78%' }}>
                  {!meVid ? (
                    <div style={{ ...baseTextC, fontSize:fsc.caption, color:cc.textSecondary, marginBottom:3, marginLeft:4, fontWeight:fwc.medium }}>{author2?.name}</div>
                  ) : null}
                  <div style={{ borderRadius:14, overflow:'hidden', background:'#000', position:'relative', aspectRatio:'16 / 9', width:240 }}>
                    <img src={m.clip.photo} alt="" style={{ width:'100%', height:'100%', objectFit:'cover' }}/>
                    <div style={{ position:'absolute', left:0, right:0, top:'62%', textAlign:'center', padding:'0 12px' }}>
                      <span style={{ ...baseTextC, color:'#FFF', fontSize:14, fontWeight:fwc.bold, textShadow:'0 1px 4px rgba(0,0,0,0.6)' }}>{m.clip.title}</span>
                    </div>
                    <div style={{ position:'absolute', bottom:6, left:6, padding:'1px 6px', borderRadius:3, background:'rgba(0,0,0,0.55)' }}>
                      <span style={{ ...baseTextC, color:'#FFF', fontSize:9, fontWeight:fwc.medium }}>📍 {m.clip.place}</span>
                    </div>
                    <div style={{ position:'absolute', bottom:6, right:6, padding:'1px 5px', borderRadius:3, background:'rgba(0,0,0,0.55)' }}>
                      <span style={{ ...baseTextC, color:'#FFF', fontSize:9, fontWeight:fwc.medium, fontVariantNumeric:'tabular-nums' }}>0:05</span>
                    </div>
                  </div>
                </div>
                <span style={{ ...baseTextC, fontSize:10, color:cc.textTertiary, alignSelf:'flex-end', marginBottom:2 }}>{m.t}</span>
              </div>
            );
          }
          // text message
          return (
            <div key={i} style={{ display:'flex', flexDirection: isMe ? 'row-reverse' : 'row', alignItems:'flex-end', gap:6 }}>
              {!isMe ? <Avatar initials={author?.initials || '?'} size={28} tone={i}/> : null}
              <div style={{ maxWidth:'72%' }}>
                {!isMe ? (
                  <div style={{ ...baseTextC, fontSize:fsc.caption, color:cc.textSecondary, marginBottom:2, marginLeft:4, fontWeight:fwc.medium }}>{author?.name}</div>
                ) : null}
                <div style={{
                  padding:'8px 12px',
                  background: isMe ? cc.accent : cc.card,
                  color: isMe ? '#FFF' : cc.textPrimary,
                  borderRadius: 14,
                  borderBottomLeftRadius: isMe ? 14 : 4,
                  borderBottomRightRadius: isMe ? 4 : 14,
                  border: isMe ? 'none' : `1px solid ${cc.divider}`,
                }}>
                  <span style={{ ...baseTextC, fontSize:fsc.body, fontWeight:fwc.medium, color: isMe ? '#FFF' : cc.textPrimary }}>{m.text}</span>
                </div>
              </div>
              <span style={{ ...baseTextC, fontSize:10, color:cc.textTertiary, alignSelf:'flex-end', marginBottom:2 }}>{m.t}</span>
            </div>
          );
        })}
      </div>

      {/* Composer */}
      <div style={{ background:cc.card, borderTop:`1px solid ${cc.divider}`, padding:'8px 12px 28px', display:'flex', alignItems:'center', gap:8 }}>
        <button style={{ width:34, height:34, borderRadius:17, border:'none', background:cc.bg, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }} title="영상 찍기">
          <svg width="16" height="16" viewBox="0 0 22 22" fill="none"><circle cx="11" cy="11" r="4.5" stroke={cc.textPrimary} strokeWidth="1.6"/><rect x="3" y="6.5" width="16" height="11" rx="2" stroke={cc.textPrimary} strokeWidth="1.6"/></svg>
        </button>
        <div style={{ flex:1, height:36, padding:'0 14px', borderRadius:18, background:cc.bg, border:`1px solid ${cc.divider}`, display:'flex', alignItems:'center' }}>
          <span style={{ ...baseTextC, fontSize:fsc.body, color:cc.textTertiary }}>메시지 입력</span>
        </div>
        <button style={{ width:34, height:34, borderRadius:17, border:'none', background:cc.accent, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }} title="보내기">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 7l10-4-4 10-2-4-4-2z" stroke="#FFF" strokeWidth="1.4" strokeLinejoin="round" fill="rgba(255,255,255,0.18)"/></svg>
        </button>
      </div>
    </div>
  );
};

// ───────── PROFILE — my clips, or friend's clips inside one group ─────────
// scope='me' or scope='friend'. friend mode requires friendKey + visibleGroupKey.
window.DAIL_ProfileScreen = function ProfileScreen({
  scope = 'me',
  friendKey = 'minji',
  visibleGroupKey = 'seongsu',
} = {}) {
  const isMe = scope === 'me';
  const friend = !isMe ? FRIENDS[friendKey] : null;
  const group  = GROUPS[visibleGroupKey];

  // Demo: synthesize "my" clips — re-tag a couple of existing clips as the current user's posts.
  const mineSeed = ['c2', 'c5', 'c8'];
  const myClips = CLIPS.filter(c => mineSeed.includes(c.id));

  const list = isMe
    ? myClips
    : CLIPS.filter(c => c.author === friendKey && c.group === visibleGroupKey);

  const name = isMe ? '나' : friend?.name;
  const initials = isMe ? '나' : friend?.initials;

  return (
    <div style={{ width:'100%', height:'100%', background:cc.bg, display:'flex', flexDirection:'column', overflow:'hidden' }}>
      {/* Header */}
      <div style={{ paddingTop:60, paddingLeft:14, paddingRight:14, paddingBottom:10, background:cc.card, borderBottom:`1px solid ${cc.divider}`, display:'flex', alignItems:'center', gap:8 }}>
        <button style={{ width:32, height:32, background:'none', border:'none', cursor:'pointer', color:cc.textPrimary, fontSize:22, lineHeight:1 }}>‹</button>
        <span style={{ flex:1, ...baseTextC, fontSize:fsc.heading, fontWeight:fwc.semibold, textAlign:'center' }}>
          {isMe ? '내 영상' : `${name}의 영상`}
        </span>
        {!isMe ? <span style={{ width:32 }}/> : null}
        {isMe ? (
          <button style={{ width:32, height:32, background:'none', border:'none', cursor:'pointer', color:cc.textTertiary, fontSize:18, lineHeight:1 }}>⚙</button>
        ) : <span style={{ width:32 }}/>}
      </div>

      {/* Profile block */}
      <div style={{ background:cc.card, padding:'18px 18px 14px', borderBottom:`1px solid ${cc.divider}`, display:'flex', alignItems:'center', gap:14 }}>
        <Avatar initials={initials} size={64} tone={isMe ? 3 : 0}/>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ ...baseTextC, fontSize:20, fontWeight:fwc.bold, letterSpacing:'-0.01em' }}>{name}</div>
          <div style={{ ...baseTextC, fontSize:fsc.caption, color:cc.textTertiary, marginTop:3 }}>
            {isMe
              ? `올린 영상 ${list.length}개 · 그룹 ${Object.keys(GROUPS).length}개`
              : `${group?.name}에 올린 영상 ${list.length}개`}
          </div>
        </div>
      </div>

      {/* Friend mode notice removed — 그룹 권한은 이미 프로필 타이틀에서 명시됨 */}

      {/* List */}
      <div style={{ flex:1, overflowY:'auto', background:cc.bg }}>
        {list.length === 0 ? (
          <div style={{ padding:'60px 24px', textAlign:'center' }}>
            <div style={{ fontSize:32, marginBottom:6 }}>📭</div>
            <div style={{ ...baseTextC, fontSize:fsc.body, fontWeight:fwc.semibold, marginBottom:3 }}>
              {isMe ? '아직 올린 영상이 없어요' : `${name}이(가) ${group?.name}에 올린 영상이 없어요`}
            </div>
            <div style={{ ...baseTextC, fontSize:fsc.caption, color:cc.textTertiary }}>
              {isMe ? '지도에서 + 버튼을 눌러 첫 영상을 올려보세요' : '다른 그룹의 영상은 볼 수 없어요'}
            </div>
          </div>
        ) : (
          <div style={{ padding:'10px 0 24px' }}>
            {list.map(c => (
              <button key={c.id} style={{ width:'100%', padding:'8px 14px', background:'none', border:'none', cursor:'pointer', textAlign:'left' }}>
                <div style={{ background:cc.card, border:`1px solid ${cc.divider}`, borderRadius:rsc.lg, overflow:'hidden' }}>
                  {/* Video 16:9 */}
                  <div style={{ position:'relative', width:'100%', aspectRatio:'16 / 9', background:'#000' }}>
                    <img src={c.photo} alt="" style={{ width:'100%', height:'100%', objectFit:'cover' }}/>
                    {/* Place chip — top left, baked into video */}
                    <div style={{ position:'absolute', top:8, left:8, height:22, padding:'0 8px', borderRadius:11, background:'rgba(0,0,0,0.55)', display:'flex', alignItems:'center', backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)' }}>
                      <span style={{ ...baseTextC, color:'#FFF', fontSize:10, fontWeight:fwc.semibold }}>{c.place}</span>
                    </div>
                    {/* Mute badge — top right */}
                    <div style={{ position:'absolute', top:8, right:8, background:'rgba(0,0,0,0.55)', borderRadius:999, padding:'4px 8px', display:'flex', alignItems:'center', gap:4, backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)' }}>
                      <svg width="11" height="11" viewBox="0 0 12 12" fill="none">
                        <path d="M2 4.5h2L6.5 2v8L4 7.5H2z" fill="#FFF"/>
                        <path d="m9 4 2.5 4M11.5 4 9 8" stroke="#FFF" strokeWidth="1.2" strokeLinecap="round"/>
                      </svg>
                      <span style={{ ...baseTextC, color:'#FFF', fontSize:10, fontWeight:fwc.medium }}>음소거</span>
                    </div>
                    {/* Caption — baked into video */}
                    <div style={{ position:'absolute', left:0, right:0, top:'62%', textAlign:'center', padding:'0 16px', pointerEvents:'none' }}>
                      <span style={{ ...baseTextC, color:'#FFF', fontSize:18, fontWeight:fwc.bold, textShadow:'0 2px 6px rgba(0,0,0,0.65)' }}>{c.title}</span>
                    </div>
                    {/* Time pill — bottom-left, baked in */}
                    <div style={{ position:'absolute', bottom:8, left:8, height:18, padding:'0 7px', borderRadius:9, background:'rgba(0,0,0,0.55)', display:'flex', alignItems:'center', backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)' }}>
                      <span style={{ ...baseTextC, color:'#FFF', fontSize:10, fontWeight:fwc.medium }}>{c.when}</span>
                    </div>
                    <div style={{ position:'absolute', bottom:8, right:8, padding:'2px 6px', borderRadius:3, background:'rgba(0,0,0,0.6)' }}>
                      <span style={{ ...baseTextC, color:'#FFF', fontSize:10, fontWeight:fwc.medium, fontVariantNumeric:'tabular-nums' }}>0:05</span>
                    </div>
                  </div>
                  {/* Meta removed — 장소·시간 모두 영상 안에 베이크됨 */}
                </div>
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};
