// Primus IQ — Invite Modal

const InviteModal = ({ open, project, onClose, onInviteSent, currentUser }) => {
  const [email, setEmail] = React.useState('');
  const [role, setRole] = React.useState('member');
  const [sending, setSending] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState('');
  const ORG_DOMAIN = 'primuspartners.in';   // invites limited to this domain (backend enforces too)
  const [members, setMembers] = React.useState([]);
  const [joinRequests, setJoinRequests] = React.useState([]);
  const [suggestions, setSuggestions] = React.useState([]);
  const [searchTimer, setSearchTimer] = React.useState(null);
  const [showSuggestions, setShowSuggestions] = React.useState(false);

  const refreshTeam = (projectId) => {
    PrimusAPI.listMembers(projectId)
      .then(data => setMembers(data || [])).catch(() => {});
    PrimusAPI.listJoinRequests(projectId)
      .then(data => setJoinRequests(data || [])).catch(() => setJoinRequests([]));
  };

  React.useEffect(() => {
    if (open && project?.id) {
      refreshTeam(project.id);
    } else {
      setMembers([]);
      setJoinRequests([]);
      setEmail('');
      setSuggestions([]);
    }
  }, [open, project?.id]);

  if (!open) return null;

  const handleEmailChange = (e) => {
    const val = e.target.value;
    setEmail(val);
    if (searchTimer) clearTimeout(searchTimer);
    if (val.length >= 2) {
      const timer = setTimeout(async () => {
        try {
          const results = await PrimusAPI.directorySearch(val);
          setSuggestions(results || []);
          setShowSuggestions(true);
        } catch { setSuggestions([]); }
      }, 300);
      setSearchTimer(timer);
    } else {
      setSuggestions([]);
      setShowSuggestions(false);
    }
  };

  const selectSuggestion = (u) => {
    setEmail(u.email);
    setShowSuggestions(false);
    setSuggestions([]);
  };

  const handleSend = async () => {
    if (!email || !project?.id) return;
    setError('');
    const match = suggestions.find(u => u.email === email);
    // For a typed (non-directory) email, enforce the org domain before sending.
    if (!match && !email.trim().toLowerCase().endsWith('@' + ORG_DOMAIN)) {
      setError(`Invites are limited to @${ORG_DOMAIN} addresses.`);
      return;
    }
    setSending(true);
    try {
      if (match) {
        await PrimusAPI.inviteMember(project.id, { id: match.id, email: match.email, full_name: match.full_name, in_system: true }, role);
      } else {
        await PrimusAPI.inviteMember(project.id, { email, full_name: email, in_system: false }, role);
      }
      setSent(true);
      setTimeout(() => {
        setSent(false); setEmail('');
        refreshTeam(project.id);
        if (onInviteSent) onInviteSent();
      }, 1500);
    } catch (ex) {
      setError(ex.message || 'Invite failed.');
    } finally { setSending(false); }
  };

  const handleApprove = async (reqId) => {
    try {
      await PrimusAPI.approveJoinRequest(project.id, reqId);
      refreshTeam(project.id);
    } catch (ex) { console.error('Approve failed:', ex); }
  };

  const handleReject = async (reqId) => {
    try {
      await PrimusAPI.rejectJoinRequest(project.id, reqId);
      setJoinRequests(prev => prev.filter(r => r.id !== reqId));
    } catch (ex) { console.error('Reject failed:', ex); }
  };

  const meInitials = currentUser?.full_name
    ? currentUser.full_name.split(' ').filter(Boolean).map(w => w[0].toUpperCase()).slice(0, 2).join('')
    : '?';

  return (
    <ModalShell onClose={onClose} width={680} title="Invite to project" subtitle={(project && project.name) || 'Project'}>
      <div style={{ padding: '0 24px 24px' }}>
        <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Invite by email</label>
        <div style={{ display: 'flex', gap: 8, marginTop: 8, position: 'relative' }}>
          <div style={{ flex: 1, position: 'relative' }}>
            <input
              value={email}
              onChange={handleEmailChange}
              onBlur={() => setTimeout(() => setShowSuggestions(false), 150)}
              onFocus={() => suggestions.length > 0 && setShowSuggestions(true)}
              placeholder="name@primuspartners.in"
              style={{
                width: '100%', height: 40, padding: '0 14px', borderRadius: 10,
                border: '1px solid var(--line-2)', background: 'var(--bg-card)',
                fontSize: 14, fontFamily: 'inherit', color: 'var(--ink)',
              }}
            />
            {showSuggestions && suggestions.length > 0 && (
              <div style={{
                position: 'absolute', top: '100%', left: 0, right: 0, marginTop: 4,
                background: 'var(--bg-card)', border: '1px solid var(--line-2)', borderRadius: 10,
                boxShadow: 'var(--shadow-md)', zIndex: 50,
                maxHeight: 220, overflowY: 'auto',
              }}>
                {suggestions.map(u => (
                  <div key={u.id || u.email} onMouseDown={() => selectSuggestion(u)} style={{
                    padding: '10px 14px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10,
                    transition: 'background 0.1s',
                  }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-soft)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  >
                    <div style={{
                      width: 28, height: 28, borderRadius: 14, flexShrink: 0,
                      background: 'var(--maroon-06)', color: 'var(--maroon)',
                      display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700,
                    }}>
                      {(u.full_name || u.email || '?')[0].toUpperCase()}
                    </div>
                    <div>
                      <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 600 }}>{u.full_name || u.email}</div>
                      <div style={{ fontSize: 11, color: 'var(--mute)' }}>{u.email} · {u.designation || ''}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
          <select value={role} onChange={e => setRole(e.target.value)} style={{
            height: 40, padding: '0 12px', borderRadius: 10,
            border: '1px solid var(--line-2)', background: 'var(--bg-card)',
            fontSize: 13, fontFamily: 'inherit', color: 'var(--ink)',
          }}>
            <option value="viewer">Viewer</option>
            <option value="member">Member</option>
          </select>
          <button className="btn-primary" style={{ height: 40 }} onClick={handleSend} disabled={sending || !email}>
            {sent ? '✓ Sent!' : sending ? 'Sending…' : 'Send invite'}
          </button>
        </div>
        {error && (
          <div style={{ marginTop: 8, fontSize: 12, color: 'var(--maroon)' }}>{error}</div>
        )}

        {joinRequests.length > 0 && (
          <div style={{ marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Pending requests</label>
              <span style={{ fontSize: 11, fontWeight: 700, background: 'var(--maroon)', color: 'white', borderRadius: 10, padding: '1px 7px' }}>{joinRequests.length}</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2, maxHeight: 180, overflowY: 'auto' }}>
              {joinRequests.map(req => (
                <div key={req.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0' }}>
                  <div className="avatar" style={{ width: 32, height: 32, fontSize: 12 }}>{(req.requester_name || '?')[0].toUpperCase()}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 600 }}>{req.requester_name}</div>
                    <div style={{ fontSize: 11, color: 'var(--mute)' }}>{req.requester_designation || 'Primus Partners'}</div>
                  </div>
                  <button onClick={() => handleApprove(req.id)} style={{
                    height: 30, padding: '0 12px', borderRadius: 7, border: 'none',
                    background: 'var(--maroon)', color: 'white',
                    fontSize: 12, fontFamily: 'inherit', fontWeight: 600, cursor: 'pointer',
                  }}>Approve</button>
                  <button onClick={() => handleReject(req.id)} style={{
                    height: 30, padding: '0 10px', borderRadius: 7,
                    border: '1px solid var(--line-2)', background: 'var(--bg-card)',
                    fontSize: 12, fontFamily: 'inherit', color: 'var(--ink-2)', cursor: 'pointer',
                  }}>Reject</button>
                </div>
              ))}
            </div>
          </div>
        )}

        <div style={{ marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
          <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>People with access</label>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2, marginTop: 10, maxHeight: 220, overflowY: 'auto' }}>
            {currentUser && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0' }}>
                <div className="avatar" style={{ width: 32, height: 32, fontSize: 12 }}>{meInitials}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 600 }}>{currentUser.full_name} (you)</div>
                  <div style={{ fontSize: 11, color: 'var(--mute)' }}>{currentUser.primus_email}</div>
                </div>
                <span className="role-badge owner">OWNER</span>
              </div>
            )}
            {members.filter(m => m.user_id !== currentUser?.id).map(m => {
              const av = (m.full_name || '?')[0].toUpperCase();
              return (
                <div key={m.user_id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0' }}>
                  <div className="avatar" style={{ width: 32, height: 32, fontSize: 12 }}>{av}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 600 }}>{m.full_name}</div>
                    <div style={{ fontSize: 11, color: 'var(--mute)' }}>{m.designation || m.role}</div>
                  </div>
                  <span style={{ fontSize: 12, color: 'var(--mute)', textTransform: 'capitalize' }}>{m.role}</span>
                </div>
              );
            })}
            {members.length === 0 && !currentUser && (
              <div style={{ fontSize: 13, color: 'var(--mute)', padding: '12px 0' }}>Loading members…</div>
            )}
          </div>
        </div>
      </div>
    </ModalShell>
  );
};

Object.assign(window, {
  InviteModal,
});
