// Student · Channels — a locked preview of the coach/admin broadcast channels
// (Announcement, All Members, Free Trial Tier, VIP Members, Signal View).
// Free/Trial members see every channel listed but locked; VIP members get a
// read-only viewer. Boardroom is coach/admin-internal and never shown here.
// Exposes window.ChannelsPanel({client, isVIP, onNeedVip}).
(function(){
const { useState, useEffect } = React;
const CH_LIST=[
  {key:'announcement',label:'Announcement',icon:'📣',desc:'Broadcasts from your coaches',bg:'linear-gradient(135deg,#fbbf24,#b45309)',fg:'#1a1303'},
  {key:'broadcast:all',label:'All Members',icon:'🌐',desc:'Community room for every student & staff',bg:'linear-gradient(135deg,#a5b4fc,#4338ca)',fg:'#0d0f2b'},
  {key:'broadcast:trial',label:'Free Trial Tier',icon:'🌱',desc:'Space for trial members',bg:'linear-gradient(135deg,#cbd5e1,#64748b)',fg:'#10151f'},
  {key:'broadcast:vip',label:'VIP Members',icon:'👑',desc:'VIP-only room with your coaches',bg:'linear-gradient(135deg,#f5d97a,#c79a2e)',fg:'#1a1303'},
  {key:'signalview',label:'Signal View',icon:'📡',desc:'Live trade signal feed',bg:'linear-gradient(135deg,#38bdf8,#0369a1)',fg:'#04141f'},
];
const fmtTime = d => new Date(d).toLocaleString(undefined,{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'});

function ChannelViewer({client,ch,onClose}){
  const [rows,setRows]=useState(null);
  useEffect(()=>{ let stop=false; async function load(){ if(stop) return;
      if(ch.key==='signalview'){ const { data } = await client.from('signals').select('*').order('created_at',{ascending:false}).limit(30); setRows(data||[]); }
      else if(ch.key==='announcement'){ const { data } = await client.from('announcements').select('*').eq('active',true).order('created_at',{ascending:false}); setRows(data||[]); }
      else { const { data } = await client.from('chat_messages').select('*').eq('thread_key',ch.key).eq('deleted',false).order('created_at',{ascending:false}).limit(30); setRows(data||[]); }
    } load(); const iv=setInterval(load,8000); return ()=>{ stop=true; clearInterval(iv); }; },[ch.key]);
  return <div style={{border:'1px solid var(--border)',borderRadius:'var(--radius-sm)',overflow:'hidden',marginTop:10,background:'var(--navy-950)'}}>
    <div style={{padding:'11px 14px',borderBottom:'1px solid var(--border)',display:'flex',alignItems:'center',gap:10}}>
      <span style={{width:30,height:30,borderRadius:'50%',flexShrink:0,display:'grid',placeItems:'center',fontSize:'.8rem',background:ch.bg,color:ch.fg}}>{ch.icon}</span>
      <div style={{fontWeight:600,fontSize:'.88rem',flex:1}}>{ch.label}</div>
      <button onClick={onClose} style={{border:'none',background:'none',color:'var(--ink-faint)',cursor:'pointer',fontSize:'1rem'}}>✕</button>
    </div>
    <div style={{maxHeight:280,overflowY:'auto',padding:'12px 14px',display:'grid',gap:9}}>
      {rows===null && <div style={{textAlign:'center',padding:20}}><span className="cg-spin"></span></div>}
      {rows && rows.length===0 && <p style={{color:'var(--ink-faint)',fontSize:'.86rem',textAlign:'center'}}>Nothing here yet.</p>}
      {ch.key==='signalview' && (rows||[]).map(r=>{ const dc=r.direction==='buy'?'var(--green)':'var(--red)';
        return <div key={r.id} style={{padding:'9px 11px',borderRadius:8,border:'1px solid var(--border)',borderLeft:'3px solid '+dc}}>
          <div style={{display:'flex',gap:8,alignItems:'center',flexWrap:'wrap',fontSize:'.84rem'}}><strong style={{fontFamily:'var(--font-mono)'}}>{r.pair}</strong><span style={{fontFamily:'var(--font-mono)',fontWeight:700,color:dc,fontSize:'.76rem'}}>{r.direction==='buy'?'▲ BUY':'▼ SELL'}</span></div>
          <div style={{fontSize:'.72rem',color:'var(--ink-faint)',fontFamily:'var(--font-mono)',marginTop:4}}>{fmtTime(r.created_at)}</div>
        </div>; })}
      {ch.key==='announcement' && (rows||[]).map(a=>(
        <div key={a.id} style={{padding:'9px 11px',borderRadius:8,border:'1px solid var(--border)'}}>
          {a.title && <div style={{fontWeight:700,fontSize:'.86rem',marginBottom:2}}>{a.title}</div>}
          <div style={{fontSize:'.84rem',color:'var(--ink-dim)'}}>{a.body}</div>
        </div>))}
      {ch.key!=='signalview' && ch.key!=='announcement' && (rows||[]).slice().reverse().map(m=>(
        <div key={m.id} style={{fontSize:'.84rem'}}>
          <span style={{color:'var(--gold-2)',fontFamily:'var(--font-mono)',fontSize:'.72rem',marginRight:6}}>{m.sender_name||m.sender_email}</span>
          <span style={{color:'var(--ink-dim)'}}>{m.body}</span>
        </div>))}
    </div>
  </div>;
}

function ChannelsPanel({client, isVIP, onNeedVip}){
  const [open,setOpen]=useState(null);
  return <div style={{marginTop:22}}>
    <div style={{fontWeight:700,fontSize:'1.02rem',marginBottom:4}}>Channels</div>
    <p style={{color:'var(--ink-dim)',fontSize:'.86rem',marginBottom:14}}>{isVIP ? 'Browse the community rooms your coaches use.' : 'A look at the community rooms \u2014 unlock with VIP to view them.'}</p>
    <div style={{display:'grid',gap:8}}>
      {CH_LIST.map(ch=>{ const locked=!isVIP;
        return <div key={ch.key}>
          <button onClick={()=> locked ? onNeedVip('Must be a VIP member to access '+ch.label+'.') : setOpen(open===ch.key?null:ch.key)}
            style={{width:'100%',display:'flex',alignItems:'center',gap:12,padding:'12px 14px',borderRadius:'var(--radius-sm)',border:'1px solid var(--border)',background:'var(--surface)',cursor:'pointer',textAlign:'left',opacity:locked?.72:1}}>
            <span style={{width:36,height:36,borderRadius:'50%',flexShrink:0,display:'grid',placeItems:'center',fontSize:'.9rem',background:ch.bg,color:ch.fg,filter:locked?'grayscale(.55)':'none'}}>{ch.icon}</span>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontWeight:600,fontSize:'.9rem'}}>{ch.label}</div>
              <div style={{fontSize:'.76rem',color:'var(--ink-faint)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{ch.desc}</div>
            </div>
            {locked
              ? <span style={{fontSize:'.72rem',fontFamily:'var(--font-mono)',color:'var(--gold-2)',border:'1px solid var(--border-gold)',borderRadius:999,padding:'4px 10px',flexShrink:0,display:'flex',alignItems:'center',gap:5}}>🔒 VIP</span>
              : <span style={{fontSize:'.78rem',color:'var(--ink-faint)',flexShrink:0}}>{open===ch.key?'Hide ▲':'View ▾'}</span>}
          </button>
          {!locked && open===ch.key && <ChannelViewer client={client} ch={ch} onClose={()=>setOpen(null)}/>}
        </div>; })}
    </div>
  </div>;
}
window.ChannelsPanel = ChannelsPanel;
})();
