// src/features/admin/ui/admin-meeting-notes.jsx
//
// Admin "Send note" button rendered inside the live-meeting row on the
// Schedule tab. Click → modal with textarea + Send. Send calls the
// admin_send_meeting_note RPC; the teacher's open meeting wrapper page
// receives it over Supabase realtime and renders the banner.
//
// Public API:
//   window.AdminMeetingNotes.SendMeetingNoteButton({ booking })
//
// Renders as a small inline-block button — sized to sit naturally next to
// the existing Join button in admin-schedule-live's RowStatus. No layout
// changes to RowStatus.

(function () {
  'use strict';

  window.AdminMeetingNotes = window.AdminMeetingNotes || {};

  const MAX_LEN = 500;

  // Compact button that opens the modal. Lives inside RowStatus.
  function SendMeetingNoteButton({ booking }) {
    const [open, setOpen] = React.useState(false);
    if (!booking || !booking.id) return null;
    return (
      <React.Fragment>
        <button
          type="button"
          onClick={() => setOpen(true)}
          title="Send a short note to the teacher inside the meeting"
          style={{
            background: '#fff',
            color: 'oklch(34% 0.13 75)',
            border: '1px solid oklch(82% 0.10 75)',
            borderRadius: 6,
            padding: '5px 10px',
            fontSize: 11,
            fontWeight: 700,
            cursor: 'pointer',
            fontFamily: "'Plus Jakarta Sans', sans-serif",
            whiteSpace: 'nowrap',
          }}
        >
          Send note
        </button>
        {open && (
          <SendNoteModal
            booking={booking}
            onClose={() => setOpen(false)}
          />
        )}
      </React.Fragment>
    );
  }

  function SendNoteModal({ booking, onClose }) {
    const [message, setMessage] = React.useState('');
    const [busy,    setBusy]    = React.useState(false);
    const [error,   setError]   = React.useState('');
    const [sent,    setSent]    = React.useState(false);
    const taRef = React.useRef(null);

    React.useEffect(() => {
      // Autofocus on open so the admin can just start typing.
      const t = setTimeout(() => { try { taRef.current?.focus(); } catch (_) {} }, 30);
      return () => clearTimeout(t);
    }, []);

    // Escape closes when not busy.
    React.useEffect(() => {
      function onKey(e) {
        if (e.key === 'Escape' && !busy) onClose();
      }
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [busy, onClose]);

    const trimmedLen = message.trim().length;
    const canSend = trimmedLen > 0 && trimmedLen <= MAX_LEN && !busy;

    async function handleSend(e) {
      if (e) e.preventDefault();
      if (!canSend) return;
      setBusy(true); setError('');
      try {
        const { error: rpcErr } = await window.supa.rpc('admin_send_meeting_note', {
          p_booking_id: booking.id,
          p_message:    message.trim(),
        });
        if (rpcErr) throw rpcErr;
        setSent(true);
        // Brief success state, then close so admin can continue.
        setTimeout(onClose, 900);
      } catch (err) {
        setError(err?.message || 'Could not send. Try again.');
        setBusy(false);
      }
    }

    return (
      <div
        role="dialog"
        aria-modal="true"
        aria-label="Send note to teacher"
        onClick={(e) => { if (e.target === e.currentTarget && !busy) onClose(); }}
        style={{
          position: 'fixed', inset: 0,
          background: 'rgba(15, 17, 21, 0.55)',
          zIndex: 10000,
          display: 'flex',
          alignItems: 'flex-end',
          justifyContent: 'center',
          padding: 12,
          fontFamily: "'Plus Jakarta Sans', sans-serif",
        }}
      >
        <form
          onSubmit={handleSend}
          onClick={(e) => e.stopPropagation()}
          style={{
            background: '#fff',
            width: '100%', maxWidth: 460,
            borderRadius: 16,
            padding: 18,
            boxShadow: '0 24px 60px rgba(0,0,0,0.35)',
            marginBottom: 'env(safe-area-inset-bottom, 0px)',
            // On wider viewports center it vertically; on mobile the
            // bottom-sheet alignment above keeps it above any keyboard.
            alignSelf: window.innerWidth >= 720 ? 'center' : 'flex-end',
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <h2 style={{
              margin: 0, fontSize: 16, fontWeight: 700,
              color: 'oklch(22% 0.06 265)',
            }}>
              Note to teacher
            </h2>
            <span style={{ flex: 1 }} />
            <button
              type="button"
              onClick={onClose}
              disabled={busy}
              aria-label="Close"
              style={{
                background: 'transparent', border: 'none',
                color: 'oklch(46% 0.04 265)',
                fontSize: 22, cursor: busy ? 'not-allowed' : 'pointer',
                padding: 0, lineHeight: 1, width: 32, height: 32,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}
            >×</button>
          </div>
          <p style={{
            margin: '0 0 10px',
            fontSize: 12, color: 'oklch(46% 0.04 265)', lineHeight: 1.4,
          }}>
            Appears inside the meeting until she taps Got it.
          </p>
          <textarea
            ref={taRef}
            value={message}
            onChange={(e) => setMessage(e.target.value.slice(0, MAX_LEN))}
            placeholder="e.g. Wrap up in 5 — next student is waiting."
            rows={4}
            disabled={busy || sent}
            style={{
              width: '100%',
              boxSizing: 'border-box',
              padding: '10px 12px',
              border: '1px solid oklch(86% 0.02 265)',
              borderRadius: 9,
              fontFamily: 'inherit',
              fontSize: 15,
              lineHeight: 1.45,
              color: 'oklch(20% 0.05 265)',
              resize: 'vertical',
              minHeight: 90,
              outline: 'none',
            }}
          />
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            marginTop: 4, marginBottom: 14,
          }}>
            <span style={{
              fontSize: 11,
              color: trimmedLen > MAX_LEN - 50
                ? 'oklch(48% 0.18 25)'
                : 'oklch(56% 0.03 265)',
              fontWeight: trimmedLen > MAX_LEN - 50 ? 700 : 500,
            }}>
              {trimmedLen} / {MAX_LEN}
            </span>
            <span style={{ flex: 1 }} />
            {error && (
              <span style={{
                fontSize: 11, color: 'oklch(46% 0.18 25)',
                fontWeight: 600,
              }}>
                {error}
              </span>
            )}
          </div>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
            <button
              type="button"
              onClick={onClose}
              disabled={busy}
              style={{
                background: 'transparent', border: 'none',
                color: 'oklch(46% 0.04 265)',
                padding: '12px 16px',
                fontSize: 14, fontWeight: 600,
                cursor: busy ? 'not-allowed' : 'pointer',
                fontFamily: 'inherit',
              }}
            >Cancel</button>
            <button
              type="submit"
              disabled={!canSend}
              style={{
                background: canSend ? 'oklch(56% 0.13 250)' : 'oklch(82% 0.02 265)',
                color: '#fff',
                border: 'none',
                borderRadius: 10,
                padding: '12px 18px',
                minHeight: 44,
                fontSize: 14, fontWeight: 700,
                cursor: canSend ? 'pointer' : 'not-allowed',
                fontFamily: 'inherit',
              }}
            >
              {sent ? 'Sent' : busy ? 'Sending…' : 'Send'}
            </button>
          </div>
        </form>
      </div>
    );
  }

  window.AdminMeetingNotes.SendMeetingNoteButton = SendMeetingNoteButton;
})();
