// confirm-assignment-page.jsx — teacher lands here from the
// "new student assigned" email. One button, calls
// supa.rpc('teacher_confirm_assignment'), shows success → dashboard.
//
// Surface: full-screen, no NavBar/Footer (the deep-link should not be
// distracted by site chrome). If the teacher isn't signed in yet we
// pop the AuthModal so the magic-link email + this confirm link work
// from either entry point.

const CAP_PAGE_BG  = 'oklch(98.5% 0.007 60)';
const CAP_PRIMARY  = 'oklch(22% 0.06 265)';
const CAP_ACCENT   = 'oklch(72% 0.17 80)';
const CAP_MUTED    = 'oklch(55% 0.03 265)';

const ConfirmAssignmentPage = ({ assignmentId, onDone, openAuth }) => {
  const auth = window.useAuth();
  const [status, setStatus]   = React.useState('loading');  // loading|ready|saving|done|err
  const [error,  setError]    = React.useState('');
  const [info,   setInfo]     = React.useState(null);       // { studentName }

  // Look up the teacher's view of this assignment via the existing RPC,
  // which already returns the student's profile row as JSON. The RPC is
  // SECURITY DEFINER and filtered to assignments where the caller is the
  // instructor, so an unrelated id returns nothing — we treat that as
  // "not yours" without leaking existence.
  React.useEffect(() => {
    if (auth.loading) return;
    if (!auth.user) { setStatus('signed-out'); return; }
    let cancelled = false;
    (async () => {
      const { data, error } = await window.supa.rpc('my_instructor_assignments');
      if (cancelled) return;
      if (error) { setError(error.message || 'Could not load assignment.'); setStatus('err'); return; }
      const row = (data || []).find(r => r.id === assignmentId);
      if (!row) { setError('This assignment is not yours, or it no longer exists.'); setStatus('err'); return; }
      setInfo({ studentName: row.student?.full_name || 'this student' });
      setStatus('ready');
    })();
    return () => { cancelled = true; };
  }, [assignmentId, auth.user?.id, auth.loading]);

  const confirm = async () => {
    setStatus('saving');
    const { error } = await window.supa.rpc('teacher_confirm_assignment', { p_assignment_id: assignmentId });
    if (error) { setError(error.message || 'Confirm failed.'); setStatus('err'); return; }
    setStatus('done');
  };

  const Shell = ({ children }) => (
    <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', background: CAP_PAGE_BG, fontFamily:"'Plus Jakarta Sans', sans-serif", padding:24 }}>
      <div style={{ background:'#fff', borderRadius:16, border:'1px solid oklch(91% 0.01 265)', padding:'40px 36px', maxWidth:480, width:'100%', boxShadow:'0 4px 24px oklch(18% 0.06 265 / 0.07)' }}>
        <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:22, fontWeight:700, letterSpacing:'0.14em', color: CAP_PRIMARY, marginBottom:22, textAlign:'center' }}>COACHING</div>
        {children}
      </div>
    </div>
  );

  if (status === 'loading' || auth.loading) {
    return <Shell><div style={{ textAlign:'center', color: CAP_MUTED, fontSize:14 }}>Loading…</div></Shell>;
  }

  if (status === 'signed-out') {
    return (
      <Shell>
        <h2 style={{ fontSize:18, fontWeight:700, color: CAP_PRIMARY, margin:'0 0 10px' }}>Sign in to confirm</h2>
        <p style={{ fontSize:14, color: CAP_MUTED, lineHeight:1.55, marginBottom:18 }}>
          You need to be signed in as the teacher to confirm this student.
        </p>
        <button onClick={() => openAuth('login')} style={{ background: CAP_PRIMARY, color:'#fff', border:'none', borderRadius:10, padding:'12px 22px', fontSize:14, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", width:'100%' }}>
          Sign in
        </button>
      </Shell>
    );
  }

  if (status === 'err') {
    return (
      <Shell>
        <h2 style={{ fontSize:18, fontWeight:700, color:'oklch(40% 0.18 25)', margin:'0 0 10px' }}>Couldn't confirm</h2>
        <p style={{ fontSize:14, color: CAP_MUTED, lineHeight:1.55, marginBottom:18 }}>{error}</p>
        <button onClick={onDone} style={{ background: CAP_PRIMARY, color:'#fff', border:'none', borderRadius:10, padding:'12px 22px', fontSize:14, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", width:'100%' }}>
          Go to dashboard
        </button>
      </Shell>
    );
  }

  if (status === 'done') {
    return (
      <Shell>
        <h2 style={{ fontSize:18, fontWeight:700, color: CAP_PRIMARY, margin:'0 0 10px' }}>Confirmed</h2>
        <p style={{ fontSize:14, color: CAP_MUTED, lineHeight:1.55, marginBottom:18 }}>
          {info?.studentName ? `${info.studentName} is now confirmed as your student.` : 'This student is confirmed.'}
        </p>
        <button onClick={onDone} style={{ background: CAP_PRIMARY, color:'#fff', border:'none', borderRadius:10, padding:'12px 22px', fontSize:14, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", width:'100%' }}>
          Go to dashboard
        </button>
      </Shell>
    );
  }

  // status === 'ready' or 'saving'
  const saving = status === 'saving';
  return (
    <Shell>
      <h2 style={{ fontSize:18, fontWeight:700, color: CAP_PRIMARY, margin:'0 0 10px' }}>New student assigned</h2>
      <p style={{ fontSize:14, color: CAP_MUTED, lineHeight:1.55, marginBottom:22 }}>
        Confirm <strong style={{ color: CAP_PRIMARY }}>{info?.studentName}</strong> as your student so they can book lessons with you.
      </p>
      <button disabled={saving} onClick={confirm} style={{ background: saving ? 'oklch(70% 0.05 265)' : CAP_ACCENT, color: CAP_PRIMARY, border:'none', borderRadius:10, padding:'13px 22px', fontSize:14, fontWeight:700, cursor: saving ? 'wait' : 'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", width:'100%' }}>
        {saving ? 'Confirming…' : `Confirm ${info?.studentName || 'student'} as my student`}
      </button>
      <div style={{ marginTop:12, textAlign:'center' }}>
        <button onClick={onDone} style={{ background:'transparent', border:'none', color: CAP_MUTED, fontSize:12, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", textDecoration:'underline' }}>
          Not now
        </button>
      </div>
    </Shell>
  );
};

window.ConfirmAssignmentPage = ConfirmAssignmentPage;
