// invite-member.jsx — "Invite member" modal for Settings → Members.
//
// R03 / T0007 (Phase 5). Email + role picker (owner/admin/member/viewer,
// restricted server-side to roles ≤ the actor's role). On submit calls
// `inviteMember({workspace_id, email, role, continue_url_base})`.
// Exposes window.InviteMemberModal.

(function (window) {
  'use strict';

  const { fns } = window.exoteamAuth || {};
  if (!fns) {
    console.error('invite-member.jsx: window.exoteamAuth missing');
    return;
  }

  // Roles a given actor-role is allowed to invite at. Mirrors the
  // server-side check in `inviteMember.js` so the picker doesn't offer
  // options that will 403; the server is still the source of truth.
  function rolesUserCanInvite(actorRole) {
    if (actorRole === 'owner') return ['owner', 'admin', 'member', 'viewer'];
    if (actorRole === 'admin') return ['admin', 'member', 'viewer'];
    return [];
  }

  const ROLE_DESCRIPTIONS = {
    owner: 'Full access — billing, members, all data. There is always at least one owner.',
    admin: 'Manage members + billing + workspace settings. Cannot change workspace ownership.',
    member: 'Read + edit ICP, products, dossiers, outreach. No member or billing changes.',
    viewer: 'Read-only across everything. Cannot edit, send, or invite.',
  };

  function InviteMemberModal({ workspaceId, actorRole, onClose, onInvited }) {
    const [email, setEmail] = React.useState('');
    const [role, setRole] = React.useState('member');
    const [busy, setBusy] = React.useState(false);
    const [error, setError] = React.useState(null);
    const [sent, setSent] = React.useState(false);

    const allowed = rolesUserCanInvite(actorRole || 'member');

    React.useEffect(() => {
      if (allowed.length > 0 && !allowed.includes(role)) {
        setRole(allowed.includes('member') ? 'member' : allowed[0]);
      }
    }, [actorRole]);

    async function submit(e) {
      e.preventDefault();
      const trimmed = email.trim().toLowerCase();
      if (!trimmed) return;
      setBusy(true);
      setError(null);
      try {
        const callable = fns.httpsCallable('inviteMember');
        await callable({
          workspace_id: workspaceId,
          email: trimmed,
          role,
          continue_url_base: window.location.origin,
        });
        setSent(true);
        if (onInvited) onInvited({ email: trimmed, role });
      } catch (err) {
        console.error('inviteMember failed', err);
        setError(err.message || String(err));
      } finally {
        setBusy(false);
      }
    }

    if (allowed.length === 0) {
      return (
        <Modal onClose={onClose} title="Invite a member">
          <p className="exo-admin-modal-body">
            Your role on this Workspace doesn't allow inviting members.
            Ask an owner or admin.
          </p>
          <div className="exo-admin-modal-actions">
            <button
              type="button"
              className="exo-admin-btn exo-admin-btn--ghost"
              onClick={onClose}
            >
              Close
            </button>
          </div>
        </Modal>
      );
    }

    return (
      <Modal onClose={onClose} title="Invite a member">
        {sent ? (
          <>
            <p className="exo-admin-modal-body">
              Invitation sent to <strong>{email}</strong>. They'll get a
              magic link to accept and land on this Workspace's
              dashboard.
            </p>
            <div className="exo-admin-modal-actions">
              <button
                type="button"
                className="exo-admin-btn"
                onClick={onClose}
              >
                Done
              </button>
            </div>
          </>
        ) : (
          <form onSubmit={submit}>
            <label className="exo-admin-label" htmlFor="exo-invite-email" style={{ marginTop: 0 }}>
              Email address
            </label>
            <input
              id="exo-invite-email"
              type="email"
              required
              autoFocus
              autoComplete="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="exo-admin-input"
              placeholder="colleague@theircompany.com"
              disabled={busy}
            />
            <label className="exo-admin-label" htmlFor="exo-invite-role">
              Role
            </label>
            <select
              id="exo-invite-role"
              className="exo-admin-select"
              value={role}
              onChange={(e) => setRole(e.target.value)}
              disabled={busy}
            >
              {allowed.map((r) => (
                <option key={r} value={r}>
                  {r.charAt(0).toUpperCase() + r.slice(1)}
                </option>
              ))}
            </select>
            <p className="exo-admin-hint">{ROLE_DESCRIPTIONS[role]}</p>
            {error && (
              <div className="exo-admin-banner is-error" style={{ marginTop: 12 }}>
                <span>{error}</span>
              </div>
            )}
            <div className="exo-admin-modal-actions">
              <button
                type="button"
                className="exo-admin-btn exo-admin-btn--ghost"
                onClick={onClose}
                disabled={busy}
              >
                Cancel
              </button>
              <button
                type="submit"
                className="exo-admin-btn"
                disabled={busy || !email.trim()}
              >
                {busy ? 'Sending…' : 'Send invite'}
              </button>
            </div>
          </form>
        )}
      </Modal>
    );
  }

  function Modal({ title, children, onClose }) {
    React.useEffect(() => {
      function onKey(e) {
        if (e.key === 'Escape') onClose();
      }
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [onClose]);

    return (
      <div className="exo-admin-modal-backdrop" onClick={onClose}>
        <div className="exo-admin-modal" onClick={(e) => e.stopPropagation()}>
          <h3 className="exo-admin-modal-title">{title}</h3>
          {children}
        </div>
      </div>
    );
  }

  window.InviteMemberModal = InviteMemberModal;
})(window);
