// src/features/calls/ui/request-call-button.jsx
//
// Phase 2 student-side replacement for the direct CallButton. Instead of
// ringing the teacher's phone (which doesn't work for foreign teachers —
// inbound international call, "calling-party-pays" markets bill the
// receiver, foreign +1 looks like spam), this button:
//
//   1. Posts an in-thread message via window.Messages.db.sendMessage(),
//      which routes through the send_message RPC, atomically inserting,
//      auditing, and emailing the teacher (the standard message-notify
//      flow already fires push + email).
//   2. Shows a confirmation ("Your teacher will get a notification").
//
// The teacher then initiates the call herself from the same thread,
// using the browser-audio CallButton — which means only the student's
// phone rings. Same end-to-end outcome, no inbound charge to a Lebanese
// teacher.
//
// Public: window.MaskedCalls.ui.RequestCallButton

(function () {
  const PRIMARY = 'oklch(50% 0.18 250)';
  const PRIMARY_HOVER = 'oklch(45% 0.18 250)';

  function RequestCallButton({ conversation, viewerUserId }) {
    const [open, setOpen]   = React.useState(false);
    const [busy, setBusy]   = React.useState(false);
    const [err,  setErr]    = React.useState('');
    const [done, setDone]   = React.useState(false);

    if (!conversation || !viewerUserId) return null;
    // Only renders for the student side. Membership re-checked server-side
    // when we send the message.
    if (conversation.student_id !== viewerUserId) return null;

    async function sendRequest() {
      setBusy(true); setErr(''); setDone(false);
      try {
        const sender = (window.MASTERY && window.MASTERY.profile) || {};
        const name = (sender.first_name || sender.full_name || 'A student').trim();
        const body = `Requesting a call back — ${name}. Please call me when you get a moment.`;
        // window.Messages.db.sendMessage is the canonical send path; it
        // routes through the send_message RPC which inserts the message
        // row + fires the teacher-notify email + push atomically.
        if (!window.Messages || !window.Messages.db || !window.Messages.db.sendMessage) {
          throw new Error('Messages helper not available — refresh the page and try again.');
        }
        await window.Messages.db.sendMessage({ conversationId: conversation.id, body });
        setDone(true);
        setTimeout(() => { setOpen(false); setDone(false); }, 3000);
      } catch (e) {
        setErr(e.message || String(e));
      } finally {
        setBusy(false);
      }
    }

    return (
      <React.Fragment>
        <button
          type="button"
          onClick={() => { setOpen(true); setErr(''); setDone(false); }}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '6px 12px', borderRadius: 6,
            background: PRIMARY, color: '#fff',
            border: 'none', cursor: 'pointer',
            fontSize: 13, fontWeight: 600,
            fontFamily: "'Plus Jakarta Sans', sans-serif",
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = PRIMARY_HOVER}
          onMouseLeave={(e) => e.currentTarget.style.background = PRIMARY}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.9.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          Request call
        </button>

        {open && (
          <div role="dialog" aria-modal="true"
            style={{
              position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              zIndex: 5000, padding: 16,
              fontFamily: "'Plus Jakarta Sans', sans-serif",
            }}
            onClick={(e) => { if (e.target === e.currentTarget && !busy) setOpen(false); }}
          >
            <div style={{
              background: '#fff', borderRadius: 12, padding: 24,
              maxWidth: 420, width: '100%',
              boxShadow: '0 12px 40px rgba(0,0,0,0.2)',
            }}>
              <div style={{ fontSize: 18, fontWeight: 700, color: 'oklch(22% 0.06 265)', marginBottom: 8 }}>
                Ask your teacher to call?
              </div>
              <div style={{ fontSize: 14, color: 'oklch(40% 0.04 265)', marginBottom: 16, lineHeight: 1.5 }}>
                We&rsquo;ll send your teacher a message asking them to call you. They&rsquo;ll
                get an email notification and can ring you from inside the lesson app — your
                phone will ring without showing their real number.
              </div>
              {err && (
                <div style={{
                  padding: 10, borderRadius: 6,
                  background: 'oklch(96% 0.06 25)', color: 'oklch(40% 0.15 25)',
                  fontSize: 13, marginBottom: 12,
                }}>{err}</div>
              )}
              {done && (
                <div style={{
                  padding: 10, borderRadius: 6,
                  background: 'oklch(96% 0.06 145)', color: 'oklch(36% 0.13 145)',
                  fontSize: 13, marginBottom: 12,
                }}>Your teacher will get a notification.</div>
              )}
              <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                <button
                  type="button"
                  disabled={busy}
                  onClick={() => setOpen(false)}
                  style={{
                    padding: '8px 16px', borderRadius: 6,
                    border: '1px solid oklch(86% 0.02 265)', background: '#fff',
                    cursor: busy ? 'not-allowed' : 'pointer',
                    fontSize: 14, color: 'oklch(35% 0.04 265)',
                    fontFamily: 'inherit',
                  }}
                >Cancel</button>
                <button
                  type="button"
                  disabled={busy || done}
                  onClick={sendRequest}
                  style={{
                    padding: '8px 16px', borderRadius: 6,
                    border: 'none', background: PRIMARY, color: '#fff',
                    cursor: (busy || done) ? 'not-allowed' : 'pointer',
                    fontSize: 14, fontWeight: 600,
                    fontFamily: 'inherit',
                    opacity: (busy || done) ? 0.7 : 1,
                  }}
                >{busy ? 'Sending…' : done ? 'Sent' : 'Send request'}</button>
              </div>
            </div>
          </div>
        )}
      </React.Fragment>
    );
  }

  window.MaskedCalls = window.MaskedCalls || {};
  window.MaskedCalls.ui = window.MaskedCalls.ui || {};
  window.MaskedCalls.ui.RequestCallButton = RequestCallButton;
})();
