// src/features/instructor/ui/instructor-dashboard-modals-2.jsx
//
// Second half of instructor-dashboard-modals.jsx. Split to keep both
// files under the 400-LOC budget.
//
// Contains: LessonDetailPopup (booking row click), the miniBtn helper
// it uses, and TeacherStudentRow (collapsible per-student notes panel).
//
// Public: window.{LessonDetailPopup, TeacherStudentRow}.

// ── LessonDetailPopup ───────────────────────────────────────────────
// Joe spec (2026-05-21): after a lesson, the teacher writes notes
// (required, >=1 char) and presses either Save (lesson happened) or
// Mark as absent (student no-showed). Both gate on the same >=1 char
// rule; both close the popup with a toast. No mark-paid, no separate
// mark-complete, no cancel button in this surface. Cancel belongs to
// admin; payment status belongs to admin's payment view.
// v47 added bookings.no_show + a p_no_show arg on instructor_save_notes
// — the absent button wires through that.
const LessonDetailPopup = ({ booking, onApproveReschedule, onDeclineReschedule, onSaveNotes, onClose }) => {
  const date = new Date(booking.scheduledAt);
  const isTrial = /trial/i.test(booking.message || '');
  const reschedule = booking.rescheduleRequestedAt ? new Date(booking.rescheduleRequestedAt) : null;
  const [notesDraft, setNotesDraft] = React.useState(booking.teacherNotes || '');
  const [notesBusy, setNotesBusy] = React.useState(false);
  const [notesStatus, setNotesStatus] = React.useState('');
  React.useEffect(() => { setNotesDraft(booking.teacherNotes || ''); }, [booking.id]);

  // Notes required >=1 char to save. Stops empty-save mistakes.
  const notesTrimmed = (notesDraft || '').trim();
  const canSave = notesTrimmed.length >= 1;

  const handleSave = async () => {
    if (notesBusy || !canSave) return;
    setNotesBusy(true); setNotesStatus('');
    try {
      // Save notes + mark complete in one call (Joe: 'Save' means both).
      await onSaveNotes(booking.id, notesDraft, true);
      setNotesStatus('Saved');
      setTimeout(() => { setNotesStatus(''); if (onClose) onClose(); }, 900);
    } catch (e) { setNotesStatus('Error: ' + (e.message || 'could not save')); }
    finally { setNotesBusy(false); }
  };

  const handleMarkAbsent = async () => {
    if (notesBusy || !canSave) return;
    setNotesBusy(true); setNotesStatus('');
    try {
      // 4th arg = no_show. RPC sets no_show=true AND status='completed'
      // in the same UPDATE (v47).
      await onSaveNotes(booking.id, notesDraft, true, true);
      setNotesStatus('Marked absent');
      setTimeout(() => { setNotesStatus(''); if (onClose) onClose(); }, 900);
    } catch (e) { setNotesStatus('Error: ' + (e.message || 'could not save')); }
    finally { setNotesBusy(false); }
  };
  // Pull this student's online flag + meeting link so the teacher can join
  // the same Zoom/Meet the student uses. RLS policy
  // student_info_instructor_read (v16) lets the teacher read this row
  // without an extra RPC. Fetched lazily on popup open.
  const [studentInfo, setStudentInfo] = React.useState(null);
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      if (!booking?.studentId) return;
      const { data } = await window.supa.from('student_info')
        .select('is_online, meeting_link').eq('user_id', booking.studentId).maybeSingle();
      if (!cancelled && data) setStudentInfo(data);
    })();
    return () => { cancelled = true; };
  }, [booking?.studentId]);
  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.32)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:8000, padding:12 }} onClick={onClose}>
      <div style={{ background:'#fff', borderRadius:14, padding:'22px 22px 20px', width:'min(380px, 100%)', maxHeight:'90vh', overflowY:'auto', boxShadow:'0 20px 60px rgba(0,0,0,0.22)', fontFamily:"'Plus Jakarta Sans', sans-serif", boxSizing:'border-box' }} onClick={e => e.stopPropagation()}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:10, marginBottom:14 }}>
          <div style={{ minWidth:0, flex:1 }}>
            <div style={{ fontFamily:"'Cormorant Garamond', serif", fontWeight:700, fontSize:22, color:'oklch(18% 0.03 265)', lineHeight:1.15, wordBreak:'break-word' }}>{booking.student?.name || 'Unknown student'}</div>
            <div style={{ fontSize:12.5, color:'oklch(54% 0.03 265)', marginTop:4, lineHeight:1.5 }}>{niceDateStr(date)} · {instH(date.getHours())} · {booking.durationMinutes} min</div>
          </div>
          {!reschedule && (
            <span style={{ fontSize:10, fontWeight:700, padding:'4px 10px', borderRadius:20, textTransform:'uppercase', letterSpacing:'0.06em', background: isTrial ? 'oklch(95% 0.13 80)' : 'oklch(92% 0.08 265)', color: isTrial ? 'oklch(36% 0.14 75)' : 'oklch(28% 0.1 265)', whiteSpace:'nowrap', flexShrink:0 }}>
              {isTrial ? 'Trial' : 'Lesson'}
            </span>
          )}
        </div>
        {!reschedule && studentInfo?.is_online && studentInfo?.meeting_link && (
          <div style={{ background:'oklch(96% 0.04 265)', borderRadius:8, padding:'10px 12px', margin:'10px 0', borderLeft:'3px solid oklch(60% 0.18 265)' }}>
            <div style={{ fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.07em', color:'oklch(40% 0.12 265)', marginBottom:4 }}>💻 Online lesson</div>
            <a href={studentInfo.meeting_link} target="_blank" rel="noopener noreferrer" style={{ fontSize:12, fontWeight:600, color:'oklch(28% 0.13 265)', wordBreak:'break-all', textDecoration:'underline' }}>{studentInfo.meeting_link}</a>
          </div>
        )}
        {!reschedule && booking.message && <div style={{ fontSize:12, color:'oklch(52% 0.03 265)', lineHeight:1.55, margin:'10px 0' }}>{booking.message}</div>}

        {reschedule && (
          <div style={{ background:'oklch(96.5% 0.07 80)', borderRadius:10, padding:'14px 16px', margin:'4px 0 0', borderLeft:'3px solid oklch(70% 0.14 80)' }}>
            <div style={{ fontSize:11, fontWeight:700, color:'oklch(36% 0.13 75)', letterSpacing:'0.05em', textTransform:'uppercase', marginBottom:10 }}>🔄 Reschedule requested</div>
            <div style={{ fontSize:13, color:'oklch(28% 0.08 75)', lineHeight:1.7, marginBottom:14 }}>
              <div>From: <strong>{niceDateStr(date)} · {instH(date.getHours())}</strong></div>
              <div>To: <strong>{niceDateStr(reschedule)} · {instH(reschedule.getHours())}</strong></div>
            </div>
            <div style={{ display:'flex', gap:8 }}>
              <button onClick={onApproveReschedule} style={{ flex:1, background:'oklch(32% 0.14 150)', color:'#fff', border:'none', borderRadius:8, padding:'10px 0', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Approve</button>
              <button onClick={onDeclineReschedule} style={{ flex:1, background:'#fff', color:'oklch(40% 0.1 25)', border:'1px solid oklch(88% 0.08 25)', borderRadius:8, padding:'10px 0', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Decline</button>
            </div>
          </div>
        )}

        {/* v72 session rating — 1-5 stars, admin-only. Sits above the
            notes block so the teacher reads "How was the session?" before
            picking up the keyboard. Saves on click via Bookings.db. */}
        {!reschedule && window.TeacherSessionRatingControl && (
          <window.TeacherSessionRatingControl booking={booking} />
        )}

        {/* Teacher session notes — REQUIRED, single Save button.
            Saving also marks the lesson complete. Notes are admin-visible,
            never student-visible. Hidden while a reschedule is pending. */}
        {!reschedule && (
        <div style={{ marginTop:14, paddingTop:12, borderTop:'1px solid oklch(94% 0.005 60)' }}>
          <div style={{ fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.07em', color:'oklch(52% 0.04 265)', marginBottom:6 }}>
            Session notes <span style={{ fontWeight:500, color:'oklch(60% 0.03 25)', textTransform:'none', letterSpacing:0 }}>· required to save</span>
          </div>
          <textarea value={notesDraft} onChange={e=>setNotesDraft(e.target.value)}
            placeholder="What did you cover? Homework? How is the student progressing?"
            rows={5} autoFocus
            style={{ width:'100%', padding:'12px 14px', borderRadius:9, border:'1.5px solid ' + (canSave ? 'oklch(88% 0.015 265)' : 'oklch(82% 0.06 25)'), fontSize:14, lineHeight:1.5, fontFamily:"'Plus Jakarta Sans', sans-serif", color:'oklch(22% 0.06 265)', background:'#fff', resize:'vertical', boxSizing:'border-box', minHeight:108, outline:'none' }} />
          {booking.teacherNotesAt && (
            <div style={{ fontSize:10, color:'oklch(60% 0.03 265)', marginTop:4 }}>
              Last saved: {new Date(booking.teacherNotesAt).toLocaleString()}
            </div>
          )}
          {notesStatus && (
            <div style={{ fontSize:11, color: notesStatus.startsWith('Error') ? 'oklch(40% 0.15 25)' : 'oklch(30% 0.13 150)', marginTop:5, fontWeight:600 }}>{notesStatus}</div>
          )}
          <div style={{ display:'flex', gap:8, marginTop:12, flexWrap:'wrap' }}>
            <button disabled={notesBusy || !canSave} onClick={handleSave}
              title={canSave ? 'Saves notes and marks the lesson complete.' : 'Write at least one character of notes to enable.'}
              style={{ flex:'1 1 140px', background: canSave ? 'oklch(32% 0.14 150)' : 'oklch(85% 0.02 265)', color: canSave ? '#fff' : 'oklch(50% 0.04 265)', border:'none', borderRadius:9, padding:'12px 0', fontSize:14, fontWeight:700, cursor: (!canSave || notesBusy) ? 'not-allowed' : 'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity: notesBusy ? 0.7 : 1, minHeight:44 }}>
              {notesBusy ? 'Saving…' : 'Save notes'}
            </button>
            <button disabled={notesBusy || !canSave} onClick={handleMarkAbsent}
              title={canSave ? 'Records the lesson as a no-show (notes still save).' : 'Write at least one character of notes to enable.'}
              style={{ flex:'1 1 140px', background: canSave ? 'oklch(96% 0.08 80)' : 'oklch(95% 0.01 265)', color: canSave ? 'oklch(36% 0.14 75)' : 'oklch(50% 0.04 265)', border:'1px solid ' + (canSave ? 'oklch(82% 0.12 80)' : 'oklch(90% 0.01 265)'), borderRadius:9, padding:'12px 0', fontSize:14, fontWeight:600, cursor: (!canSave || notesBusy) ? 'not-allowed' : 'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity: notesBusy ? 0.7 : 1, minHeight:44 }}>
              Mark as absent
            </button>
            <button onClick={onClose}
              style={{ flex:'1 1 100%', background:'transparent', color:'oklch(54% 0.03 265)', border:'none', borderRadius:9, padding:'8px 0 0', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
              Close
            </button>
          </div>
        </div>
        )}

        {reschedule && (
          <div style={{ marginTop:12 }}>
            <button onClick={onClose} style={{ ...miniBtn('ghost'), width:'100%' }}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
};
const miniBtn = (kind) => {
  const map = {
    primary: { background:'oklch(22% 0.06 265)', color:'#fff' },
    paid:    { background:'oklch(94% 0.1 150)',  color:'oklch(28% 0.13 150)' },
    danger:  { background:'oklch(96% 0.05 25)',  color:'oklch(36% 0.1 25)' },
    ghost:   { background:'oklch(95% 0.01 265)', color:'oklch(44% 0.04 265)' },
  };
  return { ...map[kind], border:'none', borderRadius:8, padding:'9px 0', fontSize:11, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" };
};

// ── TeacherStudentRow ───────────────────────────────────────────────
const TeacherStudentRow = ({ name, nextLesson, notes, adminNote }) => {
  const [open, setOpen] = React.useState(false);
  const nextLabel = nextLesson
    ? `${niceDateStr(new Date(nextLesson.scheduledAt))} · ${instH(new Date(nextLesson.scheduledAt).getHours())}`
    : 'No upcoming lessons';
  const initial = (name || '?').trim().charAt(0).toUpperCase();
  const adminNoteTrimmed = (adminNote || '').trim();
  const hasAdminNote = adminNoteTrimmed.length > 0;
  return (
    <div style={{ background:'#fff', borderRadius:12, border:'1px solid oklch(92% 0.01 265)', overflow:'hidden', transition:'border-color 0.12s, box-shadow 0.12s' }}>
      <button onClick={() => setOpen(o => !o)}
        onMouseEnter={e => { if (!open) e.currentTarget.parentElement.style.borderColor = 'oklch(82% 0.03 265)'; }}
        onMouseLeave={e => { if (!open) e.currentTarget.parentElement.style.borderColor = 'oklch(92% 0.01 265)'; }}
        style={{ width:'100%', textAlign:'left', display:'flex', alignItems:'center', gap:12, padding:'14px 16px', background:'#fff', border:'none', cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", minHeight:60 }}>
        <div style={{ width:36, height:36, borderRadius:'50%', background:'oklch(94% 0.03 265)', color:'oklch(28% 0.06 265)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, fontWeight:700, flexShrink:0 }}>{initial}</div>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:14.5, fontWeight:700, color:'oklch(22% 0.06 265)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{name}</div>
          <div style={{ fontSize:12, color:'oklch(58% 0.03 265)', marginTop:3, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>Next: {nextLabel}</div>
        </div>
        {hasAdminNote && (
          <span title="Note from admin about this student" style={{ background:'oklch(96% 0.06 80)', color:'oklch(36% 0.14 75)', border:'1px solid oklch(86% 0.1 80)', borderRadius:5, padding:'2px 7px', fontSize:10, fontWeight:700, flexShrink:0, marginRight:6 }}>Note</span>
        )}
        <span style={{ fontSize:11, color:'oklch(60% 0.03 265)', transform: open ? 'rotate(90deg)' : 'rotate(0deg)', transition:'transform 0.15s', display:'inline-block', flexShrink:0 }}>▶</span>
      </button>
      {open && (
        <div style={{ padding:'4px 16px 16px', borderTop:'1px solid oklch(95% 0.005 60)' }}>
          {hasAdminNote && (
            <div style={{ background:'oklch(98% 0.04 80)', border:'1px solid oklch(90% 0.07 80)', borderLeft:'3px solid oklch(72% 0.17 80)', borderRadius:6, padding:'10px 12px', marginTop:14 }}>
              <div style={{ fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.07em', color:'oklch(36% 0.14 75)', marginBottom:6 }}>
                From admin
              </div>
              <div style={{ fontSize:13, color:'oklch(28% 0.05 265)', whiteSpace:'pre-wrap', lineHeight:1.5 }}>{adminNoteTrimmed}</div>
            </div>
          )}
          <div style={{ fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.07em', color:'oklch(58% 0.03 265)', margin:'14px 0 8px' }}>
            Session notes ({notes.length})
          </div>
          {notes.length === 0 ? (
            <div style={{ fontSize:12, color:'oklch(64% 0.03 265)', fontStyle:'italic' }}>
              No notes yet. Open any past lesson to add one.
            </div>
          ) : (
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {notes.slice(0, 12).map(n => (
                <div key={n.id} style={{ background:'oklch(98% 0.005 60)', borderLeft:'2px solid oklch(72% 0.17 80)', borderRadius:6, padding:'7px 10px' }}>
                  <div style={{ fontSize:11, color:'oklch(56% 0.03 265)', marginBottom:3, fontWeight:600 }}>
                    {new Date(n.scheduledAt).toLocaleDateString(undefined, { month:'short', day:'numeric', year:'numeric' })}
                  </div>
                  <div style={{ fontSize:12, color:'oklch(28% 0.05 265)', whiteSpace:'pre-wrap', lineHeight:1.5 }}>{n.teacherNotes}</div>
                </div>
              ))}
              {notes.length > 12 && <div style={{ fontSize:11, color:'oklch(60% 0.03 265)', textAlign:'center', padding:6 }}>… {notes.length - 12} earlier notes</div>}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { LessonDetailPopup, TeacherStudentRow });
