// Project members management modal
const MBIcons = window.Icons;

function MembersModal({ project, currentUser, onClose }) {
  const [members,    setMembers]    = React.useState([]);
  const [pending,    setPending]    = React.useState([]);
  const [email,      setEmail]      = React.useState('');
  const [role,       setRole]       = React.useState('editor');
  const [loading,    setLoading]    = React.useState(true);
  const [inviting,   setInviting]   = React.useState(false);
  const [inviteLink, setInviteLink] = React.useState('');
  const [msg,        setMsg]        = React.useState(null); // { type: 'ok'|'err', text }

  const load = async () => {
    setLoading(true);
    try {
      const res = await fetch(`./api/invite.php?action=members&projectKey=${encodeURIComponent(project.id)}`, { credentials: 'include' });
      const data = await res.json();
      if (data.ok) { setMembers(data.members || []); setPending(data.pending || []); }
    } catch (e) {}
    setLoading(false);
  };

  React.useEffect(() => { load(); }, [project.id]);

  const invite = async () => {
    if (!email.trim()) return;
    setInviting(true);
    setMsg(null);
    try {
      const res = await fetch('./api/invite.php?action=invite', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ projectKey: project.id, projectName: project.name, email: email.trim(), role }),
      });
      const data = await res.json();
      if (data.ok) {
        setInviteLink(data.inviteUrl);
        setMsg({ type: 'ok', text: 'Davet bağlantısı oluşturuldu.' });
        setEmail('');
        load();
      } else {
        setMsg({ type: 'err', text: data.error || 'Hata oluştu.' });
      }
    } catch (e) {
      setMsg({ type: 'err', text: 'Ağ hatası.' });
    }
    setInviting(false);
  };

  const removeMember = async (memberId) => {
    try {
      await fetch('./api/invite.php?action=remove', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ projectKey: project.id, memberId }),
      });
      load();
    } catch (e) {}
  };

  const revokeInvite = async (invEmail) => {
    try {
      await fetch('./api/invite.php?action=revoke', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ projectKey: project.id, email: invEmail }),
      });
      load();
    } catch (e) {}
  };

  const copyLink = () => {
    navigator.clipboard?.writeText(inviteLink).then(() => setMsg({ type: 'ok', text: 'Bağlantı kopyalandı!' }));
  };

  return (
    <div className="confirm-overlay" onClick={onClose}>
      <div className="members-modal" onClick={e => e.stopPropagation()}>

        {/* Header */}
        <div className="members-modal-header">
          <div className="project-tile" style={{ background: project.color, width: 28, height: 28 }}>
            <window.ProjectIcon icon={project.icon} size={14} />
          </div>
          <div>
            <div className="members-modal-title">{project.name}</div>
            <div className="members-modal-sub">Proje üyeleri</div>
          </div>
          <button className="icon-btn icon-btn-sm" style={{ marginLeft: 'auto' }} onClick={onClose}>
            <MBIcons.X size={16} />
          </button>
        </div>

        {/* Body */}
        <div className="members-modal-body">
          {/* Owner */}
          <div className="members-section-label">Sahip</div>
          <div className="member-row">
            {currentUser.avatarUrl
              ? <img src={currentUser.avatarUrl} className="avatar avatar-img" alt="" style={{ width: 32, height: 32 }} />
              : <div className="avatar" style={{ width: 32, height: 32, fontSize: 11 }}>{window.projectAbbr(currentUser.name || 'U')}</div>
            }
            <div className="member-info">
              <div className="member-name">{currentUser.name}</div>
              <div className="member-email">{currentUser.email}</div>
            </div>
            <span className="member-role-badge role-owner">Sahip</span>
          </div>

          {/* Members */}
          {!loading && members.length > 0 && (
            <>
              <div className="members-section-label" style={{ marginTop: 16 }}>Üyeler ({members.length})</div>
              {members.map(m => (
                <div key={m.id} className="member-row">
                  {m.avatarUrl
                    ? <img src={m.avatarUrl} className="avatar avatar-img" alt="" style={{ width: 32, height: 32 }} />
                    : <div className="avatar" style={{ width: 32, height: 32, fontSize: 11 }}>{window.projectAbbr(m.name || m.email)}</div>
                  }
                  <div className="member-info">
                    <div className="member-name">{m.name || m.email}</div>
                    <div className="member-email">{m.email}</div>
                  </div>
                  <span className={`member-role-badge role-${m.role}`}>{m.role === 'editor' ? 'Editör' : 'Görüntüleyici'}</span>
                  <button className="icon-btn icon-btn-sm" onClick={() => removeMember(m.id)} title="Çıkar" style={{ opacity: .5 }}>
                    <MBIcons.X size={13} />
                  </button>
                </div>
              ))}
            </>
          )}

          {/* Pending invites */}
          {!loading && pending.length > 0 && (
            <>
              <div className="members-section-label" style={{ marginTop: 16 }}>Bekleyen Davetler</div>
              {pending.map((p, i) => (
                <div key={i} className="member-row pending">
                  <div className="avatar" style={{ width: 32, height: 32, fontSize: 11, background: 'var(--bg-sunken)', color: 'var(--text-muted)' }}>
                    <MBIcons.Mail size={14} />
                  </div>
                  <div className="member-info">
                    <div className="member-email">{p.email}</div>
                    <div className="member-email" style={{ fontSize: 11 }}>Davet süresi: {p.expires_at?.slice(0, 10)}</div>
                  </div>
                  <span className={`member-role-badge role-${p.role}`}>{p.role === 'editor' ? 'Editör' : 'Görüntüleyici'}</span>
                  <button className="icon-btn icon-btn-sm" onClick={() => revokeInvite(p.email)} title="İptal et" style={{ opacity: .5 }}>
                    <MBIcons.X size={13} />
                  </button>
                </div>
              ))}
            </>
          )}

          {loading && <div style={{ padding: '16px 0', color: 'var(--text-muted)', fontSize: 13 }}>Yükleniyor...</div>}

          {/* Invite form */}
          <div className="members-invite-section">
            <div className="members-section-label" style={{ marginTop: 16 }}>Davet Et</div>
            <div className="members-invite-row">
              <input
                className="input"
                type="email"
                placeholder="ornek@email.com"
                value={email}
                onChange={e => setEmail(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && invite()}
                style={{ flex: 1, height: 40, fontSize: 13 }}
              />
              <select className="select-control" value={role} onChange={e => setRole(e.target.value)} style={{ height: 40, width: 130, fontSize: 13 }}>
                <option value="editor">Editör</option>
                <option value="viewer">Görüntüleyici</option>
              </select>
              <button className="btn btn-primary btn-sm" onClick={invite} disabled={inviting || !email.trim()}>
                {inviting ? '...' : 'Davet Et'}
              </button>
            </div>

            {msg && (
              <div className={`profile-msg ${msg.type === 'ok' ? 'ok' : 'err'}`} style={{ marginTop: 8 }}>
                {msg.text}
              </div>
            )}

            {inviteLink && (
              <div className="members-invite-link">
                <span className="members-invite-link-url">{inviteLink}</span>
                <button className="btn btn-ghost btn-sm" onClick={copyLink}>
                  <MBIcons.Copy size={13} /> Kopyala
                </button>
              </div>
            )}

            <div className="members-role-desc">
              <strong>Editör:</strong> Görev ekleyebilir, düzenleyebilir. &nbsp;
              <strong>Görüntüleyici:</strong> Sadece okuyabilir.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.MembersModal = MembersModal;
