// admin-schedule-detail.jsx — right-side drawer for a single class.
//
// The Schedule list rows are intentionally minimal (just "student with
// teacher"). Everything else — the exact time, duration, status
// (confirmed / no-show / cancelled), whether it recurs, plus the
// actions (series, delete, transcript, approve/decline a reschedule) —
// lives here and opens when a row is clicked.
//
// Presentational only: it receives the booking + resolved names +
// callbacks from admin-schedule.jsx and never touches the DB itself.
// Loads BEFORE admin-schedule.jsx (which references
// window.AdminScheduleDetailDrawer); see index.html.

const AdminScheduleDetailDrawer = ({
  booking, studentName, teacherName, liveEl, busy,
  onClose, onReschedule, onSeries, onDelete, onTranscript, onApproveResched, onDeclineResched,
}) => {
  // Slide-in on mount; slide-out before the parent unmounts us.
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setShown(true), 10);
    return () => clearTimeout(t);
  }, []);
  if (!booking) return null;
  const b = booking;

  const handleClose = () => { setShown(false); setTimeout(onClose, 200); };

  const at = new Date(b.scheduledAt);
  const dateStr = at.toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric' });
  const timeStr = at.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
  const tz = window.adminSchTzAbbrev(at);

  const rd = b.rescheduleRequestedAt ? new Date(b.rescheduleRequestedAt) : null;
  const rdStr = rd
    ? `${rd.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })} · ${rd.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })} ${window.adminSchTzAbbrev(rd)}`
    : '';

  // Status badge — the one fact Joe asked for explicitly: no-show vs
  // confirmed (cancelled/completed surfaced too so the drawer never lies).
  const badge =
    b.status === 'cancelled' ? { t: 'Cancelled', bg: 'oklch(95% 0.02 25)',  fg: 'oklch(44% 0.16 25)',  bd: 'oklch(88% 0.06 25)'  }
    : b.noShow               ? { t: 'No-show',   bg: 'oklch(96% 0.05 55)',  fg: 'oklch(42% 0.15 55)',  bd: 'oklch(88% 0.09 55)'  }
    : b.status === 'completed' ? { t: 'Completed', bg: 'oklch(95% 0.06 150)', fg: 'oklch(34% 0.13 150)', bd: 'oklch(86% 0.09 150)' }
    :                          { t: 'Confirmed', bg: 'oklch(96% 0.03 265)', fg: 'oklch(34% 0.08 265)', bd: 'oklch(88% 0.04 265)' };

  const factRow = (label, value) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '13px 0', borderBottom: '1px solid oklch(95% 0.005 60)' }}>
      <span style={{ fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'oklch(56% 0.03 265)' }}>{label}</span>
      <span style={{ fontSize: 14, fontWeight: 600, color: 'oklch(24% 0.06 265)', textAlign: 'right' }}>{value}</span>
    </div>
  );

  const actionBtn = (label, onClick, kind) => {
    const styles = {
      primary: { bg: 'oklch(22% 0.06 265)', fg: '#fff',               bd: 'oklch(22% 0.06 265)' },
      neutral: { bg: 'oklch(96% 0.04 265)', fg: 'oklch(30% 0.13 265)', bd: 'oklch(86% 0.05 265)' },
      series:  { bg: 'oklch(96% 0.05 75)',  fg: 'oklch(36% 0.13 75)',  bd: 'oklch(86% 0.09 75)' },
      danger:  { bg: '#fff',                fg: 'oklch(40% 0.16 25)',  bd: 'oklch(86% 0.12 25)' },
    }[kind] || { bg: 'oklch(96% 0.04 265)', fg: 'oklch(30% 0.13 265)', bd: 'oklch(86% 0.05 265)' };
    return (
      <button disabled={busy} onClick={onClick}
        style={{ width: '100%', textAlign: 'left', background: styles.bg, color: styles.fg, border: `1px solid ${styles.bd}`,
          borderRadius: 9, padding: '12px 14px', fontSize: 13.5, fontWeight: 700, cursor: busy ? 'wait' : 'pointer',
          fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
        {label}
      </button>
    );
  };

  return (
    <div onClick={handleClose}
      style={{ position: 'fixed', inset: 0, background: 'rgba(15,18,40,0.35)', zIndex: 1000, display: 'flex', justifyContent: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()}
        style={{ width: 'min(400px, 92vw)', height: '100%', background: 'oklch(99% 0.004 60)',
          boxShadow: '-8px 0 40px rgba(0,0,0,0.18)', transform: shown ? 'translateX(0)' : 'translateX(100%)',
          transition: 'transform 0.22s cubic-bezier(0.4,0,0.2,1)', overflowY: 'auto',
          fontFamily: "'Plus Jakarta Sans', sans-serif", display: 'flex', flexDirection: 'column' }}>

        {/* Header */}
        <div style={{ padding: '18px 20px 16px', borderBottom: '1px solid oklch(92% 0.01 265)', position: 'sticky', top: 0, background: 'oklch(99% 0.004 60)', zIndex: 1 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'oklch(58% 0.03 265)', marginBottom: 6 }}>Class details</div>
              <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 23, fontWeight: 700, color: 'oklch(20% 0.06 265)', lineHeight: 1.15 }}>
                {studentName} <span style={{ color: 'oklch(60% 0.03 265)', fontWeight: 500, fontFamily: "'Plus Jakarta Sans', sans-serif", fontSize: 16 }}>with</span> {teacherName}
              </div>
            </div>
            <button onClick={handleClose} aria-label="Close" title="Close"
              style={{ flexShrink: 0, width: 34, height: 34, borderRadius: '50%', background: 'oklch(95% 0.005 60)', border: '1px solid oklch(90% 0.01 265)', cursor: 'pointer', fontSize: 17, lineHeight: 1, color: 'oklch(40% 0.04 265)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
          </div>
          <div style={{ marginTop: 12, fontSize: 13.5, color: 'oklch(40% 0.04 265)', fontWeight: 600 }}>
            {dateStr} · {timeStr} <span style={{ color: 'oklch(58% 0.03 265)', fontWeight: 500 }}>{tz}</span>
          </div>
        </div>

        {/* Facts */}
        <div style={{ padding: '4px 20px 8px' }}>
          {factRow('Duration', `${b.durationMinutes} minutes`)}
          {factRow('Status', (
            <span style={{ background: badge.bg, color: badge.fg, border: `1px solid ${badge.bd}`, borderRadius: 20, padding: '3px 11px', fontSize: 12, fontWeight: 700 }}>{badge.t}</span>
          ))}
          {factRow('Recurring', b.isRecurring
            ? <span style={{ color: 'oklch(36% 0.13 75)', fontWeight: 700 }}>↻ Yes</span>
            : <span style={{ color: 'oklch(58% 0.03 265)' }}>No</span>)}
        </div>

        {/* Live now (only renders content when the class is in its live window) */}
        {liveEl && <div style={{ padding: '0 20px' }}>{liveEl}</div>}

        {/* Pending reschedule — approve / decline inline */}
        {rd && (
          <div style={{ margin: '8px 20px 0', background: 'oklch(96.5% 0.07 80)', border: '1px solid oklch(88% 0.09 80)', borderRadius: 10, padding: '12px 14px' }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'oklch(34% 0.13 75)', marginBottom: 4 }}>🔄 Reschedule requested</div>
            <div style={{ fontSize: 13, color: 'oklch(38% 0.1 75)', marginBottom: 10 }}>New time: {rdStr}</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button disabled={busy} onClick={onApproveResched}
                style={{ flex: 1, background: 'oklch(32% 0.14 150)', color: '#fff', border: 'none', borderRadius: 7, padding: '8px 0', fontSize: 12.5, fontWeight: 700, cursor: busy ? 'wait' : 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Approve</button>
              <button disabled={busy} onClick={onDeclineResched}
                style={{ flex: 1, background: '#fff', color: 'oklch(40% 0.1 25)', border: '1px solid oklch(88% 0.08 25)', borderRadius: 7, padding: '8px 0', fontSize: 12.5, fontWeight: 700, cursor: busy ? 'wait' : 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Decline</button>
            </div>
          </div>
        )}

        {/* Actions */}
        <div style={{ padding: '16px 20px 24px', marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 9 }}>
          {b.status !== 'cancelled' && actionBtn('📅 Reschedule this class', onReschedule, 'primary')}
          {b.audioStoragePath && actionBtn(
            b.transcriptStatus === 'done' ? '📝 View transcript' : b.transcriptStatus === 'error' ? '⚠ Transcript' : '⏳ Transcript',
            onTranscript, 'neutral')}
          {b.seriesId && b.status !== 'cancelled' && actionBtn('↻ Manage recurring series…', onSeries, 'series')}
          {actionBtn('Delete this class', onDelete, 'danger')}
        </div>
      </div>
    </div>
  );
};

window.AdminScheduleDetailDrawer = AdminScheduleDetailDrawer;
