/* Curio — messaging: Messages list + Chat thread (group & DM). window.MessagesScreen, ChatThreadScreen */
const {useState:useChatState,useEffect:useChatEffect,useRef:useChatRef} = React;

function agoLabel(min,lang){
  if(min<1) return lang==='de'?'gerade eben':'just now';
  if(min<60) return `${Math.round(min)} ${lang==='de'?'Min':'min'}`;
  const h=Math.floor(min/60); if(h<24) return `${h} ${lang==='de'?'Std':'h'}`;
  return `${Math.floor(h/24)} ${lang==='de'?'T':'d'}`;
}

/* ── MESSAGES LIST ── */
function MessagesScreen(){
  const{t,lang,state,nav}=useApp();
  const threads=state.threads||window.DATA.seedThreads();
  const groups=threads.filter(th=>th.kind==='group');
  const dms=threads.filter(th=>th.kind==='dm');
  function preview(th){ const m=th.msgs[th.msgs.length-1]; if(!m) return {txt:lang==='de'?'Sag Hallo 👋':'Say hi 👋',ago:0,muted:true}; return {txt:(m.from==='me'?(t('you')+': '):'')+pick(m.t,lang),ago:m.ago,muted:false}; }
  function Row({th}){
    const pv=preview(th);
    return <button type="button" onClick={()=>nav.push('chat-thread',{id:th.id})} className="cu-press" style={{display:'flex',gap:13,alignItems:'center',width:'100%',textAlign:'left',padding:'13px 14px',borderRadius:16,background:T.card,border:`1.5px solid ${T.line}`,boxShadow:SH,cursor:'pointer'}}>
      {th.kind==='group'
        ?<AvStack names={(th.members||[]).map(m=>m.n)} photos={(th.members||[]).map(m=>m.photo)} sz={42}/>
        :<div style={{position:'relative',flexShrink:0}}><Av n={th.name} ci={th.ci} sz={46} photo={th.photo}/>{(()=>{const p=window.DATA.PEOPLE.find(x=>x.id===th.who);return p&&p.online;})()&&<span style={{position:'absolute',right:0,bottom:0,width:12,height:12,borderRadius:'50%',background:T.green,border:`2.5px solid ${T.card}`}}></span>}</div>}
      <div style={{flex:1,minWidth:0}}>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <span style={{flex:1,minWidth:0,color:T.text,fontSize:fz(15),fontWeight:800,fontFamily:F,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{th.name}</span>
          {th.kind==='group'&&<Chip label={t('groupChat')} kind="neutral"/>}
          <span style={{color:T.muted,fontSize:fz(11.5),fontFamily:F,flexShrink:0}}>{agoLabel(pv.ago,lang)}</span>
        </div>
        <p style={{color:pv.muted?'var(--ink-deep)':T.muted,fontSize:fz(13),fontFamily:F,margin:'3px 0 0',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',fontWeight:pv.muted?700:400}}>{pv.txt}</p>
      </div>
    </button>;
  }
  return <div data-screen-label="Messages" className="cu-scroll" style={{flex:1,overflowY:'auto',background:T.bg}}>
    <BackRow title={t('messages')}/>
    {threads.length===0
      ?<div style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',textAlign:'center',padding:'60px 32px'}}>
        <div style={{width:80,height:80,borderRadius:26,background:T.cardAlt,display:'flex',alignItems:'center',justifyContent:'center',fontSize:38,marginBottom:18}}>💬</div>
        <h2 style={{color:T.text,fontSize:fz(19),fontWeight:800,fontFamily:FD,margin:'0 0 8px'}}>{t('noMessages')}</h2>
        <p style={{color:T.muted,fontSize:fz(14),fontFamily:F,lineHeight:1.6,maxWidth:300}}>{t('noMessagesSub')}</p>
      </div>
      :<div style={{padding:'8px 20px 0'}}>
        {groups.length>0&&<><div style={{color:T.muted,fontSize:fz(11.5),fontWeight:800,fontFamily:F,textTransform:'uppercase',letterSpacing:'.6px',margin:'10px 4px 12px'}}>{t('groupChat')}</div>
          <div style={{display:'flex',flexDirection:'column',gap:10,marginBottom:24}}>{groups.map(th=><Row key={th.id} th={th}/>)}</div></>}
        {dms.length>0&&<><div style={{color:T.muted,fontSize:fz(11.5),fontWeight:800,fontFamily:F,textTransform:'uppercase',letterSpacing:'.6px',margin:'0 4px 12px'}}>{t('directMessages')}</div>
          <div style={{display:'flex',flexDirection:'column',gap:10}}>{dms.map(th=><Row key={th.id} th={th}/>)}</div></>}
      </div>}
    <Gap n={28}/>
  </div>;
}

/* ── CHAT THREAD ── */
function ChatThreadScreen(){
  const{t,lang,state,nav,route,actions}=useApp();
  const threads=state.threads||window.DATA.seedThreads();
  const th=threads.find(x=>x.id===route.p.id)||threads[0];
  const[draft,setDraft]=useChatState('');
  const[typing,setTyping]=useChatState(false);
  const scrollRef=useChatRef(null);
  const person=th&&th.kind==='dm'?window.DATA.PEOPLE.find(p=>p.id===th.who):null;
  const online=th&&th.kind==='group'?true:(person&&person.online);
  useChatEffect(()=>{ const el=scrollRef.current; if(el) el.scrollTop=el.scrollHeight; },[th&&th.msgs.length,typing]);
  if(!th) return <div className="cu-fill" style={{background:T.bg}}></div>;

  function senderMeta(from){
    if(from==='me') return {me:true,name:t('you'),photo:state.photo,ci:state.avatar};
    if(th.kind==='dm') return {me:false,name:th.name,photo:th.photo,ci:th.ci};
    const m=(th.members||[]).find(x=>x.n===from)||{n:from,ci:0};
    return {me:false,name:m.n,photo:m.photo,ci:m.ci};
  }
  function reply(){
    const who=th.kind==='dm'?th.name:((th.members||[])[Math.floor(Math.random()*(th.members||[1]).length)]?.n||th.name);
    const lines=th.kind==='dm'
      ? {en:['Sounds great! 😊','Yes, let\'s do it.','Haha totally. See you there!','Can\'t wait 🎨'],de:['Klingt super! 😊','Ja, machen wir.','Haha total. Bis dann!','Freu mich 🎨']}
      : {en:['On it 👍','Nice, almost there!','Let\'s gooo 🚀','Saving you a clue.'],de:['Bin dabei 👍','Cool, fast da!','Auf geht\'s 🚀','Heb dir einen Hinweis auf.']};
    const arr=lines[lang]||lines.en; const text=arr[Math.floor(Math.random()*arr.length)];
    setTyping(true);
    setTimeout(()=>{ setTyping(false); actions.pushMessage(th.id,{from:who,t:{en:text,de:text},ago:0}); },1400);
  }
  function send(){
    const txt=draft.trim(); if(!txt) return;
    actions.sendMessage(th.id,txt); setDraft(''); reply();
  }

  return <div data-screen-label="Chat" className="cu-fill" style={{display:'flex',flexDirection:'column',background:T.bg,minHeight:0}}>
    
    {/* header */}
    <div style={{display:'flex',alignItems:'center',gap:12,padding:'8px 16px 12px',borderBottom:`1px solid ${T.line}`}}>
      <IconBtn k="arrowL" onClick={nav.pop} ariaLabel={t('back')}/>
      {th.kind==='group'
        ?<AvStack names={(th.members||[]).map(m=>m.n)} photos={(th.members||[]).map(m=>m.photo)} sz={36}/>
        :<Av n={th.name} ci={th.ci} sz={40} photo={th.photo}/>}
      <div style={{flex:1,minWidth:0}}>
        <div style={{color:T.text,fontSize:fz(16),fontWeight:800,fontFamily:F,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{th.name}</div>
        <div style={{color:online?T.green:T.muted,fontSize:fz(12),fontFamily:F,display:'flex',alignItems:'center',gap:5}}>
          {online&&<span style={{width:7,height:7,borderRadius:'50%',background:T.green,display:'inline-block'}}></span>}
          {th.kind==='group'?`${(th.members||[]).length+1} ${t('membersCount')}`:(online?t('activeNow'):'')}
        </div>
      </div>
      {th.kind==='group'&&<IconBtn k="users" onClick={()=>nav.push('group-lobby',{code:th.code})} ariaLabel={t('crew')}/>}
    </div>
    {/* messages */}
    <div ref={scrollRef} className="cu-scroll" style={{flex:1,overflowY:'auto',padding:'16px 16px 8px',display:'flex',flexDirection:'column',gap:3,minHeight:0}}>
      {th.msgs.map((m,i)=>{
        const meta=senderMeta(m.from);
        const prev=th.msgs[i-1];
        const firstOfGroup=!prev||prev.from!==m.from;
        return <div key={i} style={{display:'flex',gap:8,alignItems:'flex-end',flexDirection:meta.me?'row-reverse':'row',marginTop:firstOfGroup?10:0}}>
          <span style={{width:28,flexShrink:0}}>{!meta.me&&firstOfGroup&&<Av n={meta.name} ci={meta.ci} sz={28} photo={meta.photo}/>}</span>
          <div style={{maxWidth:'74%'}}>
            {th.kind==='group'&&!meta.me&&firstOfGroup&&<div style={{color:T.muted,fontSize:fz(11),fontWeight:700,fontFamily:F,margin:'0 0 3px 10px',padding:'0 0 0 4px'}}>{meta.name}</div>}
            <div style={{padding:'10px 14px',borderRadius:meta.me?'16px 16px 5px 16px':'16px 16px 16px 5px',background:meta.me?'var(--ink)':T.card,border:meta.me?'none':`1.5px solid ${T.line}`,boxShadow:SH,color:meta.me?'#fff':T.text,fontSize:fz(14),fontFamily:F,lineHeight:1.45,wordBreak:'break-word'}}>{pick(m.t,lang)}</div>
          </div>
        </div>;
      })}
      {typing&&<div style={{display:'flex',gap:8,alignItems:'flex-end',marginTop:10}}>
        <Av n={th.kind==='dm'?th.name:'·'} ci={th.ci||0} sz={28} photo={th.kind==='dm'?th.photo:undefined}/>
        <div style={{padding:'12px 16px',borderRadius:'16px 16px 16px 5px',background:T.card,border:`1.5px solid ${T.line}`,boxShadow:SH,display:'flex',gap:4}}>
          {[0,1,2].map(i=><span key={i} className="cu-typing-dot" style={{width:7,height:7,borderRadius:'50%',background:T.muted,display:'block',animationDelay:`${i*.18}s`}}></span>)}
        </div>
      </div>}
    </div>
    {/* composer */}
    <div style={{display:'flex',gap:9,alignItems:'flex-end',padding:'10px 14px',paddingBottom:'max(14px, env(safe-area-inset-bottom))',borderTop:`1px solid ${T.line}`,background:T.card}}>
      <textarea value={draft} onChange={e=>setDraft(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send();}}} rows={1} placeholder={t('typeMessage')} aria-label={t('typeMessage')} style={{flex:1,resize:'none',maxHeight:96,padding:'11px 15px',borderRadius:20,border:`1.5px solid ${T.lineMd}`,background:T.bg,color:T.text,fontSize:fz(14.5),fontFamily:F,lineHeight:1.4,outline:'none',boxSizing:'border-box'}}></textarea>
      <button type="button" onClick={send} disabled={!draft.trim()} aria-label={t('send')} className="cu-press" style={{width:44,height:44,borderRadius:22,border:'none',flexShrink:0,background:draft.trim()?'var(--ink)':T.lineMd,color:'#fff',cursor:draft.trim()?'pointer':'default',display:'flex',alignItems:'center',justifyContent:'center',transition:'background .15s'}}><Ic k="arrowR" size={20} stroke={2.6}/></button>
    </div>
  </div>;
}

Object.assign(window,{MessagesScreen,ChatThreadScreen});
