// admin-pending-confirmations.jsx — admin surface for assignments where
// the teacher hasn't yet confirmed the new student (v55 confirm flow).
//
// Backend (v57):
//   - public.admin_unconfirmed_assignments() returns every unconfirmed
//     active assignment with teacher + student names, hours_since_email,
//     and an `urgency` flag ('red' >24h, 'amber' >6h, 'fresh' otherwise).
//   - public.admin_resend_confirm_email(uuid) re-fires the email + stamps
//     confirm_email_sent_at = now() so urgency resets.
//
// Renders standalone — Joe wires this into admin-dashboard.jsx as a new
// tab once the admin-UI-polish task lands (that task owns the file).
// Until then it's accessible by importing or hand-mounting; admin sees
// it as <window.AdminPendingConfirmations />.

const APC_BG       = '#fff';
const APC_BORDER   = 'oklch(90% 0.01 265)';
const APC_INK      = 'oklch(18% 0.03 265)';
const APC_MUTED    = 'oklch(50% 0.03 265)';
const APC_RED      = 'oklch(58% 0.22 25)';   // urgent
const APC_AMBER    = 'oklch(72% 0.17 80)';   // warning
const APC_GREEN    = 'oklch(60% 0.15 145)';  // success / fresh
const APC_PRIMARY  = 'oklch(22% 0.06 265)';

const APCBadge = ({ urgency }) => {
  const palette = {
    red:   { bg: 'oklch(95% 0.05 25)',  fg: APC_RED,   label: 'Urgent' },
    amber: { bg: 'oklch(96% 0.06 80)',  fg: 'oklch(45% 0.16 80)', label: 'Overdue' },
    fresh: { bg: 'oklch(95% 0.04 145)', fg: 'oklch(40% 0.12 145)', label: 'Pending' },
  }[urgency] || { bg: 'oklch(96% 0.01 265)', fg: APC_MUTED, label: 'Pending' };
  return (
    <span style={{
      display: 'inline-block', padding: '3px 9px', borderRadius: 999,
      fontSize: 10.5, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase',
      background: palette.bg, color: palette.fg,
    }}>{palette.label}</span>
  );
};

const formatHours = (h) => {
  if (h == null || isNaN(h)) return '—';
  const num = Number(h);
  if (num < 1) return `${Math.round(num * 60)}m`;
  if (num < 24) return `${num.toFixed(1)}h`;
  const d = Math.floor(num / 24);
  const rem = Math.round(num - d * 24);
  return rem ? `${d}d ${rem}h` : `${d}d`;
};

const formatWhen = (iso) => {
  if (!iso) return '—';
  try {
    const d = new Date(iso);
    return d.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
  } catch (e) { return '—'; }
};

const AdminPendingConfirmations = () => {
  const [rows, setRows]         = React.useState([]);
  const [loading, setLoading]   = React.useState(true);
  const [error, setError]       = React.useState('');
  const [nudgingId, setNudging] = React.useState(null);
  const [toast, setToast]       = React.useState('');

  const load = React.useCallback(async () => {
    setLoading(true); setError('');
    const { data, error: e } = await window.supa.rpc('admin_unconfirmed_assignments');
    if (e) {
      setError(e.message || 'Could not load pending confirmations.');
      setRows([]);
    } else {
      setRows(data || []);
    }
    setLoading(false);
  }, []);

  React.useEffect(() => {
    load();
    const t = setInterval(load, 60000); // 60s refresh
    return () => clearInterval(t);
  }, [load]);

  const onNudge = async (row) => {
    if (!window.confirm(`Re-send confirm email to ${row.instructor_name || 'this teacher'}?`)) return;
    setNudging(row.assignment_id);
    const { error: e } = await window.supa.rpc('admin_resend_confirm_email', { p_assignment_id: row.assignment_id });
    setNudging(null);
    if (e) {
      setToast(`Failed: ${e.message || 'unknown error'}`);
    } else {
      setToast(`Nudged ${row.instructor_name || 'teacher'}.`);
      load();
    }
    setTimeout(() => setToast(''), 3500);
  };

  if (loading && rows.length === 0) {
    return (
      <div style={{ padding: 30, color: APC_MUTED, fontSize: 13 }}>Loading pending confirmations…</div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: 30, color: APC_RED, fontSize: 13 }}>
        {error}
      </div>
    );
  }

  if (rows.length === 0) {
    return (
      <div style={{
        background: APC_BG, border: `1px solid ${APC_BORDER}`, borderRadius: 12,
        padding: '36px 28px', textAlign: 'center', color: APC_MUTED, fontSize: 14,
      }}>
        <div style={{ fontSize: 16, fontWeight: 600, color: APC_INK, marginBottom: 6 }}>
          All clear
        </div>
        Every assigned teacher has confirmed their student. Nothing pending.
      </div>
    );
  }

  const redCount   = rows.filter(r => r.urgency === 'red').length;
  const amberCount = rows.filter(r => r.urgency === 'amber').length;

  return (
    <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14, gap: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: APC_INK }}>{rows.length} pending</div>
          {redCount > 0 && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 9px', borderRadius: 999, background: 'oklch(95% 0.05 25)', color: APC_RED, fontSize: 11.5, fontWeight: 700 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: APC_RED }} />
              {redCount} urgent (24h+)
            </span>
          )}
          {amberCount > 0 && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 9px', borderRadius: 999, background: 'oklch(96% 0.06 80)', color: 'oklch(45% 0.16 80)', fontSize: 11.5, fontWeight: 700 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: APC_AMBER }} />
              {amberCount} overdue (6h+)
            </span>
          )}
        </div>
        <button
          onClick={load}
          style={{
            background: 'transparent', border: `1px solid ${APC_BORDER}`,
            borderRadius: 8, padding: '7px 14px', cursor: 'pointer',
            color: APC_MUTED, fontSize: 12, fontWeight: 600,
          }}
          aria-label="Refresh list"
        >Refresh</button>
      </div>

      {toast && (
        <div style={{
          marginBottom: 12, padding: '9px 14px', borderRadius: 9,
          background: 'oklch(96% 0.04 145)', color: 'oklch(36% 0.13 145)',
          fontSize: 12.5, fontWeight: 600,
        }}>{toast}</div>
      )}

      <div style={{
        background: APC_BG, border: `1px solid ${APC_BORDER}`, borderRadius: 12,
        overflow: 'hidden',
      }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: '1.3fr 1.3fr 100px 110px 130px',
          padding: '10px 18px', background: 'oklch(98% 0.005 265)',
          borderBottom: `1px solid ${APC_BORDER}`,
          fontSize: 10.5, fontWeight: 700, letterSpacing: '0.05em',
          textTransform: 'uppercase', color: APC_MUTED,
        }}>
          <div>Teacher</div>
          <div>Student</div>
          <div>Waiting</div>
          <div>Status</div>
          <div style={{ textAlign: 'right' }}>Action</div>
        </div>
        {rows.map(row => (
          <div
            key={row.assignment_id}
            style={{
              display: 'grid',
              gridTemplateColumns: '1.3fr 1.3fr 100px 110px 130px',
              padding: '13px 18px', alignItems: 'center',
              borderBottom: `1px solid ${APC_BORDER}`,
              fontSize: 13,
            }}
          >
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 600, color: APC_INK, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {row.instructor_name || '(no name)'}
              </div>
              <div style={{ fontSize: 11.5, color: APC_MUTED, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {row.instructor_email || '—'}
              </div>
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 600, color: APC_INK, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {row.student_name || '(no name)'}
              </div>
              <div style={{ fontSize: 11.5, color: APC_MUTED, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {row.student_email || '—'}
              </div>
            </div>
            <div style={{ color: APC_INK, fontWeight: 600 }}>{formatHours(row.hours_since_email)}</div>
            <div><APCBadge urgency={row.urgency} /></div>
            <div style={{ textAlign: 'right' }}>
              <button
                onClick={() => onNudge(row)}
                disabled={nudgingId === row.assignment_id}
                style={{
                  background: nudgingId === row.assignment_id ? 'oklch(94% 0.01 265)' : APC_PRIMARY,
                  color: '#fff', border: 'none', borderRadius: 8,
                  padding: '7px 14px', fontSize: 12, fontWeight: 600,
                  cursor: nudgingId === row.assignment_id ? 'wait' : 'pointer',
                  opacity: nudgingId === row.assignment_id ? 0.7 : 1,
                  fontFamily: 'inherit',
                }}
              >{nudgingId === row.assignment_id ? 'Sending…' : 'Nudge teacher'}</button>
            </div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 14, fontSize: 11.5, color: APC_MUTED }}>
        Refreshes every 60 seconds. The teacher receives the same confirm
        deep-link from v55. Nudging is a no-op if they already confirmed.
      </div>
    </div>
  );
};

Object.assign(window, { AdminPendingConfirmations });
