// Chart Growth Hub — Student "Live Trading Room" panel.
// Access model v2 (2026-07-16): the old $88 separate paywall is RETIRED.
//   VIP members  -> full live access automatically, bundled into VIP tuition. No payment here.
//   Free Trial   -> limited live access, gated on a manually admin-verified broker account
//                   (VT Markets, under our IB) + an admin-set session cap. No payment either —
//                   this is earned by having a funded broker account, not by paying us directly.
// Source of truth: students.vip (VIP) and live_access.broker_verified / session_cap / sessions_used (Free Trial).
// Exposes window.LivePanel.
(function(){
const { useState, useEffect } = React;

// ---- video helpers ----
function ytId(u){ const m=(u||'').match(/(?:youtu\.be\/|v=|embed\/)([\w-]{11})/); return m?m[1]:null; }
function vimeoId(u){ const m=(u||'').match(/vimeo\.com\/(?:video\/)?(\d+)/); return m?m[1]:null; }
function recEmbed(s){
  if(s.recording_type==='youtube'){ const id=ytId(s.recording_url); return id?`https://www.youtube.com/embed/${id}?rel=0`:null; }
  if(s.recording_type==='vimeo'){ const id=vimeoId(s.recording_url); return id?`https://player.vimeo.com/video/${id}`:null; }
  return null;
}
const fmtWhen = d => d ? new Date(d).toLocaleString(undefined,{weekday:'short',month:'short',day:'numeric',hour:'numeric',minute:'2-digit'}) : '';

function Card({children, style}){ return <div style={{background:'linear-gradient(165deg,var(--surface-2),var(--surface))',border:'1px solid var(--border-gold)',borderRadius:'var(--radius)',padding:'30px 30px',position:'relative',overflow:'hidden',...style}}>{children}</div>; }
const Bullet = ({children}) => <li style={{display:'flex',gap:11,alignItems:'flex-start',marginBottom:11,color:'var(--ink-dim)',fontSize:'.96rem'}}>
  <span className="ck" style={{marginTop:1}}><svg viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></svg></span><span>{children}</span></li>;

function LivePanel({client, session}){
  const [vip,setVip]=useState(undefined);      // undefined=loading, true/false once known
  const [la,setLa]=useState(undefined);        // live_access row (Free Trial verification/session cap) — undefined=loading, null=none yet
  const [sessions,setSessions]=useState([]);
  const [open,setOpen]=useState(null);         // recording modal
  const [err,setErr]=useState("");

  async function load(){
    const { data:stu } = await client.from('students').select('vip').eq('id',session.user.id).maybeSingle();
    const isVip = !!(stu && stu.vip); setVip(isVip);
    const { data:row } = await client.from('live_access').select('*').eq('student_id',session.user.id).maybeSingle();
    setLa(row||null);
    const trialCanJoin = !!(row && row.broker_verified && row.session_cap!=null && (row.sessions_used||0) < row.session_cap);
    if(isVip || trialCanJoin){
      const { data:s } = await client.from('live_sessions').select('*').order('starts_at',{ascending:true});
      setSessions(s||[]);
    }
  }
  useEffect(()=>{ load(); /* eslint-disable-next-line */ },[]);

  if(vip===undefined || la===undefined) return null; // loading — stay quiet

  const cap = la ? la.session_cap : null;
  const used = la ? (la.sessions_used||0) : 0;
  const verified = !!(la && la.broker_verified);
  const trialCanJoin = verified && cap!=null && used < cap;

  // ---------- ROOM: VIP (unlimited) or Free Trial with sessions remaining ----------
  if(vip || trialCanJoin){
    const now=Date.now();
    const upcoming=sessions.filter(s=>!s.recording_url && (!s.starts_at || new Date(s.starts_at).getTime()>now-3*3600e3));
    const recordings=sessions.filter(s=>s.recording_url);
    return <Section>
      <RoomHead vip={vip} remaining={vip?null:Math.max(0,cap-used)}/>
      <Card style={{borderColor:'var(--border-gold)',marginBottom:22}}>
        <div className="grid-bg"></div>
        <div style={{position:'relative'}}>
          <div style={{fontFamily:'var(--font-mono)',fontSize:'.72rem',letterSpacing:'.16em',textTransform:'uppercase',color:'var(--gold)',marginBottom:14}}>Upcoming sessions</div>
          {upcoming.length===0 && <p style={{color:'var(--ink-faint)'}}>No sessions scheduled right now — we'll post the next one here.</p>}
          <div style={{display:'grid',gap:12}}>
            {upcoming.map(s=>{
              const soon = s.starts_at && new Date(s.starts_at).getTime()-now < 30*60e3 && new Date(s.starts_at).getTime()-now > -3*3600e3;
              return <div key={s.id} style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:16,flexWrap:'wrap',padding:'16px 18px',border:'1px solid var(--border)',borderRadius:'var(--radius-sm)',background:'var(--navy-950)'}}>
                <div style={{minWidth:0}}>
                  <div style={{fontWeight:600}}>{s.title}</div>
                  <div style={{fontFamily:'var(--font-mono)',fontSize:'.78rem',color:soon?'var(--gold-2)':'var(--ink-faint)',marginTop:4}}>{fmtWhen(s.starts_at)||'Time TBA'}{soon&&' · live now / soon'}</div>
                </div>
                {s.join_url
                  ? <a className="btn btn-primary" style={{width:'auto',padding:'11px 22px',textDecoration:'none'}} href={s.join_url} target="_blank" rel="noopener">Join session ↗</a>
                  : <span style={{fontFamily:'var(--font-mono)',fontSize:'.76rem',color:'var(--ink-faint)'}}>link soon</span>}
              </div>;
            })}
          </div>
        </div>
      </Card>

      <div style={{fontFamily:'var(--font-mono)',fontSize:'.72rem',letterSpacing:'.16em',textTransform:'uppercase',color:'var(--ink-faint)',margin:'4px 0 14px'}}>Session recordings</div>
      {recordings.length===0 && <p style={{color:'var(--ink-faint)',fontSize:'.92rem',marginBottom:8}}>Recordings of past sessions will appear here.</p>}
      <div style={{display:'grid',gap:12}}>
        {recordings.map(s=>(
          <div key={s.id} className="lesson" style={{cursor:'pointer'}} onClick={()=>setOpen(s)}>
            <div className="thumb"><svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg></div>
            <div style={{minWidth:0}}>
              <div style={{fontWeight:600,marginBottom:5}}>{s.title}</div>
              <div style={{fontFamily:'var(--font-mono)',fontSize:'.76rem',color:'var(--ink-faint)'}}>{s.starts_at?new Date(s.starts_at).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'}):'Recording'}{s.duration?' · '+s.duration:''}</div>
            </div>
            <span style={{color:'var(--gold-2)',fontSize:'.84rem',fontFamily:'var(--font-mono)'}}>Watch ↗</span>
          </div>
        ))}
      </div>
      {open && <RecModal s={open} onClose={()=>setOpen(null)} />}
    </Section>;
  }

  // ---------- Free Trial, sessions used up ----------
  if(!vip && verified && cap!=null && used>=cap){
    return <Section><Card style={{textAlign:'center'}}>
      <h2 style={{fontSize:'1.5rem',marginBottom:10}}>You've used your free live sessions</h2>
      <p style={{color:'var(--ink-dim)',maxWidth:520,margin:'0 auto 20px'}}>You joined {used} of {cap} free live session{cap===1?'':'s'} on your Free Trial. Become a VIP member for unlimited live trading, plus the Calculator, Journal, Signals and the Bot.</p>
      <button className="btn btn-primary" style={{width:'auto'}} onClick={()=>{ try{ window.dispatchEvent(new CustomEvent('cg:open-vip-modal')); }catch(e){} }}>Become a VIP member</button>
    </Card></Section>;
  }

  // ---------- Free Trial, broker verification pending ----------
  if(!vip && la && la.broker_account_id && !verified){
    return <Section><Card style={{textAlign:'center'}}>
      <div className="badge" style={{background:'var(--gold-soft)',margin:'0 auto 16px',width:'fit-content'}}><span style={{width:7,height:7,borderRadius:'50%',background:'var(--gold-2)'}}></span>Confirming</div>
      <h2 style={{fontSize:'1.5rem',marginBottom:10}}>We're verifying your broker account</h2>
      <p style={{color:'var(--ink-dim)',maxWidth:520,margin:'0 auto'}}>Your coach is checking your account under our broker. Once confirmed, your free live sessions will unlock here — no action needed from you.</p>
      <p style={{fontFamily:'var(--font-mono)',fontSize:'.8rem',color:'var(--ink-faint)',marginTop:14}}>Account: {la.broker_account_id}</p>
    </Card></Section>;
  }

  // ---------- Free Trial, not yet submitted ----------
  return <Section>
    <Card>
      <div className="grid-bg"></div>
      <div style={{position:'relative'}}>
        <span style={{fontFamily:'var(--font-mono)',fontSize:'.72rem',letterSpacing:'.16em',textTransform:'uppercase',color:'var(--gold)'}}>Free Trial</span>
        <h2 style={{fontSize:'1.85rem',margin:'8px 0'}}>Trade live with a broker account under Chart Growth Hub</h2>
        <p style={{color:'var(--ink-dim)',maxWidth:600,marginBottom:22}}>Free Trial members get a limited number of live trading sessions once we've confirmed you have an account under our broker relationship. Submit your account ID below and your coach will verify it.</p>
        <ul style={{listStyle:'none',padding:0,margin:'0 0 22px',maxWidth:560}}>
          <Bullet>Join live sessions with the coaches, limited number while on Free Trial</Bullet>
          <Bullet>Full recordings of every session to rewatch</Bullet>
          <Bullet>Upgrade to VIP anytime for unlimited live trading</Bullet>
        </ul>
        <BrokerForm client={client} session={session} onDone={load} err={err} setErr={setErr}/>
      </div>
    </Card>
  </Section>;
}

// ---- Free Trial broker-account submission (admin verifies manually, same review pattern as GCash) ----
function BrokerForm({client, session, onDone, err, setErr}){
  const [id,setId]=useState(""); const [busy,setBusy]=useState(false);
  async function submit(e){
    e.preventDefault(); setErr("");
    if(!id.trim()){ setErr("Enter your broker account ID/number."); return; }
    setBusy(true);
    try{
      const { error } = await client.from('live_access').upsert({
        student_id:session.user.id, broker_account_id:id.trim(), broker_verified:false
      },{ onConflict:'student_id' });
      if(error) throw error;
      onDone();
    }catch(e){ setErr(e.message||String(e)); setBusy(false); }
  }
  return <form onSubmit={submit} style={{maxWidth:520}}>
    <div className="field" style={{marginBottom:14}}>
      <label>Your broker account ID (VT Markets, opened under our referral)</label>
      <input value={id} onChange={e=>setId(e.target.value)} placeholder="e.g. VT-123456"/>
    </div>
    {err && <div style={{color:'var(--red)',fontSize:'.84rem',fontFamily:'var(--font-mono)',marginBottom:12}}>{err}</div>}
    <button className="btn btn-primary" style={{width:'auto'}} disabled={busy}>{busy?<><span className="cg-spin"></span> Submitting…</>:'Submit for verification'}</button>
  </form>;
}

function RecModal({s,onClose}){
  const url=recEmbed(s);
  return <div className="modal-back" onClick={onClose}>
    <div className="modal" onClick={e=>e.stopPropagation()}>
      {s.recording_type==='file' && s.recording_url
        ? <video className="v-frame" src={s.recording_url} controls/>
        : url
          ? <iframe className="v-frame" src={url} allow="autoplay; fullscreen; picture-in-picture" allowFullScreen></iframe>
          : <div style={{aspectRatio:'16/9',display:'grid',placeItems:'center',background:'#000'}}>{s.recording_url?<a className="btn btn-primary" style={{width:'auto'}} href={s.recording_url} target="_blank" rel="noopener">Open recording ↗</a>:'No recording'}</div>}
      <div style={{padding:'22px 26px'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:16}}>
          <h2 style={{fontSize:'1.4rem'}}>{s.title}</h2>
          <button className="btn btn-ghost" style={{width:'auto',padding:'9px 16px'}} onClick={onClose}>Close</button>
        </div>
        {s.description && <p style={{color:'var(--ink-dim)',marginTop:10,maxWidth:640}}>{s.description}</p>}
      </div>
    </div>
  </div>;
}

function RoomHead({vip,remaining}){ return <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:16,flexWrap:'wrap'}}>
  <h2 style={{fontSize:'1.5rem'}}>Live Trading Room</h2>
  <span className="badge" style={{background:'var(--gold-soft)'}}><span className="dot"></span>{vip?'VIP · Unlimited':'Free Trial'}</span>
  {!vip && remaining!=null && <span style={{fontFamily:'var(--font-mono)',fontSize:'.76rem',color:'var(--ink-faint)'}}>{remaining} free session{remaining===1?'':'s'} left</span>}
</div>; }

function Section({children}){ return <div style={{marginBottom:40}}>{children}</div>; }

window.LivePanel = LivePanel;
})();
