// 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;
// Channel identity. Emoji were replaced with gold line-art SVGs — emoji render
// inconsistently across Windows/Android and read as unpolished next to the rest
// of the brand. VIP Members carries the real VIP Signal mark, the same one used
// on the Telegram broadcasts, so members recognise it instantly.
const ICON = {
  announcement: <svg viewBox="0 0 24 24"><path d="M3 11v2a1 1 0 0 0 1 1h2l4.5 3.4a.6.6 0 0 0 1-.5V7.1a.6.6 0 0 0-1-.5L6 10H4a1 1 0 0 0-1 1z"/><path d="M16.5 8.5a5 5 0 0 1 0 7"/><path d="M19 6a8.5 8.5 0 0 1 0 12"/></svg>,
  all:          <svg viewBox="0 0 24 24"><circle cx="9" cy="8" r="3.1"/><path d="M3.2 19a5.8 5.8 0 0 1 11.6 0"/><circle cx="17.5" cy="9.2" r="2.4"/><path d="M16 14.6a4.7 4.7 0 0 1 5 4.4"/></svg>,
  trial:        <svg viewBox="0 0 24 24"><path d="M12 20v-7"/><path d="M12 13c0-3.4 2.6-6 6-6 0 3.4-2.6 6-6 6z"/><path d="M12 15c0-2.8-2.2-5-5-5 0 2.8 2.2 5 5 5z"/></svg>,
  vip:          <svg viewBox="0 0 24 24"><path d="M3 8l4.2 3.2L12 5l4.8 6.2L21 8l-1.8 10H4.8L3 8z"/><path d="M4.8 20h14.4"/></svg>,
  signal:       <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="2.1"/><path d="M8.2 8.2a5.4 5.4 0 0 0 0 7.6"/><path d="M15.8 15.8a5.4 5.4 0 0 0 0-7.6"/><path d="M5.5 5.5a9.2 9.2 0 0 0 0 13"/><path d="M18.5 18.5a9.2 9.2 0 0 0 0-13"/></svg>,
  lock:         <svg viewBox="0 0 24 24"><rect x="4.8" y="10.5" width="14.4" height="9.2" rx="2.2"/><path d="M8.4 10.5V7.8a3.6 3.6 0 0 1 7.2 0v2.7"/></svg>,
};
const CH_LIST=[
  {key:'announcement',label:'Announcement',icon:ICON.announcement,desc:'Broadcasts from your coaches'},
  {key:'broadcast:all',label:'All Members',icon:ICON.all,desc:'Community room for every student & staff'},
  {key:'broadcast:trial',label:'Free Trial Tier',icon:ICON.trial,desc:'Space for trial members'},
  {key:'broadcast:vip',label:'VIP Members',icon:ICON.vip,desc:'VIP-only room with your coaches',brand:'assets/brand/vip-128.png'},
  {key:'signalview',label:'Signal View',icon:ICON.signal,desc:'Live trade signal feed'},
];

// One tile renderer for both the list row and the open viewer header.
function ChIcon({ch, size}){
  const s = size || 38;
  if (ch.brand) return <img src={ch.brand} alt="" width={s} height={s}
    style={{width:s,height:s,borderRadius:'50%',objectFit:'cover',flexShrink:0,
            border:'1px solid var(--border-gold)',boxShadow:'0 2px 10px rgba(212,175,55,.28)'}}/>;
  return <span style={{width:s,height:s,flexShrink:0,borderRadius:'50%',display:'grid',placeItems:'center',
      background:'linear-gradient(150deg,rgba(212,175,55,.16),rgba(212,175,55,.04))',
      border:'1px solid var(--border-gold)'}}>
    <span style={{width:Math.round(s*0.5),height:Math.round(s*0.5),display:'block'}}>
      {React.cloneElement(ch.icon,{style:{width:'100%',height:'100%',fill:'none',stroke:'var(--gold-2)',
        strokeWidth:1.7,strokeLinecap:'round',strokeLinejoin:'round'}})}
    </span>
  </span>;
}
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}}>
      <ChIcon ch={ch} size={30}/>
      <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={{flexShrink:0,opacity:locked?.6:1,filter:locked?'grayscale(.5)':'none',display:'flex'}}><ChIcon ch={ch} size={38}/></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:'inline-flex',alignItems:'center',gap:6}}><span style={{width:11,height:11,display:'block'}}>{React.cloneElement(ICON.lock,{style:{width:'100%',height:'100%',fill:'none',stroke:'currentColor',strokeWidth:1.9,strokeLinecap:'round',strokeLinejoin:'round'}})}</span>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;
})();
