/* MaiAgent Partner Portal — Team Member Management */

const MembersPage = ({ t, lang }) => {
  const [members, setMembers] = React.useState(MEMBERS.map(m => ({ ...m, perms: { ...m.perms } })));
  const [editTarget, setEditTarget] = React.useState(null);
  const [showInvite, setShowInvite] = React.useState(false);

  const allPermIds = PERM_MODULES.flatMap(m => m.items.map(i => i.id));
  const permCount = perms => Object.values(perms).filter(Boolean).length;

  const savePerms = (id, newPerms) => {
    setMembers(ms => ms.map(m => m.id === id ? { ...m, perms: newPerms } : m));
    setEditTarget(null);
  };

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-header__title">
          <div className="page-header__eyebrow">{lang === 'zh' ? '帳務' : 'Account'}</div>
          <h1>{t('members.title')}</h1>
          <div className="page-header__sub">{t('members.sub')}</div>
        </div>
        <Btn variant="primary" icon="plus" onClick={() => setShowInvite(true)}>{t('members.invite')}</Btn>
      </div>

      {/* Members table */}
      <div style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 16, overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: '#F8F9FF' }}>
              {[t('members.col.member'), t('members.col.role'), t('members.col.perms'), t('members.col.last_login'), ''].map((h, i) => (
                <th key={i} style={{ padding: '11px 16px', textAlign: 'left', fontSize: 12, fontWeight: 700, color: 'var(--mai-fg-3)', borderBottom: '1px solid var(--mai-border)' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {members.map((m) => {
              const isAdmin = m.role === 'admin';
              const pCount = permCount(m.perms);
              return (
                <tr key={m.id} style={{ borderBottom: '1px solid #F1F3FA' }}
                  onMouseEnter={e => e.currentTarget.style.background = '#FAFBFF'}
                  onMouseLeave={e => e.currentTarget.style.background = ''}>
                  <td style={{ padding: '14px 16px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <Avatar name={m.name[lang]} size="sm" />
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13.5, color: 'var(--mai-fg)' }}>{m.name[lang]}</div>
                        <div style={{ fontSize: 12, color: 'var(--mai-fg-3)' }}>{m.email}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: '14px 16px' }}>
                    {isAdmin
                      ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 10px', borderRadius: 999, background: 'linear-gradient(135deg, #EEF2FF, #E0F2FE)', border: '1px solid #C7D2F5', fontSize: 12, fontWeight: 700, color: 'var(--mai-blue)' }}>
                          <Icon name="shield-check" size={11} /> {t('members.role.admin')}
                        </span>
                      : <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 10px', borderRadius: 999, background: '#F4F6FF', border: '1px solid var(--mai-border)', fontSize: 12, fontWeight: 600, color: 'var(--mai-fg-2)' }}>
                          <Icon name="users" size={11} /> {t('members.role.member')}
                        </span>
                    }
                  </td>
                  <td style={{ padding: '14px 16px' }}>
                    {isAdmin
                      ? <span style={{ fontSize: 12.5, color: 'var(--mai-fg-3)', fontStyle: 'italic' }}>{lang === 'zh' ? '全部功能' : 'Full access'}</span>
                      : (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <div style={{ flex: 1, maxWidth: 100, height: 5, background: '#EEF2FF', borderRadius: 999, overflow: 'hidden' }}>
                            <div style={{ height: '100%', borderRadius: 999, width: (pCount / allPermIds.length * 100) + '%', background: 'var(--mai-blue)' }} />
                          </div>
                          <span style={{ fontSize: 12, color: 'var(--mai-fg-3)', whiteSpace: 'nowrap' }}>{pCount} / {allPermIds.length}</span>
                        </div>
                      )
                    }
                  </td>
                  <td style={{ padding: '14px 16px', fontSize: 12.5, color: 'var(--mai-fg-3)' }}>{m.lastLogin}</td>
                  <td style={{ padding: '14px 16px' }}>
                    {!isAdmin && (
                      <div style={{ display: 'flex', gap: 6 }}>
                        <Btn variant="ghost" size="sm" icon="settings" onClick={() => setEditTarget(m)}>{t('members.edit_perm')}</Btn>
                      </div>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {editTarget && (
        <PermModal
          member={editTarget}
          lang={lang}
          t={t}
          onSave={(id, perms) => savePerms(id, perms)}
          onClose={() => setEditTarget(null)}
        />
      )}
      {showInvite && <InviteModal lang={lang} t={t} onClose={() => setShowInvite(false)} />}
    </div>
  );
};

const PermModal = ({ member, lang, t, onSave, onClose }) => {
  const [perms, setPerms] = React.useState({ ...member.perms });
  const allPermIds = PERM_MODULES.flatMap(m => m.items.map(i => i.id));

  const applyPreset = (preset) => {
    const next = {};
    preset.perms.forEach(p => { next[p] = true; });
    setPerms(next);
  };

  const toggle = (id) => setPerms(p => ({ ...p, [id]: !p[id] }));

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: 20 }}>
      <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 600, boxShadow: '0 20px 60px rgba(0,0,0,0.18)', display: 'flex', flexDirection: 'column', maxHeight: '90vh' }}>
        {/* Header */}
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--mai-border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name={member.name[lang]} size="sm" />
            <div>
              <div style={{ fontWeight: 700, fontSize: 15 }}>{t('members.perm.title')}</div>
              <div style={{ fontSize: 12.5, color: 'var(--mai-fg-3)' }}>{member.name[lang]} · {member.email}</div>
            </div>
          </div>
          <button onClick={onClose} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--mai-fg-3)', display: 'grid', placeItems: 'center' }}><Icon name="x" size={18} /></button>
        </div>

        {/* Presets */}
        <div style={{ padding: '16px 24px', borderBottom: '1px solid #F1F3FA' }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--mai-fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>{t('members.perm.preset')}</div>
          <div style={{ display: 'flex', gap: 8 }}>
            {ROLE_PRESETS.map(p => (
              <button key={p.id} onClick={() => applyPreset(p)}
                style={{ padding: '6px 14px', borderRadius: 999, border: '1.5px solid var(--mai-border)', background: 'white', cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: 'var(--mai-fg-2)', transition: 'all 0.15s' }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--mai-blue)'; e.currentTarget.style.color = 'var(--mai-blue)'; e.currentTarget.style.background = '#EEF2FF'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--mai-border)'; e.currentTarget.style.color = 'var(--mai-fg-2)'; e.currentTarget.style.background = 'white'; }}>
                {lang === 'zh' ? p.zh : p.en}
              </button>
            ))}
            <button onClick={() => setPerms({})}
              style={{ padding: '6px 14px', borderRadius: 999, border: '1.5px solid #FEE2E2', background: 'white', cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: '#B91C1C' }}>
              {lang === 'zh' ? '清除全部' : 'Clear all'}
            </button>
          </div>
        </div>

        {/* Permission modules */}
        <div style={{ padding: '16px 24px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
          {PERM_MODULES.map(mod => (
            <div key={mod.id}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <div style={{ width: 26, height: 26, borderRadius: 6, background: '#F0F4FF', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  <Icon name={mod.icon} size={13} style={{ color: 'var(--mai-blue)' }} />
                </div>
                <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--mai-fg)' }}>{lang === 'zh' ? mod.zh : mod.en}</span>
              </div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', paddingLeft: 34 }}>
                {mod.items.map(item => {
                  const on = !!perms[item.id];
                  return (
                    <button key={item.id} onClick={() => toggle(item.id)}
                      style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 8, border: '1.5px solid ' + (on ? 'var(--mai-blue)' : 'var(--mai-border)'), background: on ? '#EEF2FF' : 'white', cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: on ? 'var(--mai-blue)' : 'var(--mai-fg-3)', transition: 'all 0.15s' }}>
                      <Icon name={on ? 'check' : 'plus'} size={12} />
                      {lang === 'zh' ? item.zh : item.en}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        {/* Footer */}
        <div style={{ padding: '16px 24px', borderTop: '1px solid var(--mai-border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 12.5, color: 'var(--mai-fg-3)' }}>
            {Object.values(perms).filter(Boolean).length} / {allPermIds.length} {lang === 'zh' ? '項功能已開啟' : 'permissions enabled'}
          </span>
          <div style={{ display: 'flex', gap: 10 }}>
            <Btn variant="ghost" onClick={onClose}>{t('common.cancel')}</Btn>
            <Btn variant="primary" icon="check" onClick={() => onSave(member.id, perms)}>{t('members.perm.save')}</Btn>
          </div>
        </div>
      </div>
    </div>
  );
};

const InviteModal = ({ lang, t, onClose }) => {
  const [email, setEmail] = React.useState('');
  const [preset, setPreset] = React.useState('');

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: 20 }}>
      <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 440, boxShadow: '0 20px 60px rgba(0,0,0,0.18)' }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--mai-border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontWeight: 700, fontSize: 15 }}>{t('members.invite.title')}</div>
          <button onClick={onClose} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--mai-fg-3)', display: 'grid', placeItems: 'center' }}><Icon name="x" size={18} /></button>
        </div>
        <div style={{ padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <label style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--mai-fg-2)', display: 'block', marginBottom: 6 }}>{t('members.invite.email')} <span style={{ color: '#EF4444' }}>*</span></label>
            <input className="input" style={{ width: '100%', boxSizing: 'border-box' }} type="email" placeholder="name@company.com" value={email} onChange={e => setEmail(e.target.value)} />
          </div>
          <div>
            <label style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--mai-fg-2)', display: 'block', marginBottom: 6 }}>{t('members.invite.preset')}</label>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {[{ id: '', zh: '自訂', en: 'Custom' }, ...ROLE_PRESETS].map(p => (
                <button key={p.id} onClick={() => setPreset(p.id)}
                  style={{ padding: '6px 14px', borderRadius: 999, border: '1.5px solid ' + (preset === p.id ? 'var(--mai-blue)' : 'var(--mai-border)'), background: preset === p.id ? '#EEF2FF' : 'white', cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: preset === p.id ? 'var(--mai-blue)' : 'var(--mai-fg-2)' }}>
                  {lang === 'zh' ? p.zh : p.en}
                </button>
              ))}
            </div>
            <div style={{ marginTop: 8, fontSize: 12, color: 'var(--mai-fg-3)' }}>
              {lang === 'zh' ? '邀請送出後，管理員仍可在成員列表精細調整權限。' : 'You can fine-tune permissions after the invite is sent.'}
            </div>
          </div>
        </div>
        <div style={{ padding: '16px 24px', borderTop: '1px solid var(--mai-border)', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
          <Btn variant="ghost" onClick={onClose}>{t('common.cancel')}</Btn>
          <Btn variant="primary" icon="mail" onClick={onClose} disabled={!email}>{t('members.invite.send')}</Btn>
        </div>
      </div>
    </div>
  );
};

window.MembersPage = MembersPage;
