// Student · Quizzes & Assignments section (window.AssessmentsPanel)
// Renders nothing unless published assessments exist. Expects React globals + Supabase `client` + `session`.
(function(){
const { useState, useEffect } = React;
const cap = s => s? s.charAt(0).toUpperCase()+s.slice(1) : s;

function QuizModal({a, attempt, session, client, onClose, onGraded}){
  const qs = Array.isArray(a.questions)? a.questions : [];
  const [ans,setAns]=useState(()=> qs.map(()=>-1));
  const [busy,setBusy]=useState(false); const [err,setErr]=useState('');
  const [result,setResult]=useState(attempt&&attempt.score!=null? {score:attempt.score, passed:attempt.passed, pass_mark:a.pass_mark} : null);
  async function submit(){ if(ans.some(x=>x<0)){ setErr('Please answer every question.'); return; } setErr(''); setBusy(true);
    try{ const { data, error }=await client.rpc('grade_quiz',{ a_id:a.id, ans }); if(error) throw error;
      setResult(data); onGraded(a.id, data); if(window.cgLog) window.cgLog(client, data.passed?'quiz_passed':'quiz_attempt', a.title, {score:data.score}); }
    catch(ex){ setErr(ex.message||'Could not submit'); } finally{ setBusy(false); } }
  return <div className="modal-back" onClick={onClose}>
    <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:640}}>
      <div style={{padding:'28px 30px'}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:16,marginBottom:6}}>
          <div><span className="eyebrow" style={{color:'var(--gold-2)'}}>Quiz</span><h2 style={{fontSize:'1.45rem',marginTop:10}}>{a.title}</h2></div>
          <button className="btn btn-ghost" style={{width:'auto',padding:'9px 16px'}} onClick={onClose}>Close</button>
        </div>
        {a.description && <p style={{color:'var(--ink-dim)',marginBottom:18}}>{a.description}</p>}

        {result
          ? <div style={{textAlign:'center',padding:'24px 10px'}}>
              <div style={{fontFamily:'var(--font-mono)',fontSize:'3rem',fontWeight:600,color:result.passed?'var(--green)':'var(--red)'}}>{result.score}%</div>
              <div style={{fontSize:'1.1rem',fontWeight:600,marginTop:6,color:result.passed?'var(--green)':'var(--red)'}}>{result.passed?'✓ Passed':'Not passed yet'}</div>
              <div style={{color:'var(--ink-faint)',fontFamily:'var(--font-mono)',fontSize:'.82rem',marginTop:6}}>Pass mark {result.pass_mark||a.pass_mark}%</div>
              <div style={{display:'flex',gap:10,justifyContent:'center',marginTop:22,flexWrap:'wrap'}}>
                <button className="btn btn-ghost" style={{width:'auto'}} onClick={()=>{ setResult(null); setAns(qs.map(()=>-1)); }}>Retake</button>
                <button className="btn btn-primary" style={{width:'auto'}} onClick={onClose}>Done</button>
              </div>
            </div>
          : <div style={{display:'grid',gap:18}}>
              {qs.map((q,i)=>(<div key={i}>
                <div style={{fontWeight:600,marginBottom:10}}><span style={{color:'var(--gold-2)',fontFamily:'var(--font-mono)',marginRight:8}}>{i+1}.</span>{q.text}</div>
                <div style={{display:'grid',gap:8}}>
                  {(q.options||[]).map((o,j)=>(<label key={j} style={{display:'flex',alignItems:'center',gap:10,padding:'11px 14px',borderRadius:10,border:'1px solid '+(ans[i]===j?'var(--border-gold)':'var(--border)'),background:ans[i]===j?'var(--gold-soft)':'var(--surface)',cursor:'pointer'}}>
                    <input type="radio" name={'q'+i} checked={ans[i]===j} onChange={()=>setAns(a2=>a2.map((x,k)=>k===i?j:x))}/>
                    <span>{o}</span>
                  </label>))}
                </div>
              </div>))}
              {err && <div style={{color:'var(--red)',fontSize:'.85rem',fontFamily:'var(--font-mono)'}}>{err}</div>}
              <button className="btn btn-primary" style={{width:'auto'}} disabled={busy} onClick={submit}>{busy?'Submitting…':'Submit quiz'}</button>
            </div>}
      </div>
    </div>
  </div>;
}

function AssessmentsPanel({client, session}){
  const [items,setItems]=useState([]); const [attempts,setAttempts]=useState({}); const [openQuiz,setOpenQuiz]=useState(null);
  async function load(){
    const { data } = await client.from('assessment_public').select('*').order('sort_order');
    setItems(data||[]);
    const { data:at } = await client.from('assessment_attempts').select('*').eq('student_id',session.user.id);
    const m={}; (at||[]).forEach(r=> m[r.assessment_id]=r); setAttempts(m);
  }
  useEffect(()=>{ load(); },[]);
  function onGraded(id, res){ setAttempts(m=>({...m,[id]:{...(m[id]||{}),assessment_id:id,student_id:session.user.id,score:res.score,passed:res.passed,completed:res.passed}})); }
  async function markDone(a){ const cur=attempts[a.id]; const next=!(cur&&cur.completed);
    setAttempts(m=>({...m,[a.id]:{...(m[a.id]||{}),assessment_id:a.id,student_id:session.user.id,completed:next}}));
    await client.from('assessment_attempts').upsert({assessment_id:a.id, student_id:session.user.id, completed:next, updated_at:new Date().toISOString()}, {onConflict:'assessment_id,student_id'}); }

  if(!items.length) return null;
  return <div style={{marginBottom:38}}>
    <h2 style={{fontSize:'1.4rem',marginBottom:4}}>Quizzes &amp; Assignments</h2>
    <p style={{color:'var(--ink-dim)',fontSize:'.9rem',marginBottom:16}}>Test what you've learned. Quizzes are graded instantly.</p>
    <div style={{display:'grid',gap:12}}>
      {items.map(a=>{ const at=attempts[a.id]; const quiz=a.kind==='quiz';
        const done = at && at.completed; const score = at && at.score!=null ? at.score : null;
        return <div key={a.id} style={{border:'1px solid '+(done?'var(--border-gold)':'var(--border)'),borderRadius:'var(--radius-sm)',padding:'16px 18px',background:'var(--surface)',display:'flex',alignItems:'center',gap:16,flexWrap:'wrap'}}>
          <span style={{fontFamily:'var(--font-mono)',fontSize:'.64rem',letterSpacing:'.1em',textTransform:'uppercase',padding:'4px 10px',borderRadius:999,border:'1px solid var(--border-gold)',color:'var(--gold-2)',background:'var(--gold-soft)',flexShrink:0}}>{a.kind}</span>
          <div style={{flex:1,minWidth:200}}>
            <div style={{fontWeight:600}}>{a.title}</div>
            {a.description && <div style={{color:'var(--ink-dim)',fontSize:'.86rem',marginTop:4,display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical',overflow:'hidden'}}>{a.description}</div>}
            <div style={{fontFamily:'var(--font-mono)',fontSize:'.74rem',color:'var(--ink-faint)',marginTop:6}}>
              {quiz
                ? (score!=null ? <span style={{color:at.passed?'var(--green)':'var(--gold-2)'}}>{at.passed?'✓ Passed':'Scored'} {score}% · pass {a.pass_mark}%</span> : (a.questions||[]).length+' question(s) · pass '+a.pass_mark+'%')
                : (done ? <span style={{color:'var(--green)'}}>✓ Marked done</span> : 'Assignment')}
            </div>
          </div>
          <div style={{display:'flex',gap:8,alignItems:'center',flexShrink:0,flexWrap:'wrap'}}>
            {quiz
              ? <button className="btn btn-primary" style={{width:'auto'}} onClick={()=>setOpenQuiz(a)}>{score!=null?'Retake':'Start quiz'}</button>
              : <React.Fragment>
                  {a.file_url && <a className="btn btn-ghost" style={{width:'auto',textDecoration:'none'}} href={a.file_url} target="_blank" rel="noopener">↓ {a.file_name||'File'}</a>}
                  {a.link_url && <a className="btn btn-ghost" style={{width:'auto',textDecoration:'none'}} href={a.link_url} target="_blank" rel="noopener">Open link ↗</a>}
                  <button className={"btn "+(done?'btn-ghost':'btn-primary')} style={{width:'auto'}} onClick={()=>markDone(a)}>{done?'✓ Done':'Mark as done'}</button>
                </React.Fragment>}
          </div>
        </div>;
      })}
    </div>
    {openQuiz && <QuizModal a={openQuiz} attempt={attempts[openQuiz.id]} session={session} client={client} onClose={()=>setOpenQuiz(null)} onGraded={onGraded} />}
  </div>;
}
window.AssessmentsPanel = AssessmentsPanel;
})();
