// UserManagement — 設定 → 用戶管理。成員列表（email + 狀態），右下角「邀請」FAB。
// Pushed from the Settings 用戶管理 tile.

function UserManagement({ navigate }) {
  const t = window.flutterTokens;
  const [users, setUsers] = React.useState([
    { id: 'u1', email: 'andywu.england@gmail.com', status: 'registered', blocked: false, notes: '英國分公司・主帳號', lastOnline: '2026-07-02 09:14', registeredAt: '2025-11-08' },
    { id: 'u2', email: 'andywu.uk@gmail.com',      status: 'registered', blocked: false, notes: '', lastOnline: '2026-06-28 21:47', registeredAt: '2026-01-22' },
  ]);
  const [menuFor, setMenuFor] = React.useState(null); // user id with open kebab popmenu
  const [detailFor, setDetailFor] = React.useState(null); // user id whose detail page is pushed
  const [noteFor, setNoteFor] = React.useState(null); // user id whose notes are being edited
  const [noteDraft, setNoteDraft] = React.useState('');
  const [search, setSearch] = React.useState('');
  const [inviteOpen, setInviteOpen] = React.useState(false);
  const [draft, setDraft] = React.useState('');
  const [inviteNote, setInviteNote] = React.useState('');

  const sendInvite = () => {
    const email = draft.trim();
    if (!email) return;
    setUsers(prev => [...prev, { id: 'u_' + Math.random().toString(36).slice(2, 7), email, status: 'pending', blocked: false, notes: inviteNote.trim(), lastOnline: null, registeredAt: new Date().toISOString().slice(0, 10) }]);
    setDraft('');
    setInviteNote('');
    setInviteOpen(false);
  };
  const deleteUser = (id) => { setUsers(prev => prev.filter(u => u.id !== id)); setMenuFor(null); };
  const toggleBlock = (id) => { setUsers(prev => prev.map(u => u.id === id ? { ...u, blocked: !u.blocked } : u)); setMenuFor(null); };
  const openNotes = (u) => { setNoteDraft(u.notes || ''); setNoteFor(u.id); setMenuFor(null); };
  const saveNotes = () => { setUsers(prev => prev.map(u => u.id === noteFor ? { ...u, notes: noteDraft.trim() } : u)); setNoteFor(null); };

  const q = search.trim().toLowerCase();
  const shown = q
    ? users.filter(u => u.email.toLowerCase().includes(q) || (u.notes || '').toLowerCase().includes(q))
    : users;

  const detailForUser = detailFor ? users.find(u => u.id === detailFor) : null;

  return (
    <div style={{ height: '100%', background: t.bg, display: 'flex', flexDirection: 'column', position: 'relative' }}>
      {/* App bar */}
      <div style={{
        padding: '60px 16px 12px', background: t.bg,
        flexShrink: 0,
        display: 'flex', alignItems: 'center', gap: 4,
      }}>
        <button onClick={() => navigate({ screen: 'list' })} style={{
          background: 'none', border: 'none', cursor: 'pointer',
          padding: 6, marginLeft: -6, color: t.ink, display: 'flex',
        }}>
          <Icon name="back" size={22}/>
        </button>
        <div style={{
          flex: 1, minWidth: 0, textAlign: 'center',
          fontFamily: '"Plus Jakarta Sans", "Noto Sans TC", sans-serif',
          fontSize: 18, fontWeight: 700, color: t.ink, letterSpacing: -0.4,
        }}>用戶管理</div>
        {/* right action: invite */}
        <button onClick={() => { setDraft(''); setInviteNote(''); setInviteOpen(true); }} style={{
          background: 'none', border: 'none', cursor: 'pointer',
          padding: 6, marginRight: -6, color: t.ink, display: 'flex', flexShrink: 0,
        }}>
          <Icon name="user-plus" size={22} strokeWidth={2}/>
        </button>
      </div>

      {/* Search bar */}
      <div style={{
        padding: '10px 16px', background: t.bg, flexShrink: 0,
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: t.surface, borderRadius: 12, padding: '9px 12px',
          border: `1px solid ${t.hairline}`,
        }}>
          <Icon name="search" size={16} color={t.ink3}/>
          <input
            value={search} placeholder="搜尋"
            onChange={e => setSearch(e.target.value)}
            style={{
              flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent',
              fontFamily: 'inherit', fontSize: 15, color: t.ink,
            }}
          />
          {search && (
            <button onClick={() => setSearch('')} style={{
              background: 'none', border: 'none', cursor: 'pointer', color: t.ink3,
              display: 'flex', padding: 0,
            }}>
              <Icon name="x" size={16}/>
            </button>
          )}
        </div>
      </div>

      {/* List */}
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 40 }}>
        {shown.length === 0 ? (
          <div style={{
            padding: '48px 24px', textAlign: 'center',
            fontSize: 13.5, color: t.ink3,
          }}>找不到符合的成員</div>
        ) : shown.map((u, i) => (
          <UserRow
            key={u.id} user={u} last={i === shown.length - 1}
            open={menuFor === u.id}
            onOpen={() => setDetailFor(u.id)}
            onMenu={() => setMenuFor(menuFor === u.id ? null : u.id)}
            onClose={() => setMenuFor(null)}
            onToggleBlock={() => toggleBlock(u.id)}
            onNotes={() => openNotes(u)}
            onDelete={() => deleteUser(u.id)}
          />
        ))}
      </div>

      {/* Invite dialog — centered */}
      {inviteOpen && (
        <Dialog onClose={() => setInviteOpen(false)}>
          <div style={{ fontSize: 16, fontWeight: 700, color: t.ink, letterSpacing: -0.3, marginBottom: 16, textAlign: 'center' }}>新增用戶</div>
          <window.FloatingField
            label="信箱" type="email" inputMode="email" autoFocus
            value={draft} onChange={e => setDraft(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') sendInvite(); }}
            wrapperStyle={{ marginBottom: 10 }}
          />
          <window.FloatingField
            label="備註（選填）" type="text"
            value={inviteNote} onChange={e => setInviteNote(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') sendInvite(); }}
          />
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <button onClick={() => setInviteOpen(false)} style={{
              flex: 1, padding: '13px 0', borderRadius: 12,
              background: t.surfaceAlt, color: t.ink,
              border: 'none', cursor: 'pointer',
              fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
            }}>取消</button>
            <button onClick={sendInvite} disabled={!draft.trim()} style={{
              flex: 1, padding: '13px 0', borderRadius: 12,
              background: draft.trim() ? 'var(--accent)' : t.surfaceAlt,
              color: draft.trim() ? '#fff' : t.ink3,
              border: 'none', cursor: draft.trim() ? 'pointer' : 'default',
              fontFamily: 'inherit', fontSize: 15, fontWeight: 700,
            }}>確定</button>
          </div>
        </Dialog>
      )}

      {/* Notes / 備註 edit sheet */}
      {noteFor && (
        <Sheet onClose={() => setNoteFor(null)}>
          <div style={{ padding: '4px 20px 14px' }}>
            <div style={{ fontSize: 16, fontWeight: 700, color: t.ink, letterSpacing: -0.3, marginBottom: 4 }}>備註</div>
            <div style={{ fontSize: 12.5, color: t.ink3, lineHeight: 1.5, marginBottom: 14 }}>為這位成員加上備註，僅你可見。</div>
            <window.FloatingField
              label="備註" multiline rows={3} autoFocus
              value={noteDraft} onChange={e => setNoteDraft(e.target.value)}
            />
            <button onClick={saveNotes} style={{
              width: '100%', marginTop: 12, padding: '13px 0', borderRadius: 12,
              background: 'var(--accent)', color: '#fff',
              border: 'none', cursor: 'pointer',
              fontFamily: 'inherit', fontSize: 15, fontWeight: 700,
            }}>儲存</button>
          </div>
        </Sheet>
      )}
      {/* User detail — pushed page */}
      {detailForUser && (
        <UserDetail
          user={detailForUser}
          onBack={() => setDetailFor(null)}
          onToggleBlock={() => toggleBlock(detailForUser.id)}
          onEditNotes={() => openNotes(detailForUser)}
        />
      )}
    </div>
  );
}
function avatarMeta(email) {
  const t = window.flutterTokens;
  const palette = [
    [t.mint, t.mintDk], [t.coral, t.coralDk], [t.lilac, t.lilacDk],
    [t.sky, t.skyDk], [t.butter, t.butterDk], [t.rose, t.roseDk],
  ];
  let h = 0; for (const c of email) h = (h * 31 + c.charCodeAt(0)) | 0;
  const [bg, ink] = palette[Math.abs(h) % palette.length];
  const initials = (email.match(/[a-z0-9]/i) || ['?'])[0].toUpperCase();
  return { bg, ink, initials };
}

// UserDetail — pushed page showing a single member's full profile + block action.
function UserDetail({ user, onBack, onToggleBlock, onEditNotes }) {
  const t = window.flutterTokens;
  const a = avatarMeta(user.email);
  const status = user.blocked ? 'blocked' : user.status;

  const Row = ({ label, value, accent, onClick }) => (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '15px 20px', borderBottom: `1px solid ${t.hairline}`,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{ fontSize: 14, color: t.ink3, letterSpacing: -0.1, flexShrink: 0, width: 84 }}>{label}</div>
      <div style={{
        flex: 1, minWidth: 0, textAlign: 'right', fontSize: 14.5, letterSpacing: -0.1,
        color: accent || t.ink, fontWeight: accent ? 600 : 500,
      }}>{value}</div>
      {onClick && <Icon name="chevron" size={16} color={t.ink3}/>}
    </div>
  );

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 60, background: t.bg,
      display: 'flex', flexDirection: 'column',
      animation: 'pushIn 240ms cubic-bezier(.2,.7,.2,1)',
    }}>
      {/* App bar */}
      <div style={{
        padding: '60px 16px 12px', background: t.bg, flexShrink: 0,
        display: 'flex', alignItems: 'center', gap: 4,
      }}>
        <button onClick={onBack} style={{
          background: 'none', border: 'none', cursor: 'pointer',
          padding: 6, marginLeft: -6, color: t.ink, display: 'flex',
        }}>
          <Icon name="back" size={22}/>
        </button>
        <div style={{
          flex: 1, minWidth: 0, textAlign: 'center',
          fontFamily: '"Plus Jakarta Sans", "Noto Sans TC", sans-serif',
          fontSize: 18, fontWeight: 700, color: t.ink, letterSpacing: -0.4,
        }}>用戶資訊</div>
        <div style={{ width: 34 }}/>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 32 }}>
        {/* Header — avatar + email + status */}
        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          gap: 12, padding: '20px 24px 26px',
        }}>
          <div style={{
            width: 84, height: 84, borderRadius: 42, flexShrink: 0,
            background: a.bg, color: a.ink,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: '"Plus Jakarta Sans", sans-serif',
            fontWeight: 700, fontSize: 32, letterSpacing: -0.5,
            opacity: user.blocked ? 0.5 : 1,
          }}>{a.initials}</div>
          <div style={{
            fontSize: 17, fontWeight: 600, color: t.ink, letterSpacing: -0.3,
            textAlign: 'center', wordBreak: 'break-all', padding: '0 20px',
          }}>{user.email}</div>
          <StatusPill status={status}/>
        </div>

        {/* Info rows */}
        <div style={{ borderTop: `1px solid ${t.hairline}` }}>
          <Row label="最後上線" value={user.lastOnline || '—'}/>
          <Row label="註冊時間" value={user.registeredAt || '—'}/>
          <Row
            label="備註"
            value={user.notes || '新增備註'}
            accent={user.notes ? null : t.ink3}
            onClick={onEditNotes}
          />
        </div>

        {/* Block / unblock */}
        <div style={{ padding: '24px 20px 0' }}>
          <button onClick={onToggleBlock} style={{
            width: '100%', padding: '14px 0', borderRadius: 13, border: 'none', cursor: 'pointer',
            fontFamily: 'inherit', fontSize: 15, fontWeight: 700, letterSpacing: -0.2,
            background: user.blocked ? t.surfaceAlt : t.downBg,
            color: user.blocked ? t.ink : t.down,
          }}>{user.blocked ? '解除封鎖' : '封鎖用戶'}</button>
        </div>
      </div>
    </div>
  );
}

function UserRow({ user, last, open, onOpen, onMenu, onClose, onToggleBlock, onNotes, onDelete }) {
  const t = window.flutterTokens;
  const a = avatarMeta(user.email);
  const status = user.blocked ? 'blocked' : user.status;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 12px 14px 20px',
      borderBottom: last ? 'none' : `1px solid ${t.hairline}`,
      opacity: user.blocked ? 0.5 : 1,
    }}>
      {/* Avatar + identity — tap to open detail */}
      <div onClick={onOpen} style={{
        flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
      }}>
        <div style={{
          width: 42, height: 42, borderRadius: 21, flexShrink: 0,
          background: a.bg, color: a.ink,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: '"Plus Jakarta Sans", sans-serif',
          fontWeight: 700, fontSize: 16, letterSpacing: -0.3,
        }}>{a.initials}</div>

        {/* Identity — title: email, subtitle: state + remark */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 15, fontWeight: 600, color: t.ink, letterSpacing: -0.2,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{user.email}</div>
          {user.notes && (
            <div style={{
              marginTop: 3, fontSize: 12.5, letterSpacing: -0.1, color: t.ink2,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{user.notes}</div>
          )}
        </div>
      </div>

      {/* Kebab — far right */}
      <div style={{ position: 'relative', flexShrink: 0 }}>
        {open && (
          <PopMenu onClose={onClose}>
            <PopItem label={user.notes ? '編輯備註' : '新增備註'} onClick={onNotes}/>
            <PopItem label={user.blocked ? '解除封鎖' : '封鎖'} onClick={onToggleBlock}/>
            <PopItem label="刪除" danger onClick={onDelete}/>
          </PopMenu>
        )}
      </div>
    </div>
  );
}

// State text (colored dot + label) shown as the subtitle's lead
function StateText({ status }) {
  const t = window.flutterTokens;
  const map = {
    registered: { label: '已註冊', ink: t.up },
    pending:    { label: '已邀請', ink: t.ink2 },
    blocked:    { label: '已封鎖', ink: t.down },
  };
  const c = map[status] || map.pending;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', flexShrink: 0,
      color: c.ink, fontWeight: 600,
    }}>
      {c.label}
    </span>
  );
}

function PopMenu({ children, onClose }) {
  const t = window.flutterTokens;
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 40 }}/>
      <div style={{
        position: 'absolute', top: 38, right: 4, zIndex: 41,
        minWidth: 148, background: t.surface,
        borderRadius: 12, border: `1px solid ${t.hairline}`,
        boxShadow: '0 10px 28px rgba(31,27,22,0.18)',
        overflow: 'hidden', padding: '4px 0',
        animation: 'dialogIn 140ms ease',
      }}>{children}</div>
    </>
  );
}

function PopItem({ label, onClick, danger }) {
  const t = window.flutterTokens;
  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left', padding: '11px 16px',
      background: 'none', border: 'none', cursor: 'pointer',
      fontFamily: 'inherit', fontSize: 14.5, fontWeight: 500,
      color: danger ? t.down : t.ink,
    }}>{label}</button>
  );
}

function StatusPill({ status }) {
  const t = window.flutterTokens;
  const map = {
    registered: { label: '已註冊', ink: t.up,   bg: t.upBg },
    pending:    { label: '邀請中', ink: t.ink2, bg: t.surfaceAlt },
    blocked:    { label: '已封鎖', ink: t.down, bg: t.downBg },
  };
  const c = map[status] || map.pending;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: '3px 9px', borderRadius: 7,
      background: c.bg, color: c.ink,
      fontSize: 12, fontWeight: 600, letterSpacing: 0,
    }}>{c.label}</span>
  );
}

function Dialog({ children, onClose }) {
  const t = window.flutterTokens;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 50,
      background: 'rgba(31,27,22,0.32)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '24px', animation: 'fadeIn 160ms ease',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 320, background: t.surface,
        borderRadius: 20, padding: '22px 20px',
        boxShadow: '0 20px 48px rgba(31,27,22,0.24)',
        animation: 'dialogIn 200ms cubic-bezier(.2,.7,.2,1)',
      }}>{children}</div>
    </div>
  );
}

function Sheet({ children, onClose }) {
  const t = window.flutterTokens;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 50,
      background: 'rgba(31,27,22,0.32)',
      display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
      animation: 'fadeIn 160ms ease',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: t.surface,
        borderTopLeftRadius: 20, borderTopRightRadius: 20,
        padding: '16px 0 calc(16px + env(safe-area-inset-bottom))',
        animation: 'slideUp 220ms cubic-bezier(.2,.7,.2,1)',
      }}>
        <div style={{
          width: 36, height: 4, borderRadius: 2, background: t.hairline,
          margin: '0 auto 12px',
        }}/>
        {children}
      </div>
    </div>
  );
}

function SheetButton({ label, onClick, danger }) {
  const t = window.flutterTokens;
  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left', padding: '14px 24px',
      background: 'none', border: 'none', cursor: 'pointer',
      fontFamily: 'inherit', fontSize: 15.5, fontWeight: 500,
      color: danger ? t.down : t.ink,
    }}>{label}</button>
  );
}

Object.assign(window, { UserManagement });
