// Chart Growth Hub — Student Trading Journal panel (VIP-only).
// Table: journal_entries (student_id, trade_date, pair, direction, entry_price, exit_price, pnl, notes).
// RLS restricts every row to student_id = auth.uid() AND my_vip(), so the panel itself just needs to
// be shown behind the isVIP gate already used elsewhere in the dashboard.
// Exposes window.JournalPanel.
(function(){
const { useState, useEffect, useMemo } = React;

const fmtDate = d => d ? new Date(d+'T00:00:00').toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'}) : '—';
const money = n => (n==null||n==='') ? '—' : (Number(n)>=0?'+':'') + '$' + Number(n).toFixed(2);

function blankForm(){ return { trade_date:new Date().toISOString().slice(0,10), pair:'', direction:'long', entry_price:'', exit_price:'', pnl:'', notes:'' }; }

function JournalPanel({client, session}){
  const [rows,setRows]=useState(null); const [err,setErr]=useState("");
  const [form,setForm]=useState(null); // null = closed, object = add/edit form open
  const [busy,setBusy]=useState(false);

  async function load(){
    const { data, error } = await client.from('journal_entries').select('*').eq('student_id',session.user.id).order('trade_date',{ascending:false}).order('created_at',{ascending:false});
    if(error) setErr(error.message); else setRows(data||[]);
  }
  useEffect(()=>{ load(); /* eslint-disable-next-line */ },[]);

  const stats = useMemo(()=>{
    const r=rows||[]; const withPnl=r.filter(x=>x.pnl!=null && x.pnl!=='');
    const wins=withPnl.filter(x=>Number(x.pnl)>0).length;
    const total=withPnl.reduce((s,x)=>s+Number(x.pnl),0);
    return { count:r.length, winRate: withPnl.length? Math.round(wins/withPnl.length*100):null, total };
  },[rows]);

  function openAdd(){ setForm(blankForm()); }
  function openEdit(r){ setForm({ ...r, entry_price:r.entry_price??'', exit_price:r.exit_price??'', pnl:r.pnl??'' }); }

  async function save(){
    if(!form.pair.trim()){ setErr('Enter the pair/asset.'); return; }
    setErr(""); setBusy(true);
    const payload = {
      student_id: session.user.id, trade_date: form.trade_date, pair: form.pair.trim().toUpperCase(),
      direction: form.direction, entry_price: form.entry_price===''?null:Number(form.entry_price),
      exit_price: form.exit_price===''?null:Number(form.exit_price), pnl: form.pnl===''?null:Number(form.pnl),
      notes: form.notes||null,
    };
    let error;
    if(form.id){ ({ error } = await client.from('journal_entries').update(payload).eq('id',form.id)); }
    else { ({ error } = await client.from('journal_entries').insert(payload)); }
    setBusy(false);
    if(error){ setErr(error.message); return; }
    setForm(null); load();
  }
  async function del(r){
    if(!confirm('Delete this journal entry?')) return;
    setRows(rs=>rs.filter(x=>x.id!==r.id));
    const { error } = await client.from('journal_entries').delete().eq('id',r.id);
    if(error){ setErr(error.message); load(); }
  }

  if(!rows) return <div style={{padding:40,textAlign:'center'}}><span className="cg-spin"></span></div>;

  return <div>
    <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:16,flexWrap:'wrap',marginBottom:18}}>
      <div>
        <h2 style={{fontSize:'1.4rem',margin:'0 0 4px'}}>Trading Journal</h2>
        <p style={{color:'var(--ink-dim)',fontSize:'.88rem',margin:0}}>Log every trade and track your progress over time. Only you can see this.</p>
      </div>
      <button className="btn btn-primary" style={{width:'auto'}} onClick={openAdd}>+ Log a trade</button>
    </div>

    <div className="stat4" style={{gridTemplateColumns:'repeat(3,1fr)',marginBottom:20}}>
      {[['Entries',stats.count],['Win rate',stats.winRate==null?'—':stats.winRate+'%'],['Total P&L',money(stats.total)]].map(([l,n])=>(
        <div key={l} style={{background:'linear-gradient(165deg,var(--surface-2),var(--surface))',border:'1px solid var(--border)',borderRadius:'var(--radius)',padding:'16px 18px'}}>
          <div style={{fontFamily:'var(--font-mono)',fontSize:'1.4rem',fontWeight:600,color:'var(--gold-2)'}}>{n}</div>
          <div style={{fontSize:'.78rem',color:'var(--ink-dim)'}}>{l}</div>
        </div>))}
    </div>

    {err && <div style={{color:'var(--red)',fontSize:'.84rem',fontFamily:'var(--font-mono)',marginBottom:14}}>{err}</div>}

    {form && <div style={{padding:'20px',border:'1px solid var(--border-gold)',borderRadius:'var(--radius-sm)',background:'var(--navy-950)',marginBottom:18}}>
      <div className="form-2" style={{marginBottom:13}}>
        <div className="field"><label>Date</label><input type="date" value={form.trade_date} onChange={e=>setForm(f=>({...f,trade_date:e.target.value}))}/></div>
        <div className="field"><label>Pair / asset</label><input value={form.pair} onChange={e=>setForm(f=>({...f,pair:e.target.value}))} placeholder="XAU/USD"/></div>
      </div>
      <div className="form-3" style={{marginBottom:13}}>
        <div className="field"><label>Direction</label><select value={form.direction} onChange={e=>setForm(f=>({...f,direction:e.target.value}))}><option value="long">Long</option><option value="short">Short</option></select></div>
        <div className="field"><label>Entry price</label><input type="number" step="any" value={form.entry_price} onChange={e=>setForm(f=>({...f,entry_price:e.target.value}))}/></div>
        <div className="field"><label>Exit price</label><input type="number" step="any" value={form.exit_price} onChange={e=>setForm(f=>({...f,exit_price:e.target.value}))}/></div>
      </div>
      <div className="field" style={{marginBottom:13}}><label>P&amp;L ($)</label><input type="number" step="any" value={form.pnl} onChange={e=>setForm(f=>({...f,pnl:e.target.value}))} placeholder="e.g. 120 or -45"/></div>
      <div className="field" style={{marginBottom:16}}><label>Notes</label><input value={form.notes||''} onChange={e=>setForm(f=>({...f,notes:e.target.value}))} placeholder="Setup, reasoning, lesson learned…"/></div>
      <div style={{display:'flex',gap:10}}>
        <button className="btn btn-primary" style={{width:'auto'}} disabled={busy} onClick={save}>{busy?<><span className="cg-spin"></span> Saving…</>:(form.id?'Save changes':'Add entry')}</button>
        <button className="btn btn-ghost" style={{width:'auto'}} onClick={()=>setForm(null)}>Cancel</button>
      </div>
    </div>}

    {rows.length===0 && !form && <div style={{padding:'40px 20px',textAlign:'center',color:'var(--ink-faint)',border:'1px dashed var(--border)',borderRadius:'var(--radius)'}}>No entries yet. Click <strong>+ Log a trade</strong> to start your journal.</div>}

    <div style={{display:'grid',gap:10}}>
      {rows.map(r=>(
        <div key={r.id} style={{padding:'14px 16px',border:'1px solid var(--border)',borderRadius:'var(--radius-sm)',background:'linear-gradient(165deg,var(--surface-2),var(--surface))',display:'flex',justifyContent:'space-between',gap:14,flexWrap:'wrap',alignItems:'center'}}>
          <div style={{minWidth:0}}>
            <div style={{display:'flex',gap:8,alignItems:'center',flexWrap:'wrap',marginBottom:4}}>
              <span style={{fontWeight:600}}>{r.pair}</span>
              <span style={{fontFamily:'var(--font-mono)',fontSize:'.66rem',textTransform:'uppercase',padding:'2px 8px',borderRadius:999,border:'1px solid var(--border)',color:r.direction==='long'?'var(--green)':'var(--red)'}}>{r.direction}</span>
              <span style={{fontFamily:'var(--font-mono)',fontSize:'.74rem',color:'var(--ink-faint)'}}>{fmtDate(r.trade_date)}</span>
            </div>
            {r.notes && <div style={{color:'var(--ink-dim)',fontSize:'.86rem',maxWidth:520}}>{r.notes}</div>}
            {(r.entry_price!=null||r.exit_price!=null) && <div style={{fontFamily:'var(--font-mono)',fontSize:'.74rem',color:'var(--ink-faint)',marginTop:4}}>{r.entry_price!=null?'entry '+r.entry_price:''}{r.entry_price!=null&&r.exit_price!=null?' → ':''}{r.exit_price!=null?'exit '+r.exit_price:''}</div>}
          </div>
          <div style={{display:'flex',alignItems:'center',gap:14}}>
            <span style={{fontFamily:'var(--font-mono)',fontWeight:600,color:r.pnl>0?'var(--green)':r.pnl<0?'var(--red)':'var(--ink-faint)'}}>{money(r.pnl)}</span>
            <div style={{display:'flex',gap:6}}>
              <button onClick={()=>openEdit(r)} style={{cursor:'pointer',padding:'5px 9px',borderRadius:7,border:'1px solid var(--border)',background:'var(--surface)',color:'var(--ink-dim)',fontSize:'.74rem'}}>Edit</button>
              <button onClick={()=>del(r)} style={{cursor:'pointer',padding:'5px 9px',borderRadius:7,border:'1px solid rgba(248,113,113,.3)',background:'rgba(248,113,113,.1)',color:'var(--red)',fontSize:'.74rem'}}>Del</button>
            </div>
          </div>
        </div>
      ))}
    </div>
  </div>;
}

window.JournalPanel = JournalPanel;
})();
