// LBO Play — the club shell: sign in, home, settings, admin, the club and its tables.
// Everything is inside one function so no name here replaces one of the Hand
// Viewer's (BridgeApp.jsx is loaded on the same page); only ClubApp is global.
(function () {
// Same stack as the Hand Viewer: React via in-browser Babel, Tailwind via CDN.
const CLUB_VERSION = '0.10.1';
const ACTION = '#0c80c0';

const SYSTEM_CHOICES = [['2over1', '2/1'], ['standard', 'SAYC'], ['acol', 'Acol']];
const ACE_CHOICES = [['blackwood', 'Blackwood'], ['rkcb1430', 'RKCB 1430']];
// Friends (the Profile list, + Friend, the Friends filter, friends under Invite players). Hidden
// for now; set to true to bring them all back.
const SHOW_FRIENDS = false;
const SEAT_CHOICES = [['N', 'North'], ['E', 'East'], ['S', 'South'], ['W', 'West']];

// ---- chat ----
// A room's messages: 'club' (the club's room) or 'table' (the table this player is at).
// Fetched again when the live connection says that room has something new (and every 30 s).
function useChat(which, enabled, key) {
  const [messages, setMessages] = React.useState(null);
  const [error, setError] = React.useState('');
  const load = React.useCallback(() => api('GET', '/api/chat?room=' + which).then((r) => setMessages(r.messages)).catch(() => {}), [which]);
  React.useEffect(() => {
    setMessages(null);
    if (!enabled) return undefined;
    load();
    const on = (e) => { if (e.detail === which) load(); };
    window.addEventListener('lbo-chat', on);
    const poll = setInterval(load, 30000);
    return () => { window.removeEventListener('lbo-chat', on); clearInterval(poll); };
  }, [which, enabled, key, load]);
  const send = async (body, parentId) => {
    setError('');
    try {
      const r = await api('POST', '/api/chat', { room: which, body, parentId: parentId || undefined });
      setMessages((m) => (m || []).filter((x) => x.id !== r.message.id).concat(r.message));
      return true;
    } catch (e) { setError(errorText(e.message)); return false; }
  };
  const remove = async (id) => {
    setError('');
    try { await api('DELETE', '/api/chat/' + id, {}); load(); } catch (e) { setError(errorText(e.message)); }
  };
  return { messages: messages || [], loaded: !!messages, send, remove, error };
}

// How many messages from other people arrived since the chat was last on screen.
function useUnread(chat, userId, showing) {
  const seen = React.useRef(null);
  const maxId = chat.messages.reduce((n, m) => Math.max(n, m.id), 0);
  if (chat.loaded && (seen.current === null || showing)) seen.current = maxId;
  return seen.current === null ? 0 : chat.messages.filter((m) => m.id > seen.current && m.userId !== userId).length;
}

const chatTime = (iso) => { try { return new Date(iso).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); } catch (e) { return ''; } };

// The box for writing a message. Enter sends, Shift+Enter starts a new line (not while an
// input method is still composing, as when typing Japanese).
function ChatComposer({ onSend, placeholder, label, autoFocus, onCancel, compact }) {
  const [text, setText] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const box = React.useRef(null);
  React.useEffect(() => { if (autoFocus && box.current) box.current.focus(); }, [autoFocus]);
  React.useLayoutEffect(() => {
    const el = box.current; if (!el) return;
    el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 112) + 'px';
  }, [text]);
  const submit = async () => {
    if (!text.trim() || busy) return;
    setBusy(true);
    const ok = await onSend(text);
    setBusy(false);
    if (ok) { setText(''); if (box.current) box.current.focus(); }
  };
  return (
    <form className="flex items-end gap-2" onSubmit={(e) => { e.preventDefault(); submit(); }}>
      <textarea ref={box} rows={1} maxLength={500} value={text} aria-label={label || placeholder} placeholder={placeholder}
        className={'flex-1 min-w-0 resize-none rounded-lg border border-gray-400 px-3 py-2 text-base leading-snug ' + (compact ? 'min-h-[40px]' : 'min-h-[44px]')}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) { e.preventDefault(); submit(); }
          if (e.key === 'Escape' && onCancel) onCancel();
        }} />
      {onCancel && <button type="button" onClick={onCancel} className={(compact ? 'h-10' : 'h-11') + ' px-3 rounded-lg border border-gray-400 bg-white text-sm'}>Cancel</button>}
      <button type="submit" disabled={!text.trim() || busy} className={(compact ? 'h-10' : 'h-11') + ' px-4 rounded-lg font-semibold text-white disabled:opacity-50'} style={{ background: ACTION }}>Send</button>
      {text.length > 400 && <span className="sr-only" role="status">{500 - text.length} characters left</span>}
    </form>
  );
}

// One message: who, when, what. The writer (or an admin) can delete it.
function ChatLine({ m, user, onDelete, reply }) {
  const mine = m.userId === user.id;
  return (
    <div className={'group flex flex-col ' + (reply ? 'pl-3 border-l-2 border-gray-200' : '')}>
      <div className="flex items-baseline gap-2 text-[13px] text-gray-600">
        <span className="font-semibold text-gray-900 text-sm">{mine ? 'You' : m.username}</span>
        <span>{chatTime(m.at)}</span>
        {m.kib && <span className="italic">to kibitzers</span>}
        {(mine || user.role === 'admin') && (
          <button type="button" className="ml-auto text-[13px] underline text-gray-500 hover:text-red-700"
            onClick={() => { if (window.confirm(m.parentId || reply ? 'Delete this message?' : 'Delete this message and its replies?')) onDelete(m.id); }}>Delete</button>
        )}
      </div>
      <div className="text-[15px] text-gray-900 whitespace-pre-wrap break-words">{m.body}</div>
    </div>
  );
}

// A chat room. Threaded (the club's room): each first message with its replies under it and a
// Reply link; flat (a table): one conversation.
function ChatPanel({ chat, user, threaded, listClass, placeholder, note, compact }) {
  const list = React.useRef(null);
  const [replyTo, setReplyTo] = React.useState(null);
  const [open, setOpen] = React.useState({});              // threads showing all their replies
  const last = chat.messages.length ? chat.messages[chat.messages.length - 1].id : 0;
  const near = React.useRef(true);
  React.useLayoutEffect(() => {                             // stay at the newest message unless the reader scrolled up
    const el = list.current;
    if (el && near.current && !replyTo) el.scrollTop = el.scrollHeight;
  }, [last, chat.loaded]);
  const onScroll = () => { const el = list.current; if (el) near.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40; };

  let body;
  if (!chat.loaded) body = <div className="text-sm text-gray-600">Loading…</div>;
  else if (!chat.messages.length) body = <div className="text-sm text-gray-600">No messages yet. Say hello!</div>;
  else if (!threaded) body = chat.messages.map((m) => <ChatLine key={m.id} m={m} user={user} onDelete={chat.remove} />);
  else {
    const threads = [], byId = {};
    chat.messages.forEach((m) => { if (!m.parentId) { const th = { first: m, replies: [], last: m.at }; byId[m.id] = th; threads.push(th); } });
    chat.messages.forEach((m) => { const th = m.parentId && byId[m.parentId]; if (th) { th.replies.push(m); if (m.at > th.last) th.last = m.at; } });
    threads.sort((a, b) => (a.last < b.last ? -1 : a.last > b.last ? 1 : a.first.id - b.first.id));
    body = threads.map((th) => {
      const id = th.first.id, all = !!open[id], hidden = all ? 0 : Math.max(0, th.replies.length - 3);
      return (
        <div key={id} className="flex flex-col gap-1.5 pb-3 border-b border-gray-100 last:border-b-0">
          <ChatLine m={th.first} user={user} onDelete={chat.remove} />
          {hidden > 0 && (
            <button type="button" className="self-start pl-3 text-[13px] underline" style={{ color: ACTION }} onClick={() => setOpen(Object.assign({}, open, { [id]: true }))}>
              Show {hidden} earlier {hidden === 1 ? 'reply' : 'replies'}</button>
          )}
          {th.replies.slice(hidden).map((r) => <ChatLine key={r.id} m={r} user={user} onDelete={chat.remove} reply />)}
          {replyTo === id
            ? <div className="pl-3"><ChatComposer compact autoFocus placeholder={'Reply to ' + (th.first.userId === user.id ? 'your message' : th.first.username)}
                onCancel={() => setReplyTo(null)} onSend={async (text) => { const ok = await chat.send(text, id); if (ok) setReplyTo(null); return ok; }} /></div>
            : <button type="button" className="self-start pl-3 text-[13px] font-semibold" style={{ color: ACTION }} onClick={() => setReplyTo(id)}>Reply</button>}
        </div>
      );
    });
  }
  return (
    <div className="flex flex-col gap-2 min-h-0">
      <div ref={list} onScroll={onScroll} className={'overflow-y-auto flex flex-col gap-2 pr-1 ' + (listClass || 'max-h-[50vh]')} aria-live="polite">{body}</div>
      {chat.error && <div role="alert" className="text-sm text-red-700">{chat.error}</div>}
      <ChatComposer compact={compact} placeholder={placeholder || (threaded ? 'Start a new conversation' : 'Message the table')} onSend={(text) => chat.send(text)} />
      {note && <div className="text-[13px] text-gray-600">{note}</div>}
    </div>
  );
}

const ERROR_TEXT = {
  wrong_password: 'That password is not right.',
  not_invited: 'That email address is not on the invited list yet.',
  username_required: 'Choose a username of 3 to 20 characters (letters, numbers, spaces, _ or -).',
  username_invalid: 'Usernames are 3 to 20 characters: letters, numbers, spaces, _ or -.',
  username_taken: 'That username is taken. Please choose another.',
  too_many_attempts: 'Too many attempts. Please wait 15 minutes and try again.',
  sign_in_not_configured: 'Sign-in is not switched on yet.',
  bad_request: 'Please enter your email address and the password.',
  not_signed_in: 'Please sign in again.',
  seat_taken: 'Someone just took that seat.',
  private_table: 'That table is private. Ask to join.',
  table_full: 'That table has no more room for kibitzers.',
  table_not_found: 'That table has closed.',
  host_only: 'Only the host can do that.',
  hand_in_progress: 'A hand is being played. Try again when it ends.',
  not_your_turn: 'It is not your turn.',
  not_your_call: 'You can only change the alerts on your own calls.',
  claim_pending: 'A claim is waiting for an answer.',
  illegal_call: 'That call is not allowed here.',
  illegal_card: 'That card cannot be played now.',
  waiting_for_host: 'Waiting for the host: a seat is empty.',
  empty_seats: 'There are empty seats.',
  already_here: 'That player is already at your table.',
  user_not_found: 'That player was not found.',
  password_too_short: 'Use at least 8 characters, with no space at the start or end.',
  empty_message: 'Type a message first.',
  message_too_long: 'Messages can be up to 500 characters.',
  slow_down: 'Please wait a moment before sending more messages.',
  not_at_table: 'You are no longer at that table.',
  thread_gone: 'That conversation has been removed.',
  not_yours: 'You can only delete your own messages.',
  blocked_word: 'That contains a word that is not allowed here. Please rephrase.',
  username_not_allowed: 'That username is not allowed. Please choose another.',
  blocked: 'This account has been blocked. Please contact hello@learnbridgeonline.com.',
  link_expired: 'That link has expired. Please go back to learnbridgeonline.com and open Play again.',
  cannot_block_yourself: 'You cannot block yourself.',
  title_required: 'Please give it a title.',
  nothing_to_save: 'There is nothing to save yet.',
  too_many_saved: 'You have reached the limit of saved hands and sets. Delete some first.',
  teachers_only: 'The Hand Creator is for teachers.'
};
const errorText = (code) => ERROR_TEXT[code] || 'Something went wrong. Please try again.';

async function api(method, url, body) {
  let res;
  try {
    res = await fetch(url, { method, credentials: 'same-origin',
      headers: body ? { 'Content-Type': 'application/json' } : {},
      body: body ? JSON.stringify(body) : undefined });
  } catch (e) { throw new Error('network'); }
  let data = {};
  try { data = await res.json(); } catch (e) {}
  if (!res.ok) throw new Error(data.error || 'server_error');
  return data;
}

function Panel({ children, className }) {
  return <div className={'bg-white rounded-xl shadow p-6 ' + (className || '')}>{children}</div>;
}
function Choice({ options, value, onChange, label }) {
  return (
    <div>
      <div className="text-base font-semibold mb-2">{label}</div>
      <div className="flex gap-2">
        {options.map(([id, text]) => (
          <button key={id} type="button" onClick={() => onChange(id)} aria-pressed={value === id}
            className={'flex-1 h-11 rounded-lg border text-[15px] ' +
              (value === id ? 'border-2 border-sky-700 bg-sky-50 font-semibold' : 'border-gray-400 bg-white')}>
            {text}
          </button>
        ))}
      </div>
    </div>
  );
}
function ActionButton({ children, onClick, type, disabled, outline }) {
  const style = outline ? { borderColor: ACTION, color: ACTION } : { background: ACTION, borderColor: ACTION, color: '#fff' };
  return (
    <button type={type || 'button'} onClick={onClick} disabled={disabled} style={style}
      className="h-11 px-5 rounded-lg border font-semibold text-base disabled:opacity-50">{children}</button>
  );
}

const SYSTEM_NAME = { '2over1': '2/1', standard: 'SAYC', acol: 'Acol' };
const ACE_NAME = { blackwood: 'Blackwood', rkcb1430: 'RKCB 1430' };
const SEAT_NAME = { N: 'North', E: 'East', S: 'South', W: 'West' };
const SEAT_ORDER = ['N', 'E', 'S', 'W'];
const tableLine = (t) => SYSTEM_NAME[t.system] + ' · ' + ACE_NAME[t.aceAsking];

function PersonIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#1f2937" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx="12" cy="8" r="4" /><path d="M4 21c0-4 3.6-7 8-7s8 3 8 7" />
    </svg>
  );
}

function CogIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#1f2937" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  );
}

// The deal, contract and tricks in the middle of the header, as in the Hand
// Viewer's play screen. The contract opens the auction; the trick count opens
// the last trick.
function GameHeading({ g, review, setReview, kibitzing }) {
  const vulNS = g.vul === 'b' || g.vul === 'e', vulEW = g.vul === 'b' || g.vul === 'o';
  const c = g.contract;
  const declVul = c && (g.declarer === 'N' || g.declarer === 'S' ? vulNS : vulEW);
  const chip = (side, n, vul) => (
    <span className={'px-1.5 sm:px-2.5 py-0.5 rounded ' + (vul ? 'bg-red-100 text-red-700' : 'bg-slate-100 text-slate-700')}
      title={vul ? side + ' vulnerable' : side + ' not vulnerable'}>{side}{n === null ? '' : ': '}{n !== null && <span className="font-bold">{n}</span>}</span>
  );
  const tricksShown = g.phase === 'play' || (g.phase === 'summary' && c);
  return (
    <div className="flex-1 min-w-0 flex items-center justify-center gap-1.5 sm:gap-3 font-serif whitespace-nowrap overflow-hidden">
      <span className="text-slate-400 text-base sm:text-xl font-medium shrink-0"><span className="hidden sm:inline">Deal </span>{g.board}:</span>
      {c ? (
        <button type="button" title="Show the auction" aria-pressed={review === 'auction'} className="text-base sm:text-xl font-bold hover:opacity-80 min-w-0 truncate"
          onClick={() => setReview(review === 'auction' ? null : 'auction')}>
          <span style={{ color: RED[c.suit] ? '#c81e1e' : '#333' }}>{c.level}{SUIT_SYM[c.suit]}</span>
          {c.doubled && <span className="text-red-600 ml-1">X</span>}{c.redoubled && <span className="text-blue-600 ml-1">XX</span>}
          <span className="text-slate-600 ml-1 sm:ml-2">by {g.declarer}</span>
          {declVul && <span className="text-red-600 ml-1 text-sm hidden sm:inline">(Vul)</span>}
        </button>
      ) : (
        <span className="text-sm sm:text-lg text-slate-600">{g.phase === 'bidding' ? 'Dealer ' + g.dealer : 'Passed out'}</span>
      )}
      {tricksShown ? (
        <button type="button" title="Show the last trick" aria-pressed={review === 'last'} disabled={!g.lastTrick || g.phase !== 'play'}
          className="flex items-center gap-1 sm:gap-2 text-sm sm:text-lg hover:opacity-80 shrink-0" onClick={() => setReview(review === 'last' ? null : 'last')}>
          {chip('NS', g.tricks.NS, vulNS)}{chip('EW', g.tricks.EW, vulEW)}
        </button>
      ) : (
        <span className="flex items-center gap-1 sm:gap-2 text-sm sm:text-lg shrink-0">{chip('NS', null, vulNS)}{chip('EW', null, vulEW)}</span>
      )}
      {kibitzing && <span className="hidden sm:inline text-sm text-slate-500 font-sans">Kibitzing</span>}
    </div>
  );
}

// The header: the logo (Home) on the left, the hand in the middle at a table,
// and one menu on the right. The menu opens over the table and closes on a
// choice, a click anywhere else, or Escape.
const MEMBERS_URL = 'https://learnbridgeonline.com/members';
const isTeacher = (u) => !!u && (u.role === 'teacher' || u.role === 'admin');
const HAND_VIEWER = 'https://hand.learnbridgeonline.com';
// ---- The page frame: top bar, left sidebar, page area ----
const SERIF = "'EB Garamond', Georgia, 'Times New Roman', serif";
const NAV_PATHS = {
  home: ['M3 11l9-8 9 8', 'M5 10v10h14V10'],
  club: ['M3 9h18', 'M5 9v10', 'M19 9v10', 'M9 9v6h6V9'],
  practice: ['M8 5v14l11-7z'],
  creator: ['M12 20h9', 'M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z'],
  settings: ['M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z', 'M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-2.9-1.2l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0-1.2-2.9H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.2-2.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 2.9-1.2V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 2.9 1.2l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0 1.2 2.9h.1a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.6 1z'],
  admin: ['M12 3l8 3v6c0 4.5-3.2 8.2-8 9-4.8-.8-8-4.5-8-9V6z'],
  back: ['M15 18l-6-6 6-6'],
  activity: ['M3 12h4l3 8 4-16 3 8h4'],
  users: ['M9 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8z', 'M2 21c0-4 3-6 7-6s7 2 7 6', 'M17 4a4 4 0 0 1 0 8', 'M22 21c0-3-2-5-4-6'],
  hands: ['M3 7h6l2 2h10v10H3z'],
  chat: ['M4 5h16v11H9l-5 4z'],
  words: ['M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z', 'M6 6l12 12'],
  menu: ['M4 6h16M4 12h16M4 18h16'],
  exit: ['M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4', 'M16 17l5-5-5-5', 'M21 12H9'],
  signout: ['M16 17l5-5-5-5', 'M21 12H9', 'M12 19H5V5h7'],
  collapse: ['M11 17l-5-5 5-5', 'M18 17l-5-5 5-5'],
  expand: ['M13 17l5-5-5-5', 'M6 17l5-5-5-5'],
};
function NavIcon({ k, color, size }) {
  return (
    <svg width={size || 20} height={size || 20} viewBox="0 0 24 24" fill="none" stroke={color || '#334155'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      {(NAV_PATHS[k] || []).map((d, i) => <path key={i} d={d} />)}
    </svg>
  );
}

// The top bar, the same on every page: the logo opens and closes the sidebar. During a hand the
// deal's heading sits beside it.
const TOP_H = 56;
function TopBar({ onLogo, sideShown, middle, slim, right }) {
  const { vw } = useScreenSize();
  return (
    <div className="shrink-0 bg-white border-b border-gray-300 flex items-center gap-2 sm:gap-3 px-2 sm:px-5 relative z-40" style={{ height: slim ? 44 : TOP_H, fontFamily: SERIF }}>
      <LogoButton onClick={onLogo} open={sideShown} height={slim ? 28 : vw < 360 ? 28 : 34} />
      {middle || <div className="flex-1" />}
      {right}
    </div>
  );
}
function LogoButton({ onClick, open, height }) {
  return (
    <button type="button" onClick={onClick} aria-label={open ? 'Close the menu' : 'Open the menu'} aria-expanded={!!open} title="Menu"
      className="flex items-center h-11 shrink-0 rounded-lg hover:opacity-80">
      <img src="/club/logo-text.png" alt="Learn Bridge Online" style={{ height: height || 34 }} />
    </button>
  );
}

// The left sidebar: its items (Home first), or a section's own items under "‹ Home"; the site's
// links at the bottom.
function SideBar({ items, active, onPick, back, heading, children, footer, width, collapse, account }) {
  return (
    <nav aria-label={heading || 'Sections'} className="h-full bg-white border-r border-gray-300 flex flex-col min-h-0" style={{ width: width || 248, fontFamily: SERIF }}>
      <div className="shrink-0 flex flex-col gap-1 p-3">
        {back && (
          <div className="flex items-center justify-between">
            <button type="button" onClick={back.onClick} className="h-10 px-2 flex items-center gap-2 text-[17px] rounded-lg hover:bg-gray-100" style={{ color: '#0a6ea6' }}>
              <NavIcon k="back" color="#0a6ea6" size={18} /> {back.label}
            </button>
            {collapse && (
              <button type="button" onClick={collapse} aria-label="Close the sidebar" title="Close the sidebar" className="w-10 h-10 rounded-lg flex items-center justify-center hover:bg-gray-100">
                <NavIcon k="collapse" color="#475569" size={18} />
              </button>
            )}
          </div>
        )}
        {heading && back && <div className="px-3 pt-1 pb-2 text-[24px] font-semibold text-gray-900">{heading}</div>}
        {items.map((it) => {
          const on = it.id === active;
          return (
            <button key={it.id} type="button" onClick={() => onPick(it)} aria-current={on ? 'page' : undefined}
              className={'h-11 px-3 flex items-center gap-3 rounded-lg text-left text-[17px] ' + (on ? 'bg-sky-100 font-semibold text-gray-900' : 'text-gray-900 hover:bg-gray-100')}>
              {it.cr ? crIcon(it.cr, on ? '#075985' : undefined) : <NavIcon k={it.icon} color={on ? '#075985' : '#334155'} />}
              <span className="flex-1 truncate">{it.label}</span>
              {it.badge}
            </button>
          );
        })}
      </div>
      <div className="flex-1 min-h-0 flex flex-col">{children}</div>
      {account && <AccountLinks {...account} />}
      {footer !== false && <SiteLinks />}
    </nav>
  );
}

// The bottom of every sidebar: who is signed in, Exit to Members' Page, Log out.
function AccountLinks({ user, onSignOut, leaveSite }) {
  const row = 'h-10 px-3 flex items-center gap-3 rounded-lg text-left text-[17px] text-gray-900 hover:bg-gray-100';
  return (
    <div className="shrink-0 px-3 py-2 border-t border-gray-200 flex flex-col gap-0.5">
      <div className="px-3 pb-1 text-[14px] text-gray-600 truncate">Signed in as {user.username}</div>
      <button type="button" className={row} onClick={() => leaveSite(MEMBERS_URL)}><NavIcon k="exit" /> Exit to Members' Page</button>
      <button type="button" className={row} onClick={onSignOut}><NavIcon k="signout" /> Log out</button>
    </div>
  );
}

function SiteLinks() {
  return (
    <div className="shrink-0 px-5 py-4 border-t border-gray-200 flex flex-col gap-1 text-[15px] text-gray-700">
      <a href="https://learnbridgeonline.com" className="underline" style={{ color: '#1d4f7a' }}>learnbridgeonline.com</a>
      <a href="mailto:hello@learnbridgeonline.com" className="underline" style={{ color: '#1d4f7a' }}>Contact us</a>
      <span className="text-[13px] text-gray-600 pt-1">© Learn Bridge Online by Brooklyn Little, LLC</span>
    </div>
  );
}

// A page: one width (max 1200px), from the top; the title, a line under it and the page's main
// action on the right.
function Page({ title, sub, action, children }) {
  return (
    <div className="px-4 sm:px-10 pt-6 sm:pt-8 pb-10">
      <div className="max-w-[1200px] mx-auto flex flex-col gap-5">
        {title && (
          <div className="flex flex-wrap items-end justify-between gap-3">
            <div className="min-w-0">
              <h1 className="m-0 text-[2rem] leading-tight font-semibold text-gray-900">{title}</h1>
              {sub && <div className="text-[17px] text-gray-700">{sub}</div>}
            </div>
            {action && <div className="flex flex-wrap items-center gap-2">{action}</div>}
          </div>
        )}
        {children}
      </div>
    </div>
  );
}

function RequestAccess({ email, username }) {
  const [open, setOpen] = React.useState(false);
  const [mail, setMail] = React.useState(email);
  const [name, setName] = React.useState(username);
  const [note, setNote] = React.useState('');
  const [state, setState] = React.useState('');
  const input = 'h-11 w-full rounded-lg border border-gray-400 px-3 text-base';
  const send = async (e) => {
    e.preventDefault(); setState('sending');
    try { await api('POST', '/api/access-request', { email: mail, username: name, note }); setState('sent'); }
    catch (err) { setState(err.message === 'bad_email' ? 'Please enter your email address.' : errorText(err.message)); }
  };
  if (state === 'sent') return <div role="status" className="text-sm text-green-800 bg-green-50 border border-green-700 rounded-lg p-3">Request sent. We will be in touch once it has been reviewed.</div>;
  if (!open) {
    return (
      <div className="text-sm bg-gray-50 border border-gray-300 rounded-lg p-3 flex flex-col gap-2">
        <span>Don't have access yet, or don't know the password?</span>
        <ActionButton outline onClick={() => setOpen(true)}>Request access</ActionButton>
      </div>
    );
  }
  return (
    <form onSubmit={send} className="bg-gray-50 border border-gray-300 rounded-lg p-3 flex flex-col gap-3">
      <strong>Request access</strong>
      <div><label htmlFor="ra-email" className="block text-sm font-semibold mb-1">Email address</label>
        <input id="ra-email" type="email" required className={input} value={mail} onChange={(e) => setMail(e.target.value)} /></div>
      <div><label htmlFor="ra-name" className="block text-sm font-semibold mb-1">Username you would like</label>
        <input id="ra-name" className={input} value={name} maxLength={20} onChange={(e) => setName(e.target.value)} /></div>
      <div><label htmlFor="ra-note" className="block text-sm font-semibold mb-1">A note for us (optional)</label>
        <input id="ra-note" className={input} value={note} maxLength={300} onChange={(e) => setNote(e.target.value)} /></div>
      {state && state !== 'sending' && <div role="alert" className="text-sm text-red-700">{state}</div>}
      <ActionButton type="submit" disabled={state === 'sending'}>{state === 'sending' ? 'Sending…' : 'Send request'}</ActionButton>
    </form>
  );
}

const WP_NOTE = {
  expired: 'That link has expired. Please go back to learnbridgeonline.com and open Play again.',
  invalid: 'That link did not work. Please go back to learnbridgeonline.com and open Play again.',
  blocked: 'This account has been blocked. Please contact hello@learnbridgeonline.com.',
  off: 'Signing in from learnbridgeonline.com is not switched on yet.'
};
function SignIn({ onSignedIn, wpNote }) {
  let been = false;
  try { been = localStorage.getItem('lbo.play.signedInBefore') === '1'; } catch (e) {}
  const [mode, setMode] = React.useState(been ? 'returning' : 'first');
  const [username, setUsername] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState(WP_NOTE[wpNote] || '');
  const [offer, setOffer] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setError(''); setOffer(false);
    try {
      const r = await api('POST', '/api/login', mode === 'first' ? { email, password, username } : { email, password });
      try { localStorage.setItem('lbo.play.signedInBefore', '1'); } catch (e2) {}
      onSignedIn(r.user);
    } catch (err) {
      if (err.message === 'username_required' && mode === 'returning') {
        setMode('first'); setError('This is your first time signing in: please choose a username.');
      } else {
        setError(errorText(err.message));
        if (err.message === 'wrong_password' || err.message === 'not_invited') setOffer(true);
      }
    }
    setBusy(false);
  };
  const input = 'h-11 w-full rounded-lg border border-gray-400 px-3 text-base';
  return (
    <div className="lbo-wash min-h-screen flex flex-col items-center justify-center p-4 gap-5">
      <div className="text-center">
        <div className="text-2xl font-bold" style={{ color: '#1d4f7a' }}>Learn Bridge Online</div>
        <div className="text-gray-700">Play bridge with friends and robots</div>
      </div>
      <Panel className="w-full max-w-sm">
        <form onSubmit={submit} className="flex flex-col gap-4">
          <h1 className="text-2xl font-bold m-0">Sign in</h1>
          <Choice label="Have you signed in here before?" options={[['returning', 'Returning'], ['first', 'First time']]} value={mode} onChange={setMode} />
          {mode === 'first' && (
            <div>
              <label htmlFor="si-user" className="block text-sm font-semibold mb-1">Username</label>
              <input id="si-user" className={input} value={username} maxLength={20} autoComplete="nickname"
                onChange={(e) => setUsername(e.target.value)} />
              <div className="text-[13px] text-gray-600 mt-1">Your username is public and can be changed later.</div>
            </div>
          )}
          <div>
            <label htmlFor="si-email" className="block text-sm font-semibold mb-1">Email address</label>
            <input id="si-email" type="email" required className={input} value={email} autoComplete="email"
              onChange={(e) => setEmail(e.target.value)} />
            <div className="text-[13px] text-gray-600 mt-1">Your email is never shown to other players.</div>
          </div>
          <div>
            <label htmlFor="si-pass" className="block text-sm font-semibold mb-1">Password</label>
            <input id="si-pass" type="password" required className={input} value={password} autoComplete="current-password"
              onChange={(e) => setPassword(e.target.value)} />
          </div>
          {error && <div role="alert" className="text-sm text-red-700">{error}</div>}
          <ActionButton type="submit" disabled={busy}>{busy ? 'Signing in…' : 'Sign in'}</ActionButton>
        </form>
        {offer && <div className="mt-4"><RequestAccess email={email} username={username} /></div>}
      </Panel>
      <div className="text-xs text-gray-700">v{CLUB_VERSION}</div>
    </div>
  );
}

// A member arriving from WordPress for the first time: no password, only a username to choose.
function WelcomeFromWp({ token, onSignedIn }) {
  const [username, setUsername] = React.useState('');
  const [error, setError] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const submit = async (e) => {
    e.preventDefault(); setBusy(true); setError('');
    try {
      const r = await api('POST', '/api/wp-complete', { token, username });
      try { localStorage.setItem('lbo.play.signedInBefore', '1'); } catch (e2) {}
      onSignedIn(r.user);
    } catch (err) { setError(errorText(err.message)); }
    setBusy(false);
  };
  return (
    <div className="lbo-wash min-h-screen flex flex-col items-center justify-center p-4 gap-5">
      <div className="text-center">
        <div className="text-2xl font-bold" style={{ color: '#1d4f7a' }}>Learn Bridge Online</div>
        <div className="text-gray-700">Play bridge with friends and robots</div>
      </div>
      <Panel className="w-full max-w-sm">
        <form onSubmit={submit} className="flex flex-col gap-4">
          <h1 className="text-2xl font-bold m-0">Welcome, partner!</h1>
          <div className="text-[15px]">You are signed in from learnbridgeonline.com. Choose the name other players will see.</div>
          <div>
            <label htmlFor="wp-user" className="block text-sm font-semibold mb-1">Username</label>
            <input id="wp-user" className="h-11 w-full rounded-lg border border-gray-400 px-3 text-base" value={username} maxLength={20} autoComplete="nickname" autoFocus
              onChange={(e) => setUsername(e.target.value)} />
            <div className="text-[13px] text-gray-600 mt-1">3 to 20 characters. Your username is public and can be changed later. Your email is never shown.</div>
          </div>
          {error && <div role="alert" className="text-sm text-red-700">{error}</div>}
          <ActionButton type="submit" disabled={busy || username.trim().length < 3}>{busy ? 'One moment…' : 'Start playing'}</ActionButton>
        </form>
      </Panel>
    </div>
  );
}

function Home({ go, myTable, user, onFriends }) {
  const card = 'bg-white border border-gray-300 rounded-xl p-5 flex flex-col gap-3';
  return (
    <Page title={'Welcome, ' + user.username} sub="What would you like to do today?">
      {myTable && (
        <div className="bg-white border border-gray-300 rounded-xl px-5 py-3 flex flex-wrap items-center justify-between gap-3 text-[17px]">
          <span>You are at <b>{myTable.hostName}'s table</b>{myTable.game && myTable.game.phase !== 'summary' ? ', and a hand is being played' : ''}.</span>
          <ActionButton onClick={() => go('club')}>Return to Table</ActionButton>
        </div>
      )}
      <div className={'grid grid-cols-1 sm:grid-cols-2 gap-5 ' + (isTeacher(user) ? 'lg:grid-cols-3' : '')}>
        <div className={card}>
          <h2 className="text-[1.4rem] font-semibold m-0">Play with Friends</h2>
          <p className="text-[17px] text-gray-700 m-0 flex-1">Sit at an open table or create your own, and invite your friends. Robots fill empty seats.</p>
          <ActionButton onClick={onFriends}>Find a table</ActionButton>
        </div>
        <div className={card}>
          <h2 className="text-[1.4rem] font-semibold m-0">Practice</h2>
          <p className="text-[17px] text-gray-700 m-0 flex-1">On your own, with robots. Random hands, bid with your system.</p>
          <ActionButton onClick={() => go('practice')}>Play random hands</ActionButton>
        </div>
        {isTeacher(user) && (
          <div className={card}>
            <h2 className="text-[1.4rem] font-semibold m-0">Hand Creator</h2>
            <p className="text-[17px] text-gray-700 m-0 flex-1">For teachers: enter hands, program the bidding and play, save them to your account and share them with students.</p>
            <ActionButton onClick={() => go('creator')}>Open the Hand Creator</ActionButton>
          </div>
        )}
      </div>
    </Page>
  );
}

// Practice: the robots' bidding (the same choices as in Settings), then random hands in the Hand
// Viewer, which starts on the first deal (a one-time note in sessionStorage says so).
function Practice({ user, onUser }) {
  const [note, setNote] = React.useState('');
  const set = (key) => async (value) => {
    setNote('');
    try { const r = await api('PUT', '/api/me', { settings: { [key]: value } }); onUser(r.user); }
    catch (err) { setNote(errorText(err.message)); }
  };
  const s = user.settings;
  return (
    <Page title="Practice" sub="Random hands against the robots. You sit South."
      action={<ActionButton onClick={() => { try { sessionStorage.setItem('lbo.autoRandom', '1'); } catch (e) {} location.href = '/play'; }}>Play random hands</ActionButton>}>
      <div className="bg-white border border-gray-300 rounded-xl p-5 flex flex-col gap-4 max-w-xl">
        <h2 className="text-[1.4rem] font-semibold m-0">How the robots bid</h2>
        <Choice label="Bidding system" options={SYSTEM_CHOICES} value={s.biddingSystem} onChange={set('biddingSystem')} />
        <Choice label="Ace asking" options={ACE_CHOICES} value={s.aceAsking} onChange={set('aceAsking')} />
        <div role="status" className="text-[15px] text-gray-600">{note || 'The same choices as in Settings.'}</div>
      </div>
    </Page>
  );
}

// ---- Hand Creator (teachers and admins) ----
// The Hand Viewer's editor runs in a frame (/hand-creator/app), exactly as on its own site. This
// page reads the hands being worked on from it and saves them to the teacher's account.
const creatorDirty = { current: false };              // unsaved changes? (asked before leaving the page)
// The whole piece of work in the frame as the Hand Viewer's set text, and how many cards it holds.
function creatorWork(w) {
  try {
    const st = w && w.LBO_HV_STATE;
    if (!st || !st.mode || typeof w.encodeHandSet !== 'function') return null;
    const build = st.mode === 'editor2' && st.editorDataRef && typeof st.editorDataRef.current === 'function' ? st.editorDataRef.current : null;
    const cur = build ? build() : null;
    let hands;
    if (st.handSet && st.handSet.length) {
      hands = st.handSet.slice();
      if (st.viewingUnsaved) { const extra = cur || st.unsavedHand; if (extra) hands.push(extra); }
      else if (cur && hands[st.handIndex]) hands[st.handIndex] = Object.assign({}, hands[st.handIndex], cur);
      else if (st.unsavedHand) hands.push(st.unsavedHand);
    } else hands = [cur || st.handData].filter(Boolean);
    const count = (h) => ['north', 'east', 'south', 'west'].reduce((n, k) => n + ['s', 'h', 'd', 'c'].reduce((m, x) => m + ((h[k] && h[k][x]) || []).length, 0), 0);
    hands = hands.filter((h) => h && count(h) > 0);
    if (!hands.length) return { data: '', hands: 0 };
    return { data: w.encodeHandSet(hands), hands: hands.length };
  } catch (e) { return null; }
}
const kindText = (n) => (n > 1 ? 'Set of ' + n + ' hands' : 'Hand');

function TitleDialog({ heading, initial, action, onCancel, onDone, note }) {
  const [title, setTitle] = React.useState(initial || '');
  const [error, setError] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const submit = async (e) => {
    e.preventDefault(); setBusy(true); setError('');
    try { await onDone(title.trim()); } catch (err) { setError(errorText(err.message)); setBusy(false); }
  };
  return (
    <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-3" role="dialog" aria-modal="true" aria-label={heading}>
      <Panel className="w-full max-w-sm">
        <form onSubmit={submit} className="flex flex-col gap-3">
          <h2 className="text-xl font-bold m-0">{heading}</h2>
          <label htmlFor="cr-title" className="text-sm font-semibold">Title</label>
          <input id="cr-title" autoFocus maxLength={80} className="h-11 w-full rounded-lg border border-gray-400 px-3 text-base" value={title} onChange={(e) => setTitle(e.target.value)} />
          {note && <div className="text-[13px] text-gray-600">{note}</div>}
          {error && <div role="alert" className="text-sm text-red-700">{error}</div>}
          <div className="flex gap-2 justify-end">
            <button type="button" className="h-11 px-4 rounded-lg border border-gray-400" onClick={onCancel}>Cancel</button>
            <ActionButton type="submit" disabled={busy || !title.trim()}>{action}</ActionButton>
          </div>
        </form>
      </Panel>
    </div>
  );
}

// Close a small menu on a click elsewhere or Escape, in whichever document it is drawn (the
// Hand Creator draws some inside the editor's frame).
function useDismiss(open, setOpen, box) {
  React.useEffect(() => {
    if (!open) return undefined;
    const doc = (box.current && box.current.ownerDocument) || document;
    const away = (e) => { if (box.current && !box.current.contains(e.target)) setOpen(false); };
    const esc = (e) => { if (e.key === 'Escape') setOpen(false); };
    doc.addEventListener('pointerdown', away); doc.addEventListener('keydown', esc);
    return () => { doc.removeEventListener('pointerdown', away); doc.removeEventListener('keydown', esc); };
  }, [open]);
}

const CR_ICON = {
  new: <path d="M12 5v14M5 12h14" />,
  mine: <path d="M3 7h6l2 2h10v10H3z" />,
  history: <React.Fragment><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 3" /></React.Fragment>,
  deleted: <path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13" />,
  import: <path d="M12 3v12M7 10l5 5 5-5M4 21h16" />,
};
const crIcon = (k, color) => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={color || '#1f2937'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{CR_ICON[k]}</svg>
);
const shortDate = (t) => { const d = new Date(t); return d.toDateString() === new Date().toDateString() ? d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : d.toLocaleDateString([], { month: 'short', day: 'numeric' }); };
const PANEL_KEY = 'lbo.creatorPanel';
const PANEL_ONCE = 'lbo.creatorPanelOnce';
// The sidebar (290px open, a 64px rail closed) sits beside the editor only when the editor keeps
// at least 1100px (narrower, the Hand Viewer's Deal Cards row does not fit in landscape);
// otherwise it slides over the editor, and the rail keeps its place.
const CREATOR_SIDE_W = 290;
const CREATOR_DOCK_MIN = CREATOR_SIDE_W + 1100;

// Save, with Save a copy / Rename / New beside it (drawn in the editor's header).
function CreatorSave({ canSave, onSave, item, canCopy, onCopy, onRename, onNew, compact }) {
  const [open, setOpen] = React.useState(false);
  const box = React.useRef(null);
  useDismiss(open, setOpen, box);
  const row = 'w-full h-11 px-4 flex items-center text-left text-[15px] text-gray-900 hover:bg-gray-100 disabled:text-gray-400';
  const pick = (fn) => () => { setOpen(false); fn(); };
  return (
    <div className="relative flex shrink-0" ref={box} style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
      <button type="button" disabled={!canSave} onClick={onSave}
        className={'h-10 ' + (compact ? 'px-3' : 'px-4') + ' rounded-l-lg font-semibold text-white text-sm disabled:opacity-50'} style={{ background: ACTION }}>Save</button>
      <button type="button" aria-label="More save options" aria-haspopup="menu" aria-expanded={open} onClick={() => setOpen(!open)}
        className="h-10 w-8 rounded-r-lg text-white text-xs border-l border-white/40" style={{ background: ACTION }}>▾</button>
      {open && (
        <div role="menu" className="absolute right-0 top-12 w-52 bg-white border border-gray-300 rounded-lg shadow-lg py-1 z-50">
          <button type="button" role="menuitem" className={row} disabled={!canCopy} onClick={pick(onCopy)}>Save a copy…</button>
          <button type="button" role="menuitem" className={row} disabled={!item} onClick={pick(onRename)}>Rename…</button>
          <button type="button" role="menuitem" className={row + ' border-t border-gray-200'} onClick={pick(onNew)}>New hand</button>
        </div>
      )}
    </div>
  );
}

// Import: a hand or set from a URL (Hand Viewer, BBO, short links) or from .lin / .pbn files, loaded
// by the editor's own importers.
function CreatorImport({ editor }) {
  const [url, setUrl] = React.useState('');
  const [msg, setMsg] = React.useState('');
  const ready = () => { const e = editor(); if (!e) setMsg('Switch to the editor (the pencil icon) to import.'); return e; };
  const later = () => setTimeout(() => { const e = editor(); setMsg(e && e.urlError ? e.urlError : ''); }, 1500);
  const load = (ev) => {
    ev.preventDefault();
    const e = ready(); if (!e || !url.trim()) return;
    setMsg('Loading…'); e.loadUrl(url.trim()); setUrl(''); later();
  };
  const files = (ev) => {
    const list = Array.from(ev.target.files || []); ev.target.value = '';
    const e = ready(); if (!e || !list.length) return;
    if (!e.importFiles) { setMsg('File import is not available here.'); return; }
    Promise.all(list.map((f) => f.text().then((text) => ({ text, filename: f.name }))))
      .then((r) => { setMsg('Importing…'); e.importFiles(r); later(); }).catch((err) => setMsg(String(err.message || err)));
  };
  return (
    <div className="p-3 flex flex-col gap-4">
      <form onSubmit={load} className="flex flex-col gap-2">
        <label htmlFor="cr-url" className="text-sm font-semibold">Paste a hand URL</label>
        <input id="cr-url" className="h-11 w-full rounded-lg border border-gray-400 px-3 text-base" value={url} onChange={(e) => setUrl(e.target.value)}
          placeholder="hand.learnbridgeonline.com, BBO…" autoComplete="off" />
        <ActionButton type="submit" disabled={!url.trim()}>Load</ActionButton>
      </form>
      <div className="flex flex-col gap-2">
        <span className="text-sm font-semibold">Or import files</span>
        <label className="h-11 rounded-lg border border-gray-400 bg-white flex items-center justify-center gap-2 cursor-pointer text-[15px] hover:bg-gray-50">
          {crIcon('import')} Choose .lin or .pbn files
          <input type="file" accept=".pbn,.lin,.PBN,.LIN" multiple className="hidden" onChange={files} />
        </label>
      </div>
      {msg && <div role="status" className="text-sm text-gray-800">{msg}</div>}
      <div className="text-[12px] text-gray-600">The hands open in the editor. Press Save to keep them in My hands.</div>
    </div>
  );
}

// The panel beside the editor: My hands and sets, History, Import, Recently deleted.
function CreatorPanel({ panel, setPanel, list, item, histItem, dirty, actions, onClose, drawer, current, menu, importBox, bare }) {
  const [menuFor, setMenuFor] = React.useState(null);
  const heading = { mine: 'My hands and sets', history: 'History', import: 'Import', deleted: 'Recently deleted' }[panel];
  const btn = 'h-8 px-2.5 rounded-md border border-gray-400 bg-white text-[13px] whitespace-nowrap';
  const action = 'w-full h-10 px-3 text-left text-sm hover:bg-gray-100';
  return (
    <div className="h-full flex flex-col bg-white min-h-0">
      {!bare && <div className="h-12 shrink-0 flex items-center justify-between px-3 border-b border-gray-200">
        <strong className="text-[15px]">{drawer ? 'Hand Creator' : heading}</strong>
        <div className="flex items-center gap-1">
          {menu}
          <button type="button" aria-label="Close" onClick={onClose} className="w-10 h-10 text-xl text-gray-700 rounded-lg hover:bg-gray-100">×</button>
        </div>
      </div>}
      {current && (
        <div className="shrink-0 px-3 py-2 border-b border-gray-200 flex flex-col gap-1">
          <div className="text-[15px] font-semibold break-words">{current.title}</div>
          <div role="status" className={'text-[12px] ' + (current.warn ? 'text-amber-800 font-semibold' : 'text-gray-600')}>{current.state}</div>
          <div className="flex flex-wrap gap-2 pt-1">
            {item && <button type="button" className={btn} onClick={current.onRename}>Rename</button>}
            {current.canCopy && <button type="button" className={btn} onClick={current.onCopy}>Save a copy</button>}
          </div>
        </div>
      )}
      {drawer && !bare && (
        <div className="shrink-0 flex gap-1 p-2 border-b border-gray-200">
          {[['mine', 'My hands'], ['history', 'History'], ['import', 'Import'], ['deleted', 'Deleted']].map(([k, label]) => (
            <button key={k} type="button" aria-pressed={panel === k} onClick={() => setPanel(k)}
              className={'flex-1 h-10 rounded-lg text-sm ' + (panel === k ? 'bg-sky-100 font-semibold text-sky-800' : 'text-gray-700')}>{label}</button>
          ))}
        </div>
      )}
      {actions.note && <div role="status" className="shrink-0 px-3 py-2 text-[13px] text-gray-800 bg-amber-50 border-b border-amber-200">{actions.note}</div>}
      <div className="flex-1 min-h-0 overflow-y-auto">
        {panel === 'mine' && (
          <React.Fragment>
            {drawer && !bare && <div className="p-3 pb-1"><ActionButton onClick={actions.onNew}>+ New hand</ActionButton></div>}
            {!list && <div className="p-3 text-sm text-gray-700" role="status">Loading…</div>}
            {list && list.items.length === 0 && <div className="p-3 text-sm text-gray-700">Nothing saved yet. Press Save to keep the hands you make here.</div>}
            {list && list.items.map((c) => {
              const cur = item && item.id === c.id;
              return (
                <div key={c.id} className={'border-b border-gray-100 ' + (cur ? 'bg-sky-50' : '')} style={cur ? { boxShadow: 'inset 3px 0 0 ' + ACTION } : null}>
                  <div className="flex items-center gap-1 pr-1">
                    <button type="button" onClick={() => actions.onOpen(c.id)} aria-current={cur ? 'true' : undefined}
                      className="flex-1 min-w-0 text-left px-3 py-2">
                      <div className={'text-[14px] break-words ' + (cur ? 'font-semibold' : '')}>{c.title}</div>
                      <div className="text-[12px] text-gray-600">{kindText(c.hands)} · {cur && dirty ? 'unsaved changes' : shortDate(c.updatedAt)}</div>
                    </button>
                    <button type="button" aria-label={'Actions for ' + c.title} aria-expanded={menuFor === c.id}
                      onClick={() => setMenuFor(menuFor === c.id ? null : c.id)} className="w-9 h-9 shrink-0 rounded-lg hover:bg-gray-100 text-lg leading-none">⋯</button>
                  </div>
                  {menuFor === c.id && (
                    <div className="mx-3 mb-2 border border-gray-300 rounded-lg bg-white shadow-sm overflow-hidden" role="menu">
                      <button type="button" role="menuitem" className={action} onClick={() => { setMenuFor(null); actions.onRename(c); }}>Rename…</button>
                      <button type="button" role="menuitem" className={action} onClick={() => { setMenuFor(null); actions.onCopyLink(c); }}>Copy link</button>
                      <button type="button" role="menuitem" className={action} onClick={() => { setMenuFor(null); actions.onHistory(c); }}>History ({c.versions})</button>
                      <button type="button" role="menuitem" className={action + ' text-red-700 border-t border-gray-200'} onClick={() => { setMenuFor(null); actions.onDelete(c); }}>Delete</button>
                    </div>
                  )}
                </div>
              );
            })}
          </React.Fragment>
        )}
        {panel === 'history' && (
          !histItem ? <div className="p-3 text-sm text-gray-700">Save the hand first. After that, every save that changes the hands is kept here, so you can go back to an earlier one.</div>
          : (
            <div className="p-3 flex flex-col gap-2">
              <div className="text-[13px] font-semibold break-words">{histItem.title}</div>
              <div className="text-[12px] text-gray-600">Each save that changed the hands, newest first (the latest 20 are kept). Open an earlier one and press Save to make it the current version.</div>
              {!histItem.versions && <div className="text-sm text-gray-700" role="status">Loading…</div>}
              {histItem.versions && histItem.versions.map((v, i) => (
                <div key={v.id} className={'rounded-lg px-3 py-2 flex items-center justify-between gap-2 ' + (i === 0 ? 'border-2' : 'border border-gray-300')} style={i === 0 ? { borderColor: ACTION } : null}>
                  <div className="min-w-0">
                    <div className="text-[13px] font-semibold">{new Date(v.savedAt).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })}{i === 0 ? ' · current' : ''}</div>
                    <div className="text-[12px] text-gray-600">{kindText(v.hands)}</div>
                  </div>
                  {i > 0 && <button type="button" className={btn} onClick={() => actions.onOpen(histItem.id, v.id)}>Open</button>}
                </div>
              ))}
            </div>
          )
        )}
        {panel === 'import' && importBox}
        {panel === 'deleted' && (
          <div className="p-3 flex flex-col gap-2">
            <div className="text-[12px] text-gray-600">Deleted hands and sets are kept for 30 days.</div>
            {list && list.deleted.length === 0 && <div className="text-sm text-gray-700">Nothing deleted.</div>}
            {list && list.deleted.map((c) => (
              <div key={c.id} className="flex items-center justify-between gap-2 py-1 border-b border-gray-100">
                <div className="min-w-0">
                  <div className="text-[14px] break-words">{c.title}</div>
                  <div className="text-[12px] text-gray-600">{kindText(c.hands)} · deleted {shortDate(c.deletedAt)}</div>
                </div>
                <button type="button" className={btn} onClick={() => actions.onRestore(c)}>Restore</button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function HandCreator({ start, go, onOpened, user, account }) {
  const { vw } = useScreenSize();
  const phone = vw < 640;
  // What is open: a saved item (and perhaps an earlier version of it), or new work.
  const [item, setItem] = React.useState(null);           // { id, title }
  const [older, setOlder] = React.useState(null);         // the earlier version being looked at: { id, savedAt }
  const [src, setSrc] = React.useState(null);             // the frame's address (null until the item is known)
  const [frameKey, setFrameKey] = React.useState(0);
  const [work, setWork] = React.useState(null);           // { data, hands } read from the frame
  const [status, setStatus] = React.useState('');
  const [dialog, setDialog] = React.useState(null);       // { kind: 'save' | 'copy' | 'rename', target }
  const [list, setList] = React.useState(null);           // { items, deleted }
  const [note, setNote] = React.useState('');
  const [hist, setHist] = React.useState(null);           // { id, title, versions }: the item whose history is shown
  const [slots, setSlots] = React.useState({ left: null, right: null });   // where the editor's header takes our controls
  // The panel opens by itself only where it fits beside the editor (or when Home's "My hands and
  // sets" asked for it); elsewhere it slides over the editor when a rail button is pressed.
  const [panel, setPanelState] = React.useState(() => {
    try {
      const once = sessionStorage.getItem(PANEL_ONCE); sessionStorage.removeItem(PANEL_ONCE);
      if (once) return once;
      if (window.innerWidth < CREATOR_DOCK_MIN) return null;
      const p = localStorage.getItem(PANEL_KEY); if (p !== null) return p || null;
    } catch (e) {}
    return window.innerWidth >= CREATOR_DOCK_MIN ? 'mine' : null;
  });
  const [drawer, setDrawer] = React.useState(false);      // phones: the panel slides over the editor
  const setPanel = (p) => { setPanelState(p); try { localStorage.setItem(PANEL_KEY, p || ''); } catch (e) {} };
  const frame = React.useRef(null);
  const baseline = React.useRef(undefined);               // the work as loaded or last saved (undefined: not read yet)
  const sideRef = React.useRef(0);                        // the room the rail and panel take under the top bar
  const overlayRef = React.useRef(false);                 // the panel is over the editor: a click in the editor closes it
  const [headBottom, setHeadBottom] = React.useState(56); // where the editor's header (the top bar) ends
  const [lastPanel, setLastPanel] = React.useState(null); // kept drawn while the panel slides shut
  React.useEffect(() => { if (panel) setLastPanel(panel); }, [panel]);

  const loadList = () => api('GET', '/api/creations').then(setList).catch((e) => setNote(errorText(e.message)));
  React.useEffect(() => { loadList(); }, []);
  const showHistory = (c) => {
    setHist({ id: c.id, title: c.title, versions: null });
    api('GET', '/api/creations/' + c.id).then((r) => setHist({ id: c.id, title: r.item.title, versions: r.versions })).catch(() => setHist(null));
  };

  const open = (id, versionId) => {
    baseline.current = undefined; setWork(null); setStatus(''); setOlder(null); setNote('');
    if (!id) { setItem(null); setHist(null); setSrc('/hand-creator/app'); setFrameKey((k) => k + 1); history.replaceState(null, '', '/hand-creator'); return; }
    api('GET', '/api/creations/' + id).then((r) => {
      if (r.item.deletedAt) throw new Error('not_found');
      const v = versionId ? r.versions.find((x) => x.id === Number(versionId)) : null;
      setItem({ id: r.item.id, title: r.item.title });
      setHist({ id: r.item.id, title: r.item.title, versions: r.versions });
      setOlder(v && r.versions[0] && v.id !== r.versions[0].id ? v : null);
      setSrc('/hand-creator/app?item=' + id + (v ? '&version=' + v.id : ''));
      setFrameKey((k) => k + 1);
      history.replaceState(null, '', '/hand-creator?item=' + id);
    }).catch(() => { setNote('That hand or set could not be opened.'); open(null); });
  };
  React.useEffect(() => { open(start && start.item, start && start.version); }, [start && start.n]);

  // Read the frame twice a second; look for the editor's header often, as it is redrawn when the
  // editor switches between Edit, View and Play.
  React.useEffect(() => {
    const x = setInterval(() => {
      const w = creatorWork(frame.current && frame.current.contentWindow);
      if (!w) return;
      if (baseline.current === undefined) baseline.current = w.data;
      setWork((prev) => (prev && prev.data === w.data ? prev : w));
    }, 500);
    const y = setInterval(() => {
      let doc = null;
      try { doc = frame.current && frame.current.contentDocument; } catch (e) {}
      const left = doc ? doc.querySelector('[data-lbo-slot="left"]') : null;
      const right = doc ? doc.querySelector('[data-lbo-slot="right"]') : null;
      setSlots((p) => (p.left === left && p.right === right ? p : { left, right }));
      try {
        const w = frame.current && frame.current.contentWindow;
        if (w && w.LBO_SET_SIDE) {
          if (!w.lboClosePanel) {
            w.lboClosePanel = true;
            w.addEventListener('pointerdown', () => { if (overlayRef.current) setPanelState(null); setDrawer(false); }, true);
          }
          w.LBO_SET_SIDE(sideRef.current);
          const hb = Math.round(w.LBO_HEAD_BOTTOM || 0);
          if (hb > 0) setHeadBottom((p) => (p === hb ? p : hb));
        }
      } catch (e) {}
    }, 150);
    return () => { clearInterval(x); clearInterval(y); };
  }, []);
  const dirty = !!work && (work.data !== baseline.current || (!!older && work.hands > 0));
  creatorDirty.current = dirty;
  React.useEffect(() => {
    const warn = (e) => { if (creatorDirty.current) { e.preventDefault(); e.returnValue = ''; } };
    window.addEventListener('beforeunload', warn);
    return () => { window.removeEventListener('beforeunload', warn); creatorDirty.current = false; };
  }, []);

  const savedNow = (it, data) => {
    baseline.current = data; setItem({ id: it.id, title: it.title }); setOlder(null);
    setStatus('Saved ' + new Date().toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }));
    history.replaceState(null, '', '/hand-creator?item=' + it.id);
    if (onOpened) onOpened(it.id);
    loadList(); showHistory(it);
  };
  const save = async () => {
    if (!work || !work.hands) return;
    if (!item) { setDialog({ kind: 'save' }); return; }
    setStatus('Saving…');
    try { const r = await api('PUT', '/api/creations/' + item.id, { data: work.data }); savedNow(r.item, work.data); }
    catch (e) { setStatus(errorText(e.message)); }
  };
  const create = async (title) => {
    const r = await api('POST', '/api/creations', { title, data: work.data });
    setDialog(null); savedNow(r.item, work.data);
  };
  const rename = async (title) => {
    const target = dialog.target;
    const r = await api('PUT', '/api/creations/' + target.id, { title });
    setDialog(null);
    if (item && item.id === r.item.id) setItem({ id: r.item.id, title: r.item.title });
    if (hist && hist.id === r.item.id) setHist(Object.assign({}, hist, { title: r.item.title }));
    loadList();
  };
  const leaveWork = (what) => !dirty || window.confirm(what + ' Your unsaved changes will be lost.');
  const startNew = () => { if (leaveWork('Start a new hand?')) { open(null); setDrawer(false); } };
  const openItem = (id, versionId) => {
    if (item && item.id === id && !versionId && !older) { setDrawer(false); return; }
    if (leaveWork('Open another hand?')) { open(id, versionId); setDrawer(false); }
  };
  const copyLink = async (c) => {
    try {
      const r = await api('GET', '/api/creations/' + c.id);
      await navigator.clipboard.writeText(HAND_VIEWER + '/view?set=' + encodeURIComponent(r.item.data));
      setNote('Link to "' + c.title + '" copied. It opens on hand.learnbridgeonline.com and shows the hands as last saved.');
    } catch (e) { setNote('The link could not be copied. Open the hand and use Share in the header.'); }
  };
  const del = async (c) => {
    if (!window.confirm('Delete "' + c.title + '"? You can restore it from Recently deleted for 30 days.')) return;
    try {
      await api('PUT', '/api/creations/' + c.id, { deleted: true });
      if (item && item.id === c.id) { creatorDirty.current = false; open(null); }
      if (hist && hist.id === c.id) setHist(null);
      loadList();
    } catch (e) { setNote(errorText(e.message)); }
  };
  const restore = (c) => api('PUT', '/api/creations/' + c.id, { deleted: false }).then(loadList).catch((e) => setNote(errorText(e.message)));
  const actions = {
    note, onNew: startNew, onOpen: openItem, onCopyLink: copyLink, onDelete: del, onRestore: restore,
    onRename: (c) => setDialog({ kind: 'rename', target: c }),
    onHistory: (c) => { showHistory(c); if (phone) setDrawer(true); setPanel('history'); },
  };
  // The rail's buttons: New, then the panels (a second press closes a panel).
  const openDrawer = () => { if (!panel) setPanelState('mine'); if (panel === 'history' && item && (!hist || hist.id !== item.id)) showHistory(item); setDrawer(true); };

  const state = !work ? 'Opening…'
    : older ? 'An earlier version (' + new Date(older.savedAt).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + '). Save to make it current.'
    : !work.hands ? 'Nothing to save yet'
    : dirty ? (item ? 'Unsaved changes' : 'Not saved yet')
    : status || (item ? 'Saved' : '');
  // The editor's importers, while the frame shows the editor (not View or Play).
  const editorApi = () => {
    try {
      const w = frame.current && frame.current.contentWindow;
      return w && w.LBO_EDITOR && w.LBO_HV_STATE && w.LBO_HV_STATE.mode === 'editor2' ? w.LBO_EDITOR : null;
    } catch (e) { return null; }
  };
  const importBox = <CreatorImport editor={editorApi} />;
  const title = item ? item.title : 'New hand';
  const canSave = !!work && work.hands > 0 && (dirty || !item);
  const canCopy = !!item && !!work && work.hands > 0;
  const wide = vw >= 1100;

  // Drawn inside the editor's own header, which is the page's top bar (full width): the club's
  // logo (Home, as everywhere), then the hand's title and save state when there is room; Save and
  // the club menu at the right end, after the editor's icons.
  const showTitle = vw >= 1000;
  const dock = !phone && vw >= CREATOR_DOCK_MIN;           // the open sidebar beside the editor, not over it
  const side = phone ? 0 : (panel && dock ? CREATOR_SIDE_W : 0);
  sideRef.current = side;
  overlayRef.current = !dock && !!panel;
  // The logo opens and closes the sidebar, as on every page (phones: over the editor).
  const sideShown = phone ? drawer : !!panel;
  const toggleSide = () => { if (phone) { if (drawer) setDrawer(false); else openDrawer(); } else setPanel(panel ? null : (lastPanel || 'mine')); };
  const headLeft = (
    <div className="flex items-center gap-3 min-w-0 shrink" style={{ fontFamily: SERIF, maxWidth: showTitle ? 440 : undefined }}>
      <LogoButton onClick={toggleSide} open={sideShown} height={vw < 360 ? 28 : 34} />
      {showTitle && <div className="min-w-0 flex flex-col leading-tight pl-3 border-l border-gray-300">
        <button type="button" onClick={() => (item ? setDialog({ kind: 'rename', target: item }) : save())} title={item ? 'Rename' : 'Save'}
          className="text-left font-semibold text-[18px] text-gray-900 truncate hover:underline">{title}</button>
        <span role="status" className={'text-[14px] truncate ' + (dirty || older ? 'text-amber-800 font-semibold' : 'text-gray-600')}>{state}</span>
      </div>}
    </div>
  );
  const headRight = (
    <div className="flex items-center gap-2 shrink-0" style={{ fontFamily: SERIF }}>
      {phone
        ? <button type="button" disabled={!canSave} onClick={save} className="h-10 px-3 rounded-lg font-semibold text-white text-base disabled:opacity-50 shrink-0" style={{ background: ACTION }}>Save</button>
        : <CreatorSave canSave={canSave} onSave={save} item={item}
            canCopy={canCopy} onCopy={() => setDialog({ kind: 'copy' })}
            onRename={() => setDialog({ kind: 'rename', target: item })} onNew={startNew} />}
    </div>
  );
  // Without the title in the top bar, the sidebar shows it (with Rename / Save a copy).
  const current = { title, state, warn: dirty || !!older, canCopy, onRename: () => setDialog({ kind: 'rename', target: item }), onCopy: () => setDialog({ kind: 'copy' }) };
  const ITEMS = [['new', 'New hand', 'new'], ['mine', 'My hands and sets', 'mine'], ['history', 'History', 'history'], ['import', 'Import', 'import'], ['deleted', 'Recently deleted', 'deleted']];
  const pickItem = (k) => {
    if (k === 'new') { startNew(); return; }
    if (k === 'history' && item && (!hist || hist.id !== item.id)) showHistory(item);
    setPanel(k);
  };
  // The open sidebar: ‹ Home, the Hand Creator's items, the chosen item's contents, the site's links.
  const sideOpen = (shown) => (
    <SideBar width="100%" back={{ label: 'Home', onClick: () => go('home') }} heading="Hand Creator" active={shown}
      items={ITEMS.map(([id, label, icon]) => ({ id, label, icon: null, cr: icon }))} onPick={(it) => pickItem(it.id)} account={account}>
      <div className="flex-1 min-h-0 border-t border-gray-200">
        <CreatorPanel bare drawer={phone} panel={shown} setPanel={setPanel} list={list} item={item} histItem={hist} dirty={dirty} actions={actions} importBox={importBox}
          current={showTitle ? null : current} />
      </div>
    </SideBar>
  );
  return (
    <div className="flex-1 min-h-0 bg-white relative">
      {src && <iframe key={frameKey} ref={frame} src={src} title="Hand Creator" className="absolute inset-0 w-full h-full border-0 bg-white" />}
      {!slots.left && (
        <div className="absolute left-0 right-0 top-0 z-40 bg-white border-b border-gray-300 flex items-center px-2 sm:px-5" style={{ height: TOP_H, fontFamily: SERIF }}>
          <LogoButton onClick={toggleSide} open={sideShown} height={vw < 360 ? 28 : 34} />
          <span className="ml-3 text-[17px] text-gray-600" role="status">Opening the Hand Creator…</span>
        </div>
      )}
      {!phone && (
        <div className="absolute left-0 bottom-0 z-30 flex" style={{ top: headBottom }}>
          {panel && (
            <div className="h-full shrink-0" style={{ width: CREATOR_SIDE_W, boxShadow: dock ? 'none' : '6px 0 16px rgba(0,0,0,0.12)' }}>
              {sideOpen(panel)}
            </div>
          )}
        </div>
      )}
      {phone && (
        <div className="absolute left-0 right-0 bottom-0 z-40 overflow-hidden" style={{ top: headBottom, pointerEvents: drawer ? 'auto' : 'none' }}>
          <button type="button" aria-label="Close" tabIndex={drawer ? 0 : -1} onClick={() => setDrawer(false)}
            className="absolute inset-0 w-full h-full bg-black/40" style={{ opacity: drawer ? 1 : 0, transition: 'opacity 180ms' }} />
          <div className="absolute left-0 top-0 bottom-0 w-[85%] max-w-[340px] shadow-xl bg-white"
            style={{ transform: drawer ? 'none' : 'translateX(-105%)', transition: 'transform 200ms ease-out' }} aria-hidden={!drawer}>
            {(drawer || lastPanel) && sideOpen(panel || 'mine')}
          </div>
        </div>
      )}
      {slots.left && ReactDOM.createPortal(headLeft, slots.left)}
      {slots.right && ReactDOM.createPortal(headRight, slots.right)}
      {dialog && dialog.kind === 'save' && <TitleDialog heading="Save to My hands" action="Save" onCancel={() => setDialog(null)} onDone={create}
        note={kindText(work.hands) + '. It will be listed under My hands, beside the editor.'} />}
      {dialog && dialog.kind === 'copy' && <TitleDialog heading="Save a copy" initial={item.title + ' (copy)'} action="Save a copy" onCancel={() => setDialog(null)} onDone={create}
        note="A new entry in My hands. The original stays as it was last saved." />}
      {dialog && dialog.kind === 'rename' && <TitleDialog heading="Rename" initial={dialog.target.title} action="Rename" onCancel={() => setDialog(null)} onDone={rename} />}
    </div>
  );
}

function Settings({ user, onUser, onSignOut, club, refresh }) {
  const [username, setUsername] = React.useState(user.username);
  const [note, setNote] = React.useState('');
  const save = async (body, okText) => {
    setNote('');
    try { const r = await api('PUT', '/api/me', body); onUser(r.user); setNote(okText || 'Saved.'); }
    catch (err) { setNote(errorText(err.message)); }
  };
  const set = (key) => (value) => save({ settings: { [key]: value } });
  const s = user.settings;
  return (
    <Page title="Settings" sub="Your account, and how the robots bid.">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-5 content-start">
        <Panel className="flex flex-col gap-4">
          <h2 className="text-[1.4rem] font-semibold m-0">Your account</h2>
          <form className="flex flex-col gap-2" onSubmit={(e) => { e.preventDefault(); save({ username }, 'Username saved.'); }}>
            <label htmlFor="st-user" className="text-sm font-semibold">Username (public)</label>
            <div className="flex gap-2">
              <input id="st-user" className="h-11 flex-1 min-w-0 rounded-lg border border-gray-400 px-3 text-base" value={username}
                maxLength={20} onChange={(e) => setUsername(e.target.value)} />
              <ActionButton type="submit" outline disabled={username.trim() === user.username}>Save</ActionButton>
            </div>
          </form>
          <div>
            <div className="text-sm font-semibold">Email (sign-in, never shown)</div>
            <div className="text-base break-all">{user.email}</div>
          </div>
          <div role="status" className="text-sm text-gray-700 min-h-[20px]">{note}</div>
          <button type="button" onClick={onSignOut} className="h-11 rounded-lg border border-gray-400 bg-white">Log out</button>
        </Panel>
        <Panel className="flex flex-col gap-4">
          <h2 className="text-[1.4rem] font-semibold m-0">Bidding and table defaults</h2>
          <div className="text-[13px] text-gray-600">Used for Practice, and filled in when you create a table.</div>
          <Choice label="Bidding system" options={SYSTEM_CHOICES} value={s.biddingSystem} onChange={set('biddingSystem')} />
          <Choice label="Ace asking" options={ACE_CHOICES} value={s.aceAsking} onChange={set('aceAsking')} />
          <label className="flex items-center gap-3 min-h-[44px] text-[15px]">
            <input type="checkbox" className="w-5 h-5" checked={s.beginnerFriendly}
              onChange={(e) => save({ settings: { beginnerFriendly: e.target.checked } })} />
            Beginner friendly by default
          </label>
          <label className="flex items-center gap-3 min-h-[44px] text-[15px]">
            <input type="checkbox" className="w-5 h-5" checked={!s.tableOpen}
              onChange={(e) => save({ settings: { tableOpen: !e.target.checked } })} />
            Private table by default
          </label>
        </Panel>
        {SHOW_FRIENDS && (
          <Panel className="flex flex-col gap-4 md:col-span-2">
            <h2 className="text-xl font-bold m-0">Friends</h2>
            <FriendsPanel club={club} refresh={refresh} />
          </Panel>
        )}
      </div>
    </Page>
  );
}

// ---- Admin: activity, chat review, blocked words ----
function StatTile({ label, value }) {
  return (
    <div className="rounded-lg border border-gray-300 bg-white px-3 py-2 min-w-[110px] flex-1">
      <div className="text-2xl font-bold leading-tight">{value}</div>
      <div className="text-[13px] text-gray-700">{label}</div>
    </div>
  );
}
function AdminActivity({ users }) {
  const [st, setSt] = React.useState(null);
  React.useEffect(() => {
    const load = () => api('GET', '/api/admin/stats').then(setSt).catch(() => {});
    load(); const x = setInterval(load, 30000); return () => clearInterval(x);
  }, []);
  const recent = (users || []).filter((u) => u.username && (u.online || u.lastSeenAt))
    .sort((a, b) => (b.online ? 1 : 0) - (a.online ? 1 : 0) || String(b.lastSeenAt || '').localeCompare(String(a.lastSeenAt || ''))).slice(0, 15);
  if (!st) return <Panel><div className="text-gray-700" role="status">Loading…</div></Panel>;
  return (
    <React.Fragment>
      <Panel className="flex flex-col gap-4">
        <div>
          <h2 className="text-xl font-bold m-0 mb-2">Now</h2>
          <div className="flex flex-wrap gap-2">
            <StatTile label="players here" value={st.now.online} /><StatTile label="tables open" value={st.now.tables} /><StatTile label="hands in play" value={st.now.handsInPlay} />
          </div>
        </div>
        <div>
          <h2 className="text-xl font-bold m-0 mb-2">Active players</h2>
          <div className="flex flex-wrap gap-2">
            <StatTile label="last 24 hours" value={st.active.day} /><StatTile label="last 7 days" value={st.active.week} /><StatTile label="last 30 days" value={st.active.month} />
          </div>
        </div>
        <div>
          <h2 className="text-xl font-bold m-0 mb-2">Hands played at tables</h2>
          <div className="flex flex-wrap gap-2">
            <StatTile label="last 24 hours" value={st.hands.day} /><StatTile label="last 7 days" value={st.hands.week} /><StatTile label="all time" value={st.hands.all} />
          </div>
          <div className="text-[13px] text-gray-600 mt-1">Play with Friends only, counted from this update on. Practice hands are played in the browser and are not counted.</div>
        </div>
      </Panel>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
        <Panel>
          <h2 className="text-xl font-bold m-0 mb-2">Recently active</h2>
          {recent.length === 0 && <div className="text-sm text-gray-700">Nobody yet.</div>}
          {recent.map((u) => (
            <div key={u.id} className="flex items-baseline justify-between gap-3 py-1 border-t border-gray-100 text-[15px]">
              <span className="truncate">{u.username}{u.blockedAt ? ' (blocked)' : ''}</span>
              <span className="text-sm text-gray-700 whitespace-nowrap">{u.online ? <span className="text-green-700 font-semibold">here now</span> : new Date(u.lastSeenAt).toLocaleString()}</span>
            </div>
          ))}
        </Panel>
        <Panel>
          <h2 className="text-xl font-bold m-0 mb-2">Most hands, last 7 days</h2>
          {st.topPlayers.length === 0 && <div className="text-sm text-gray-700">No hands yet.</div>}
          {st.topPlayers.map((p, i) => (
            <div key={i} className="flex items-baseline justify-between gap-3 py-1 border-t border-gray-100 text-[15px]">
              <span className="truncate">{p.username}</span><span className="text-sm text-gray-700">{p.hands}</span>
            </div>
          ))}
        </Panel>
      </div>
      <Panel>
        <h2 className="text-xl font-bold m-0 mb-2">Latest hands</h2>
        {st.recentHands.length === 0 && <div className="text-sm text-gray-700">No hands yet.</div>}
        <div className="overflow-x-auto">
          <table className="w-full text-sm text-left">
            <tbody>
              {st.recentHands.map((h) => (
                <tr key={h.id} className="border-t border-gray-100">
                  <td className="py-1.5 pr-3 whitespace-nowrap">{new Date(h.at).toLocaleString()}</td>
                  <td className="py-1.5 pr-3 whitespace-nowrap">Board {h.board}</td>
                  <td className="py-1.5 pr-3">{h.result}</td>
                  <td className="py-1.5 text-gray-700">{SEAT_ORDER.map((s) => s + ': ' + (h.names[s] || '?')).join(' · ')}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Panel>
    </React.Fragment>
  );
}

function AdminChat() {
  const [list, setList] = React.useState(null);
  const [more, setMore] = React.useState(true);
  const [note, setNote] = React.useState('');
  const load = () => api('GET', '/api/admin/chat').then((r) => { setList(r.messages); setMore(r.messages.length === 100); }).catch((e) => setNote(errorText(e.message)));
  React.useEffect(() => { load(); }, []);
  const older = () => api('GET', '/api/admin/chat?before=' + list[list.length - 1].id).then((r) => { setList(list.concat(r.messages)); setMore(r.messages.length === 100); }).catch(() => {});
  const remove = (m) => { if (window.confirm('Delete this message' + (m.reply || m.where !== 'Room' ? '' : ' and its replies') + '? Players will no longer see it.')) api('DELETE', '/api/admin/chat/' + m.id, {}).then(load).catch((e) => setNote(errorText(e.message))); };
  return (
    <Panel>
      <div className="flex flex-wrap items-baseline justify-between gap-2 mb-1">
        <h2 className="text-xl font-bold m-0">Chat history</h2>
        <button type="button" className="h-9 px-3 rounded-lg border border-gray-400" onClick={load}>Refresh</button>
      </div>
      <div className="text-sm text-gray-700 mb-3">Every message from the room and from tables, newest first. Deleted messages stay here, marked.</div>
      {note && <div role="alert" className="text-sm text-red-700 mb-2">{note}</div>}
      {!list && <div className="text-gray-700" role="status">Loading…</div>}
      {list && list.length === 0 && <div className="text-sm text-gray-700">No messages yet.</div>}
      {(list || []).map((m) => (
        <div key={m.id} className={'py-2 border-t border-gray-200 flex items-start justify-between gap-3 ' + (m.hidden ? 'opacity-60' : '')}>
          <div className="min-w-0">
            <div className="text-[13px] text-gray-700">
              <b className="text-gray-900">{m.username}</b> · {new Date(m.at).toLocaleString()} · {m.where}{m.tableKey ? ' ' + m.tableKey : ''}{m.reply ? ' · reply' : ''}
              {m.hidden && <span className="ml-2 px-2 rounded-full text-xs font-semibold bg-gray-200 text-gray-800">deleted</span>}
            </div>
            <div className="text-[15px] whitespace-pre-wrap break-words">{m.body}</div>
          </div>
          {!m.hidden && <button type="button" className="h-9 px-2 rounded border border-gray-400 text-sm shrink-0" onClick={() => remove(m)}>Delete</button>}
        </div>
      ))}
      {list && list.length > 0 && more && <div className="pt-3"><button type="button" className="h-11 px-4 rounded-lg border border-gray-400" onClick={older}>Show older messages</button></div>}
    </Panel>
  );
}

// Every hand and set saved in the Hand Creator, by creator. Read-only: View opens the hands on the Hand Viewer.
function AdminCreations() {
  const [data, setData] = React.useState(null);
  const [note, setNote] = React.useState('');
  React.useEffect(() => { api('GET', '/api/admin/creations').then(setData).catch((e) => setNote(errorText(e.message))); }, []);
  const link = async (c) => HAND_VIEWER + '/view?set=' + encodeURIComponent((await api('GET', '/api/admin/creations/' + c.id)).item.data);
  const copy = async (c) => {
    try { await navigator.clipboard.writeText(await link(c)); setNote('Link to "' + c.title + '" copied.'); } catch (e) { setNote('The link could not be copied.'); }
  };
  const btn = 'h-9 px-3 rounded-lg border border-gray-400 bg-white text-sm whitespace-nowrap';
  const total = data ? data.creators.reduce((n, g) => n + g.items.length, 0) : 0;
  return (
    <React.Fragment>
      <Panel>
        <h2 className="text-xl font-bold m-0 mb-1">Saved hands and sets{data ? ' (' + total + ')' : ''}</h2>
        <div className="text-sm text-gray-700">Everything saved in the Hand Creator, by creator. View opens the hands as last saved on hand.learnbridgeonline.com, in a new tab.</div>
        {note && <div role="status" className="text-sm text-gray-800 mt-2">{note}</div>}
        {!data && <div className="text-gray-700 mt-2" role="status">Loading…</div>}
        {data && total === 0 && <div className="text-sm text-gray-700 mt-2">Nothing has been saved yet.</div>}
      </Panel>
      {data && data.creators.map((g) => (
        <Panel key={g.userId}>
          <div className="flex flex-wrap items-baseline justify-between gap-x-3 mb-1">
            <h3 className="text-lg font-bold m-0">{g.username}</h3>
            <span className="text-sm text-gray-700 break-all">{g.email} · {g.items.length} saved</span>
          </div>
          {g.items.map((c) => (
            <div key={c.id} className={'border-t border-gray-200 py-2 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 ' + (c.deletedAt ? 'opacity-60' : '')}>
              <div className="min-w-0">
                <div className="font-semibold break-words">{c.title}
                  {c.deletedAt && <span className="ml-2 px-2 rounded-full text-xs font-semibold bg-gray-200 text-gray-800">deleted {new Date(c.deletedAt).toLocaleDateString()}</span>}</div>
                <div className="text-[13px] text-gray-600">{kindText(c.hands)} · saved {new Date(c.updatedAt).toLocaleString()} · created {new Date(c.createdAt).toLocaleDateString()} · {c.versions} {c.versions === 1 ? 'version' : 'versions'}</div>
              </div>
              <div className="flex gap-2">
                <a className={btn + ' flex items-center no-underline text-gray-900'} href={'/admin/creations/' + c.id + '/view'} target="_blank" rel="noopener">View</a>
                <button type="button" className={btn} onClick={() => copy(c)}>Copy link</button>
              </div>
            </div>
          ))}
        </Panel>
      ))}
    </React.Fragment>
  );
}

function AdminWords() {
  const [text, setText] = React.useState(null);
  const [note, setNote] = React.useState('');
  React.useEffect(() => { api('GET', '/api/admin/blocked-words').then((r) => setText(r.words.join('\n'))).catch((e) => setNote(errorText(e.message))); }, []);
  const save = async (e) => {
    e.preventDefault();
    try { const r = await api('PUT', '/api/admin/blocked-words', { words: text.split('\n') }); setText(r.words.join('\n')); setNote('Saved: ' + r.words.length + (r.words.length === 1 ? ' entry.' : ' entries.')); }
    catch (err) { setNote(errorText(err.message)); }
  };
  return (
    <Panel>
      <form onSubmit={save} className="flex flex-col gap-3">
        <h2 className="text-xl font-bold m-0">Blocked words</h2>
        <label htmlFor="ad-words" className="text-sm text-gray-700">
          One word or phrase per line. A chat message, username or bid explanation containing one is refused, and the writer is asked to rephrase.
          Whole words only, in any letter case: an entry "ass" does not stop "class".
        </label>
        <textarea id="ad-words" rows={12} className="rounded-lg border border-gray-400 p-3 text-base font-mono" value={text === null ? '' : text} disabled={text === null}
          onChange={(e) => { setText(e.target.value); setNote(''); }} />
        <div className="flex items-center gap-3">
          <ActionButton type="submit" disabled={text === null}>Save</ActionButton>
          <span role="status" className="text-sm text-gray-700">{note}</span>
        </div>
      </form>
    </Panel>
  );
}

const ADMIN_TABS = [['activity', 'Activity', 'activity', 'Who is playing, and how much.'], ['users', 'Users', 'users', 'Invite players, roles, blocking and the shared password.'],
  ['hands', 'Saved hands', 'hands', 'Every saved hand and set, by its creator.'], ['chat', 'Chat', 'chat', 'Recent messages in the room and at the tables.'],
  ['words', 'Blocked words', 'words', 'Words that cannot be used in chat or usernames.']];
function Admin({ me, tab }) {
  const [users, setUsers] = React.useState(null);
  const [emails, setEmails] = React.useState('');
  const [note, setNote] = React.useState('');
  const [newPw, setNewPw] = React.useState('');
  const [pwNote, setPwNote] = React.useState('');
  const [pwChanged, setPwChanged] = React.useState(null);
  const [requests, setRequests] = React.useState([]);
  const load = () => api('GET', '/api/admin/users').then((r) => { setUsers(r.users); setPwChanged(r.sharedPasswordChangedAt); setRequests(r.requests || []); }).catch((e) => setNote(errorText(e.message)));
  const savePw = async (e) => {
    e.preventDefault();
    try { await api('POST', '/api/admin/shared-password', { password: newPw }); setNewPw(''); setPwNote('Shared password changed.'); load(); }
    catch (err) { setPwNote(errorText(err.message)); }
  };
  const [engines, setEngines] = React.useState(null);
  React.useEffect(() => { load(); api('GET', '/api/admin/engines').then(setEngines).catch(() => {}); }, []);
  React.useEffect(() => { if (tab === 'users') load(); }, [tab]);
  const head = ADMIN_TABS.find((x) => x[0] === tab) || ADMIN_TABS[0];
  const usersOnly = tab === 'users' ? '' : 'hidden';
  const invite = async (e) => {
    e.preventDefault();
    const list = emails.split(/[\s,;]+/).filter(Boolean);
    try {
      const r = await api('POST', '/api/admin/invite', { emails: list });
      setNote(r.added.length + ' invited.' + (r.rejected.length ? ' Not valid: ' + r.rejected.join(', ') : ''));
      setEmails(''); load();
    } catch (err) { setNote(errorText(err.message)); }
  };
  const act = (fn) => fn.then(load).catch((e) => setNote(errorText(e.message)));
  return (
    <Page title={head[1]} sub={head[3]}>
      <div className="flex flex-col gap-5">
        {tab === 'activity' && <AdminActivity users={users} />}
        {tab === 'hands' && <AdminCreations />}
        {tab === 'chat' && <AdminChat />}
        {tab === 'words' && <AdminWords />}
        <Panel className={usersOnly}>
          <form onSubmit={invite} className="flex flex-col gap-3">
            <h2 className="text-xl font-bold m-0">Invite players</h2>
            <label htmlFor="ad-emails" className="text-sm text-gray-700">Email addresses, separated by spaces, commas or new lines. Invited players sign in with the shared password.</label>
            <textarea id="ad-emails" rows={3} className="rounded-lg border border-gray-400 p-3 text-base" value={emails}
              onChange={(e) => setEmails(e.target.value)} />
            <div className="flex items-center gap-3">
              <ActionButton type="submit" disabled={!emails.trim()}>Invite</ActionButton>
              <span role="status" className="text-sm text-gray-700">{note}</span>
            </div>
          </form>
        </Panel>
        {tab === 'users' && requests.length > 0 && (
          <Panel>
            <h2 className="text-xl font-bold m-0 mb-1">Access requests ({requests.length})</h2>
            <div className="text-sm text-gray-700 mb-3">Approve adds the email to the invited list. Send the person the shared password yourself.</div>
            {requests.map((q) => (
              <div key={q.id} className="flex flex-wrap items-center justify-between gap-2 py-2 border-t border-gray-200">
                <div className="min-w-0">
                  <div className="font-semibold break-all">{q.email}{q.username ? ' · ' + q.username : ''}</div>
                  <div className="text-sm text-gray-700">{q.note || 'No note'} · {new Date(q.createdAt).toLocaleString()}</div>
                </div>
                <span className="flex gap-2">
                  <ActionButton outline onClick={() => act(api('POST', '/api/admin/requests/' + q.id, { approve: true }))}>Approve</ActionButton>
                  <button type="button" className="h-11 px-4 rounded-lg border border-gray-400"
                    onClick={() => act(api('POST', '/api/admin/requests/' + q.id, { approve: false }))}>Decline</button>
                </span>
              </div>
            ))}
          </Panel>
        )}
        <Panel className={usersOnly}>
          <form onSubmit={savePw} className="flex flex-col gap-3">
            <h2 className="text-xl font-bold m-0">Shared password</h2>
            <label htmlFor="ad-pw" className="text-sm text-gray-700">The one password all invited players sign in with. Changing it does not sign anyone out; players need the new one the next time they sign in. Admins keep their own password.</label>
            <div className="flex flex-wrap items-center gap-3">
              <input id="ad-pw" type="text" autoComplete="off" placeholder="New shared password" value={newPw} maxLength={100}
                className="h-11 flex-1 min-w-[200px] rounded-lg border border-gray-400 px-3 text-base" onChange={(e) => setNewPw(e.target.value)} />
              <ActionButton type="submit" disabled={newPw.length < 8}>Change</ActionButton>
            </div>
            <span role="status" className="text-sm text-gray-700">
              {pwNote || (pwChanged ? 'Last changed here ' + new Date(pwChanged).toLocaleString() + '.' : 'Still the password set in the hosting panel.')}
            </span>
          </form>
        </Panel>
        {tab === 'activity' && engines && (
          <Panel>
            <h2 className="text-xl font-bold m-0 mb-2">Robots</h2>
            <div className="text-[15px] flex flex-col gap-1">
              <div>Card play: <b>PlayEngine {engines.play.version}</b>{engines.play.trial && <span className="ml-2 px-2 rounded-full text-sm font-semibold bg-amber-100 text-amber-900">on trial</span>}</div>
              <div>Bidding: <b>BiddingEngine {engines.bidding.version}</b>{engines.bidding.trial && <span className="ml-2 px-2 rounded-full text-sm font-semibold bg-amber-100 text-amber-900">on trial</span>}</div>
              <div className="text-sm text-gray-700">
                Since {new Date(engines.stats.since).toLocaleString()}: {engines.stats.cards} robot cards, slowest {engines.stats.slowestMs} ms,{' '}
                <span className={engines.stats.fallbacks ? 'text-red-700 font-semibold' : ''}>{engines.stats.fallbacks} without a usable card from the engine</span>
                {engines.stats.lastFallback ? ' (last: ' + engines.stats.lastFallback.contract + ', trick ' + engines.stats.lastFallback.trick + ', ' + engines.stats.lastFallback.seat + ')' : ''}.
              </div>
              {engines.play.trial && <div className="text-sm text-gray-700">This engine comes from the Hand Viewer's test site. To go back to the Hand Viewer's live engine, set ENGINE_TRIAL=0 in the hosting panel and restart.</div>}
            </div>
          </Panel>
        )}
        <Panel className={usersOnly + ' order-first'}>
          <h2 className="text-xl font-bold m-0 mb-1">Players {users ? '(' + users.length + ')' : ''}</h2>
          <div className="text-sm text-gray-700 mb-3">A blocked player is signed out at once and cannot sign in again, by password or from WordPress.</div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm text-left">
              <thead><tr className="border-b border-gray-300">
                <th className="py-2 pr-3">ID</th><th className="py-2 pr-3">Username</th><th className="py-2 pr-3">Email</th>
                <th className="py-2 pr-3">Role</th><th className="py-2 pr-3">Signs in</th><th className="py-2 pr-3">Last seen</th><th className="py-2 pr-3">Hands (7 days / all)</th><th className="py-2"></th>
              </tr></thead>
              <tbody>
                {(users || []).map((u) => (
                  <tr key={u.id} className="border-b border-gray-200">
                    <td className="py-2 pr-3">{u.id}</td>
                    <td className="py-2 pr-3">{u.username || <span className="text-gray-600">(not signed in yet)</span>}
                      {u.blockedAt && <span className="ml-2 px-2 rounded-full text-xs font-semibold bg-red-100 text-red-800">blocked</span>}</td>
                    <td className="py-2 pr-3 break-all">{u.email}</td>
                    <td className="py-2 pr-3">{u.role === 'user' ? 'player' : u.role}</td>
                    <td className="py-2 pr-3 whitespace-nowrap">{u.viaWordPress ? 'WordPress' : u.username ? 'Password' : '—'}</td>
                    <td className="py-2 pr-3 whitespace-nowrap">{u.online ? <span className="text-green-700 font-semibold">here now</span> : u.lastSeenAt ? new Date(u.lastSeenAt).toLocaleString() : '—'}</td>
                    <td className="py-2 pr-3">{u.hands7} / {u.handsAll}</td>
                    <td className="py-2 whitespace-nowrap">
                      {u.id !== me.id && (
                        <span className="flex gap-2">
                          <select aria-label={'Role of ' + (u.username || u.email)} className="h-9 px-1 rounded border border-gray-400 bg-white" value={u.role}
                            onChange={(e) => act(api('POST', '/api/admin/users/' + u.id + '/role', { role: e.target.value }))}>
                            <option value="user">Player</option><option value="teacher">Teacher</option><option value="admin">Admin</option>
                          </select>
                          <button type="button" className={'h-9 px-2 rounded border ' + (u.blockedAt ? 'border-gray-400' : 'border-red-600 text-red-700')}
                            onClick={() => { if (u.blockedAt || window.confirm('Block ' + (u.username || u.email) + '? They are signed out at once and cannot sign in again until you unblock them.')) act(api('POST', '/api/admin/users/' + u.id + '/block', { blocked: !u.blockedAt })); }}>
                            {u.blockedAt ? 'Unblock' : 'Block'}</button>
                          <button type="button" className="h-9 px-2 rounded border border-gray-400"
                            onClick={() => { if (window.confirm('Remove ' + u.email + '?')) act(api('DELETE', '/api/admin/users/' + u.id, {})); }}>
                            Remove</button>
                        </span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Panel>
      </div>
    </Page>
  );
}

// ---- Play with Friends (the club) ----
// One view of the club from the server, fetched again whenever it says
// "changed" over the live connection (and every 20 seconds as a fallback).
function useClub(active, onSignedOut) {
  const [club, setClub] = React.useState(null);
  // A player who is no longer signed in (the session ended, or an admin blocked them) goes back to the sign-in page.
  const refresh = React.useCallback(() => api('GET', '/api/club').then(setClub).catch((e) => { if (e && e.message === 'not_signed_in' && onSignedOut) onSignedOut(); }), []);
  React.useEffect(() => {
    if (!active) { setClub(null); return undefined; }
    let ws = null, timer = null, closed = false, wait = 1000;
    const connect = () => {
      try { ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws'); }
      catch (e) { return; }
      ws.onopen = () => { wait = 1000; refresh(); ['club', 'table'].forEach((r) => window.dispatchEvent(new CustomEvent('lbo-chat', { detail: r }))); };
      ws.onmessage = (ev) => {
        let d = null; try { d = JSON.parse(ev.data); } catch (e) {}
        if (d && d.type === 'chat') window.dispatchEvent(new CustomEvent('lbo-chat', { detail: d.room }));
        else refresh();
      };
      ws.onclose = () => { if (!closed) { refresh(); timer = setTimeout(connect, wait); wait = Math.min(wait * 2, 15000); } };
    };
    connect(); refresh();
    const poll = setInterval(refresh, 20000);
    return () => { closed = true; clearTimeout(timer); clearInterval(poll); if (ws) ws.close(); };
  }, [active]);
  return [club, refresh];
}

function UserSearch({ onPick, pickLabel, skipIds }) {
  const [q, setQ] = React.useState('');
  const [found, setFound] = React.useState(null);
  React.useEffect(() => {
    if (q.trim().length < 2) { setFound(null); return undefined; }
    const t = setTimeout(() => api('GET', '/api/users/search?q=' + encodeURIComponent(q.trim())).then((r) => setFound(r.users)).catch(() => setFound([])), 300);
    return () => clearTimeout(t);
  }, [q]);
  const list = (found || []).filter((u) => !(skipIds || []).includes(u.id));
  return (
    <div className="flex flex-col gap-2">
      <input aria-label="Find a player by username or full email address" placeholder="Username, or full email address" value={q}
        className="h-11 w-full rounded-lg border border-gray-400 px-3 text-base" onChange={(e) => setQ(e.target.value)} />
      {found && list.length === 0 && <div className="text-sm text-gray-700">Nobody found.</div>}
      {list.map((u) => (
        <div key={u.id} className="flex items-center justify-between gap-2">
          <span className="truncate">{u.username}</span>
          <ActionButton outline onClick={() => { onPick(u); setQ(''); }}>{pickLabel}</ActionButton>
        </div>
      ))}
    </div>
  );
}

function whereText(p, tables) {
  if (p.tableId) { const t = (tables || []).find((x) => x.id === p.tableId); return t ? 'at ' + t.hostName + "'s table" : 'at a table'; }
  return p.online === false ? 'not here now' : 'in the room';
}

function FriendsPanel({ club, refresh }) {
  const friends = (club && club.friends) || [];
  const act = (p) => p.then(refresh).catch(() => {});
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
      <div>
        <div className="text-sm font-semibold mb-2">Add a friend</div>
        <UserSearch pickLabel="Add" skipIds={friends.map((f) => f.id)} onPick={(u) => act(api('POST', '/api/friends', { userId: u.id }))} />
        <div className="text-[13px] text-gray-600 mt-2">Adding someone does not need their approval. Friends come first when you invite players to your table.</div>
      </div>
      <div>
        <div className="text-sm font-semibold mb-2">Your friends ({friends.length})</div>
        {friends.length === 0 && <div className="text-sm text-gray-700">No friends added yet.</div>}
        {friends.map((f) => (
          <div key={f.id} className="flex items-center justify-between gap-2 min-h-[44px] border-b border-gray-200">
            <span className="truncate">{f.username} <span className="text-[13px] text-gray-600">· {whereText(f, club.tables)}</span></span>
            <button type="button" className="h-11 px-2 text-sm text-gray-700 underline" onClick={() => act(api('DELETE', '/api/friends/' + f.id, {}))}>Remove</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function CreateTable({ user, seat0, onClose, onCreated }) {
  const d = user.settings;
  const [system, setSystem] = React.useState(d.biddingSystem);
  const [aceAsking, setAce] = React.useState(d.aceAsking);
  const [open, setOpen] = React.useState(d.tableOpen);
  const [beginner, setBeginner] = React.useState(d.beginnerFriendly);
  const [seat, setSeat] = React.useState(seat0 || 'S');     // South unless a seat at an empty table was clicked
  const [error, setError] = React.useState('');
  const create = () => api('POST', '/api/club/tables', { system, aceAsking, open, beginnerFriendly: beginner, seat })
    .then(onCreated).catch((e) => setError(errorText(e.message)));
  return (
    <div className="fixed inset-0 z-50 bg-black/40 flex items-start sm:items-center justify-center p-3 overflow-y-auto" role="dialog" aria-modal="true" aria-label="Create a table">
      <Panel className="w-full max-w-md flex flex-col gap-4">
        <h2 className="text-xl font-bold m-0">Create a table</h2>
        <Choice label="Bidding system" options={SYSTEM_CHOICES} value={system} onChange={setSystem} />
        <Choice label="Ace asking" options={ACE_CHOICES} value={aceAsking} onChange={setAce} />
        <div className="text-[13px] text-gray-600 -mt-2">Robots at the table follow these.</div>
        <label className="flex items-center gap-3 min-h-[44px] text-[15px]">
          <input type="checkbox" className="w-5 h-5" checked={beginner} onChange={(e) => setBeginner(e.target.checked)} /> Beginner friendly
        </label>
        <label className="flex items-start gap-3 min-h-[44px] text-[15px]">
          <input type="checkbox" className="w-5 h-5 mt-0.5" checked={!open} onChange={(e) => setOpen(!e.target.checked)} />
          <span>Private table<span className="block text-[13px] text-gray-600">You approve each request to sit or to kibitz.</span></span>
        </label>
        <Choice label="Your seat" options={SEAT_CHOICES} value={seat} onChange={setSeat} />
        <div className="text-[13px] text-gray-600 -mt-2">You can change seats at the table before play starts.</div>
        {error && <div role="alert" className="text-sm text-red-700">{error}</div>}
        <div className="flex gap-2 justify-end">
          <button type="button" className="h-11 px-4 rounded-lg border border-gray-400" onClick={onClose}>Cancel</button>
          <ActionButton onClick={create}>Open the table</ActionButton>
        </div>
      </Panel>
    </div>
  );
}

function TableCard({ t, friendIds, act }) {
  const cell = { N: 'col-start-2 row-start-1', W: 'col-start-1 row-start-2', E: 'col-start-3 row-start-2', S: 'col-start-2 row-start-3' };
  const empty = SEAT_ORDER.filter((s) => !t.seats[s]).length;
  return (
    <Panel className="flex flex-col gap-3 !p-4">
      <div className="flex flex-wrap items-baseline justify-between gap-x-3">
        <strong className="text-lg">{t.hostName}'s table</strong>
        <span className="text-sm text-gray-700">{tableLine(t)}</span>
      </div>
      <div className="flex flex-wrap gap-2 text-xs">
        <span className="px-2 py-0.5 rounded-full border border-gray-500">{t.open ? 'Open' : 'Private'}</span>
        {t.beginnerFriendly && <span className="px-2 py-0.5 rounded-full border border-gray-500">Beginner friendly</span>}
        <span className="px-2 py-0.5 rounded-full border border-gray-500">{empty ? empty + (empty === 1 ? ' open seat' : ' open seats') : 'Full'}</span>
        {t.playing && <span className="px-2 py-0.5 rounded-full border border-gray-500">Playing board {t.playing.board}</span>}
        {t.invited && <span className="px-2 py-0.5 rounded-full border border-green-700 bg-green-50">You are invited</span>}
      </div>
      <div className="grid grid-cols-3 grid-rows-3 gap-1 bg-gray-100 rounded-lg p-2 text-sm">
        {SEAT_ORDER.map((s) => {
          const p = t.seats[s];
          return (
            <div key={s} className={cell[s] + ' flex flex-col items-center justify-center min-h-[52px] text-center'}>
              <span className="text-xs font-bold">{SEAT_NAME[s]}</span>
              {p ? <span className={'truncate max-w-full ' + (!p.robot && friendIds.includes(p.id) ? 'font-semibold' : '')}>{p.username}</span>
                : t.playing && t.playing.midHand ? <span className="text-gray-600">open</span>
                : t.canSit ? <button type="button" className="h-9 px-3 rounded-lg border font-semibold" style={{ borderColor: ACTION, color: ACTION }}
                    onClick={() => act(api('POST', '/api/club/tables/' + t.id + '/sit', { seat: s }))}>Sit</button>
                : t.requested ? <span className="text-gray-600">open</span>
                : <button type="button" className="h-9 px-2 rounded-lg border border-gray-500"
                    onClick={() => act(api('POST', '/api/club/tables/' + t.id + '/request', { seat: s }))}>Ask to sit</button>}
            </div>
          );
        })}
      </div>
      <div className="flex flex-wrap items-center justify-between gap-2 text-sm">
        <span className="text-gray-700">{t.watchers.length ? 'Kibitzing: ' + t.watchers.map((w) => w.username).join(', ') : ''}</span>
        {!t.requested && (t.canSit
          ? <button type="button" className="h-9 px-3 rounded-lg border border-gray-500 bg-white" onClick={() => act(api('POST', '/api/club/tables/' + t.id + '/watch', {}))}>Kibitz</button>
          : <button type="button" className="h-9 px-3 rounded-lg border border-gray-500 bg-white" onClick={() => act(api('POST', '/api/club/tables/' + t.id + '/request', { watch: true }))}>Ask to kibitz</button>)}
      </div>
      {t.requested && (
        <div className="flex items-center justify-between gap-2 text-sm">
          <span>You asked to join. Waiting for {t.hostName}.</span>
          <button type="button" className="h-9 px-2 underline" onClick={() => act(api('POST', '/api/club/tables/' + t.id + '/cancel-request', {}))}>Cancel</button>
        </div>
      )}
      {t.invited && (
        <button type="button" className="self-end h-9 px-2 text-sm underline" onClick={() => act(api('POST', '/api/club/tables/' + t.id + '/decline-invite', {}))}>Not now</button>
      )}
    </Panel>
  );
}

// ---- play at the table: the Hand Viewer's own components ----
// BridgeApp.jsx (the Hand Viewer, loaded before this file) provides CardHandDisplay,
// TrickDisplay, AuctionDisplay, SummaryDisplay, TableNotice, NoticeBelow,
// useScreenSize, useNarrowTableFit, PAGE_HEIGHT. The table is drawn as the
// Hand Viewer's Play draws it, with the player's own seat in South's place:
// each hand is handed to the component under its place on the screen, and the
// club's one edit to the Hand Viewer (seat-label) writes the real seat and
// player above it.
const SUIT_SYM = { s: '♠', h: '♥', d: '♦', c: '♣', n: 'NT' };
const RED = { h: true, d: true };
// Table chat during a hand (the 💬 button, and new messages shown by the writer's seat). Off for now:
// the table chat stays in Table Settings. Set to true to bring it back.
const CHAT_IN_HAND = false;
const EMOTE = { hello: ['🤗', 'Hello'], thanks: ['🙏', 'Thank you'], heart: ['❤️', ''], leaving: ['👋', 'I must leave'] };
const NO_HAND = { s: [], h: [], d: [], c: [] };

// The table as it will be once the server has a card the player just played: the card leaves the
// hand and joins the trick at once, while the server is still being told (see `pending` below).
function withCard(g, c) {
  const hands = Object.assign({}, g.hands);
  if (hands[c.seat]) { const h = Object.assign({}, hands[c.seat]); h[c.suit] = (h[c.suit] || []).filter((r) => r !== c.rank); hands[c.seat] = h; }
  const trick = g.trick.concat({ suit: c.suit, rank: c.rank, position: c.seat });
  const next = SEAT_ORDER[(SEAT_ORDER.indexOf(c.seat) + 1) % 4];
  return Object.assign({}, g, { hands, trick, counts: Object.assign({}, g.counts, { [c.seat]: g.counts[c.seat] - 1 }),
    turn: trick.length < 4 ? next : null, actor: null });
}

function HVTable({ user, club, t, act, refresh, review, setReview }) {
  // A card the player has just played is shown played straight away (no wait for the server); it is
  // dropped as soon as the server's table has it, or put back if the server refuses it.
  const [pending, setPending] = React.useState(null);         // { seat, suit, rank, board, count }
  const g0 = t.game;
  const settled = pending && (g0.board !== pending.board || g0.phase !== 'play' || g0.counts[pending.seat] < pending.count);
  React.useEffect(() => { if (settled) setPending(null); }, [settled]);
  React.useEffect(() => {                                      // never stuck: after 8 s ask the server again
    if (!pending) return undefined;
    const x = setTimeout(() => { setPending(null); refresh(); }, 8000);
    return () => clearTimeout(x);
  }, [pending]);
  const g = pending && !settled ? withCard(g0, pending) : g0;
  const mySeat = club.me.seat;                               // null for a kibitzer
  const base = mySeat || 'S';
  const shift = (SEAT_ORDER.indexOf(base) - 2 + 4) % 4;      // real seat at a place on the screen
  const realAt = (place) => SEAT_ORDER[(SEAT_ORDER.indexOf(place) + shift) % 4];
  const placeOf = (real) => SEAT_ORDER[(SEAT_ORDER.indexOf(real) - shift + 4) % 4];

  const { isNarrow, isLandMobile, isSmall, vh, vw } = useScreenSize();
  // The Hand Viewer's card unit (it allows 130px for its header and button bar; the club's take about 20px more).
  const unitW = Math.max(24, Math.min(Math.floor((vh - 150) / 9.8), Math.floor(vw / 13)));
  const unitH = Math.floor(unitW * (vw < 500 ? 1.6 : 1.4));
  const fitter = useNarrowTableFit();
  const { page: pageRef, felt: feltRef, n: nRef, s: sRef, row: rowRef } = fitter.refs;
  const fit = fitter.fit, scroll = fitter.scroll;
  // Keeps the player's own hand clear of the bottom bar: after each render, how much the table is
  // taller than the room it has. The auction box (bidding) or the trick area (card play, wide
  // layouts) gives up that much height; anything still left over scrolls above the bar.
  const [squeeze, setSqueeze] = React.useState(0);
  const roomRef = React.useRef(null), contentRef = React.useRef(null);
  const squeezeLog = React.useRef([]), squeezeRetry = React.useRef(null);
  const [, setSqueezeTick] = React.useState(0);
  React.useEffect(() => () => clearTimeout(squeezeRetry.current), []);
  React.useLayoutEffect(() => {
    const room = roomRef.current, content = contentRef.current;
    if (!room || !content || isNarrow && g.phase !== 'bidding') { if (squeeze) setSqueeze(0); return; }
    const cs = getComputedStyle(content.parentElement);         // the felt, whose padding is not room
    const pad = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0);
    const need = Math.ceil(content.getBoundingClientRect().height - (room.clientHeight - pad));
    // Shrink when anything is hidden; give the room back only when there is plenty to spare (a dead band, so it settles).
    if (need <= 0 && need > -24) return;
    const next = Math.max(0, Math.min(600, squeeze + need + (need > 0 ? 4 : 12)));
    if (Math.abs(next - squeeze) <= 1) return;
    const now = Date.now(), log = squeezeLog.current.filter((x) => now - x < 1000);
    if (log.length >= 6) { clearTimeout(squeezeRetry.current); squeezeRetry.current = setTimeout(() => setSqueezeTick((n) => n + 1), 600); return; }   // never more than a few changes a second; look again shortly
    squeezeLog.current = log.concat(now);
    setSqueeze(next);
  });

  const showAuction = review === 'auction', showLast = review === 'last';
  React.useEffect(() => { if (review === 'last') setReview(null); }, [g.trick.length, g.phase]);
  React.useEffect(() => { setReview(null); }, [g.board]);
  const [claiming, setClaiming] = React.useState(null);    // the claim dialog: the number of tricks chosen
  // ---- table chat during the hand: the 💬 panel above the bar, and a new message shown by its writer's seat ----
  const tableChat = useChat('table', CHAT_IN_HAND, t.id);
  const [chatOpen, setChatOpen] = React.useState(false);
  const chatUnread = useUnread(tableChat, user.id, chatOpen);
  const arrived = React.useRef(null);                        // message id -> when this browser first saw it
  const [, setBubbleTick] = React.useState(0);
  if (tableChat.loaded) {
    if (!arrived.current) { arrived.current = {}; tableChat.messages.forEach((m) => { arrived.current[m.id] = 0; }); }
    else tableChat.messages.forEach((m) => { if (!(m.id in arrived.current)) arrived.current[m.id] = Date.now(); });
  }
  const newest = tableChat.messages.length ? tableChat.messages[tableChat.messages.length - 1].id : 0;
  React.useEffect(() => { const x = setTimeout(() => setBubbleTick((n) => n + 1), 8100); return () => clearTimeout(x); }, [newest]);
  const bubbleFor = (userId) => {
    if (!arrived.current || !userId) return null;
    const now = Date.now();
    const m = tableChat.messages.slice().reverse().find((x) => x.userId === userId && !x.kib && now - (arrived.current[x.id] || 0) < 8000);
    return m ? m.body : null;
  };
  const emoteKey = JSON.stringify(g.emotes);
  React.useEffect(() => {
    if (emoteKey === '{}') return undefined;
    const x = setTimeout(refresh, 6200);
    return () => clearTimeout(x);
  }, [emoteKey]);

  const paused = g.vacant.length > 0;
  const myTurn = !!mySeat && !paused && g.actor === mySeat && !!g.turn;
  const bidding = g.phase === 'bidding';
  const summary = g.phase === 'summary';
  const led = g.trick.length && !g.trickWinner ? g.trick[0].suit : null;

  // ---- the auction, with the Hand Viewer's alerts ----
  // A call the player is about to make can carry an alert (preAlert); their own
  // calls can be changed afterwards (sent to the server a moment after typing stops).
  const [preAlert, setPreAlert] = React.useState(null);
  const [mineEdits, setMineEdits] = React.useState({});        // index -> { text, on } while being changed
  React.useEffect(() => { setPreAlert(null); setMineEdits({}); }, [g.calls.length, g.board]);
  const explanations = {}, isAlert = {};
  Object.keys(g.notes).forEach((i) => { explanations[i] = g.notes[i]; isAlert[i] = !!g.alerts[i]; });
  Object.keys(g.alerts).forEach((i) => { isAlert[i] = true; });
  Object.keys(mineEdits).forEach((i) => {
    const e = mineEdits[i];
    if (e.text !== undefined) { if (e.text) explanations[i] = e.text; else delete explanations[i]; }
    if (e.on !== undefined) isAlert[i] = e.on;
  });
  const saveTimer = React.useRef(null);
  const editMine = (idx, change) => {
    setMineEdits((prev) => {
      const next = Object.assign({}, prev, { [idx]: Object.assign({}, prev[idx], change) });
      clearTimeout(saveTimer.current);
      saveTimer.current = setTimeout(() => {
        const e = next[idx] || {};
        const text = e.text !== undefined ? e.text : (g.notes[idx] || '');
        const on = e.on !== undefined ? e.on : (g.alerts[idx] ? true : !g.notes[idx]);
        api('POST', '/api/club/alert', { index: idx, alert: { on, text } }).then(refresh).catch(() => {});
      }, 600);
      return next;
    });
  };
  const makeCall = (bid) => {
    const call = bid.type === 'bid' ? { type: 'bid', level: bid.level, suit: bid.suit } : { type: bid.type };
    const a = preAlert && (preAlert.on || (preAlert.text || '').trim()) ? { on: !!preAlert.on, text: preAlert.text || '' } : null;
    act(api('POST', '/api/club/call', a ? { call, alert: a } : { call }));
  };
  const mySeats = mySeat ? new Set([mySeat]) : null;
  const auctionProps = {
    auction: g.calls, dealer: g.dealer, bidExplanations: explanations, bidIsAlert: isAlert, alertDefaultOn: true,
    handData: { vulnerability: g.vul, dealer: g.dealer }, activePlayer: bidding ? g.turn : null,
    onSetBidExplanation: mySeat && !summary ? (idx, text) => editMine(idx, { text }) : undefined,
    onSetBidAlert: mySeat && !summary ? (idx, on) => editMine(idx, { on }) : undefined,
    editableBidSeats: mySeat && !summary ? mySeats : new Set()
  };

  // ---- the hands ----
  const pilot = g.pilot;
  const handProps = (place) => {
    const real = realAt(place);
    const hand = g.hands[real];
    const mine = myTurn && g.phase === 'play' && g.turn === real;
    return {
      hand: hand || NO_HAND, position: place, isVisible: !!hand, playedCards: [],
      isDummy: !bidding && g.dummy === real, isActivePlayer: mine, visibleHands: new Set(), hasContract: !bidding,
      onToggleView: null, labelPosition: 'top', isClickable: mine,
      onCardClick: (p, suit, rank) => {
        const seat = realAt(p);
        if (pending) return;
        setPending({ seat, suit, rank, board: g0.board, count: g0.counts[seat] });
        act(api('POST', '/api/club/card', { seat, suit, rank }).catch((e) => { setPending(null); throw e; }));
      },
      leadSuit: mine ? led : null, trumpSuit: bidding ? null : g.trumpSuit, touchBelow: place === 'N' || place === 'S',
      unitCardW: unitW, unitCardH: unitH
    };
  };
  // The label above each hand: the real seat, the player, and a quick message when one was sent.
  window.LBO_SEAT_LABEL = (place, isDummy, narrow) => {
    const real = realAt(place), p = t.seats[real];
    const who = !p ? 'empty' : p.robot ? 'Robot' : p.id === user.id ? 'You' : p.username;
    const side = place === 'E' || place === 'W';
    const e = g.emotes[real];
    const said = p && !p.robot ? bubbleFor(p.id) : null;
    const max = narrow ? 22 : 48;
    return (
      <span className="relative inline-flex items-baseline gap-1 whitespace-nowrap">
        <span>{real}</span>
        {!(narrow && side) && <span className="font-sans font-normal" style={{ fontSize: '0.6em' }}>{who}</span>}
        {isDummy && <span className="text-xs text-white/70">{narrow ? '(D)' : '(Dummy)'}</span>}
        {bidding && g.dealer === real && !(narrow && side) && <span className="text-xs text-white/70">Dealer</span>}
        {e && <span className="font-sans font-normal bg-white text-gray-900 rounded-full px-2 text-sm">{EMOTE[e][0]}{narrow ? '' : ' ' + EMOTE[e][1]}</span>}
        {said && <span className="font-sans font-normal bg-white text-gray-900 rounded-xl px-2 text-sm shadow" title={said}>💬 {said.length > max ? said.slice(0, max - 1) + '…' : said}</span>}
      </span>
    );
  };
  React.useEffect(() => () => { delete window.LBO_SEAT_LABEL; }, []);

  // ---- notices ----
  let pilotText = '';
  if (pilot) {
    const p = t.seats[pilot.seat];
    pilotText = SEAT_NAME[pilot.for] + ' (Robot) is declarer: ' + (p && p.id === user.id ? 'you play' : (p ? p.username : SEAT_NAME[pilot.seat]) + ' plays') + ' both ' + SEAT_NAME[pilot.for] + ' and ' + SEAT_NAME[pilot.seat] + '.';
  }
  let prompt = null;
  const claim = g.claim;
  const claimer = claim ? t.seats[claim.player !== undefined ? claim.player : claim.by] : null;
  if (claim) {
    const by = SEAT_NAME[claim.by];
    prompt = <TableNotice>{by + ' claims ' + claim.tricks + ' of the remaining ' + claim.left + ' tricks.'}</TableNotice>;
  } else if (paused) prompt = <TableNotice>{g.vacant.map((x) => SEAT_NAME[x]).join(' and ') + (g.vacant.length > 1 ? ' are' : ' is') + ' empty. ' + (t.isHost ? 'Choose what happens next.' : 'Waiting for the host.')}</TableNotice>;
  else if (summary) prompt = t.isHost ? null : <TableNotice>{isNarrow ? 'Waiting for the host' : 'Waiting for the host to deal the next hand.'}</TableNotice>;
  else if (g.turn && !g.trickWinner) {
    if (myTurn) prompt = <TableNotice prompt>{bidding ? 'Your turn to bid' : g.turn === mySeat ? 'Your turn to play' : 'Your turn: play from ' + SEAT_NAME[g.turn] + (g.turn === g.dummy ? ' (dummy)' : '')}</TableNotice>;
    else {
      const p = t.seats[g.actor];
      prompt = <TableNotice>{SEAT_NAME[g.turn] + "'s turn" + (g.turn !== g.actor ? ' (played by ' + SEAT_NAME[g.actor] + ')' : '') + (p && p.robot ? ' (robot)' : '')}</TableNotice>;
    }
  }
  if (!claim && g.claimNote && g.phase === 'play') prompt = <div className="flex flex-col items-center gap-1"><TableNotice>{g.claimNote.text}</TableNotice>{prompt}</div>;
  const notices = (pilotText && g.phase === 'play' && g.trick.length === 0 && g.counts[g.declarer] === 13)
    ? <div className="flex flex-col items-center gap-1"><TableNotice>{pilotText}</TableNotice>{prompt}</div> : prompt;

  // ---- the centre ----
  const centerW = isNarrow ? Math.min(Math.floor(vw * 0.55), Math.floor(vh * 0.35)) : isLandMobile ? 180 : Math.min(unitW * 4, Math.floor(vh * 0.50));
  const centerH0 = isNarrow ? Math.min(Math.floor(vw * 0.55), Math.floor(vh * 0.30)) : isLandMobile ? 120 : Math.min(unitH * 3.5, Math.floor(vh * 0.42));
  const centerH = isNarrow ? centerH0 : Math.max(Math.min(centerH0, isLandMobile ? 76 : 150), centerH0 - squeeze);
  const placed = (trick) => trick.map((c) => Object.assign({}, c, { position: placeOf(c.position) }));
  const total = g.scores.reduce((n, x) => n + x.ns, 0);
  const hostRow = (
    <div className="w-full flex border-t border-slate-100 gap-2 px-2 py-2" data-tb-guard="">
      <button type="button" onClick={(e) => { e.stopPropagation(); act(api('POST', '/api/club/end', {})); }}
        className="flex-1 min-w-0 whitespace-nowrap font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg py-2 text-sm">Table settings</button>
      <button type="button" onClick={(e) => { e.stopPropagation(); act(api('POST', '/api/club/start', {})); }}
        className="flex-1 min-w-0 whitespace-nowrap font-semibold text-white rounded-lg py-2 text-sm" style={{ backgroundColor: '#16a34a' }}>Next Hand</button>
    </div>
  );
  const pausedPanel = (
    <div data-tb-guard="" className="bg-white rounded-xl shadow-lg p-2 flex flex-col gap-2 w-full">
      {g.vacant.map((x) => (
        <button key={x} type="button" className="rounded-lg py-2 text-sm font-semibold text-white" style={{ backgroundColor: ACTION }}
          onClick={(e) => { e.stopPropagation(); act(api('POST', '/api/club/robot', { seat: x, on: true })); }}>Robot plays {SEAT_NAME[x]}</button>
      ))}
      <button type="button" className="rounded-lg py-2 text-sm font-semibold bg-slate-100 text-slate-700"
        onClick={(e) => { e.stopPropagation(); act(api('POST', '/api/club/end', {})); }}>End game: back to table settings</button>
    </div>
  );
  const closeX = (
    <div className="absolute -top-3 -right-3 z-50 cursor-pointer bg-slate-700 hover:bg-slate-600 rounded-full p-0.5 shadow-lg" onClick={(e) => { e.stopPropagation(); setReview(null); }}>
      <svg className="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
    </div>
  );
  // A claim waiting for the opponents: the claimer's cards are face up; each opponent accepts or rejects.
  const mustAnswer = claim && mySeat && claim.from.includes(mySeat) && !claim.answers[mySeat];
  const claimPanel = claim && (
    <div data-tb-guard="" className="bg-white rounded-xl shadow-lg p-3 flex flex-col gap-2 w-full text-center font-serif" onClick={(e) => e.stopPropagation()}>
      <div className="font-bold text-slate-800">{SEAT_NAME[claim.by]} claims {claim.tricks} of the remaining {claim.left} {claim.left === 1 ? 'trick' : 'tricks'}</div>
      <div className="text-sm text-slate-600">{claim.from.map((p) => SEAT_NAME[p] + ': ' + (claim.answers[p] === 'accept' ? 'accepts' : 'deciding…')).join(' · ')}</div>
      {mustAnswer && (
        <div className="flex gap-2">
          <button type="button" className="flex-1 rounded-lg py-2 text-sm font-semibold bg-slate-100 text-slate-700" onClick={() => act(api('POST', '/api/club/claim/answer', { accept: false }))}>Reject</button>
          <button type="button" className="flex-1 rounded-lg py-2 text-sm font-semibold text-white" style={{ backgroundColor: '#16a34a' }} onClick={() => act(api('POST', '/api/club/claim/answer', { accept: true }))}>Accept</button>
        </div>
      )}
      {claimer && !claimer.robot && claimer.id === user.id && (
        <button type="button" className="rounded-lg py-2 text-sm font-semibold bg-slate-100 text-slate-700" onClick={() => act(api('POST', '/api/club/claim/withdraw', {}))}>Withdraw the claim</button>
      )}
    </div>
  );
  let center;
  if (paused && t.isHost) center = <div className="w-full h-full flex items-center">{pausedPanel}</div>;
  else if (claim) center = <div className="w-full h-full flex items-center">{claimPanel}</div>;
  else if (showLast && g.lastTrick) {
    center = (
      <div data-tb-guard="" className="relative bg-white rounded-xl shadow-lg flex flex-col items-center justify-center w-full h-full" style={{ padding: 3 }}>
        <div className="text-center text-slate-500 text-xs font-serif mb-1">Previous Trick</div>
        <TrickDisplay currentTrick={placed(g.lastTrick.trick)} activePlayer={null} useCards={true} trumpSuit={g.trumpSuit} centerW={centerW} centerH={Math.max(60, centerH - 48)} minCardW={isNarrow ? Math.floor(unitW * 1.5) : unitW} />
        <div className="text-center text-slate-400 text-xs mt-1">Won by {g.lastTrick.winner}</div>
        {closeX}
      </div>
    );
  } else if (summary) {
    center = (
      <div className="w-full bg-white/95 rounded-xl shadow-lg" data-tb-guard="">
        <SummaryDisplay contract={g.contract} declarer={g.declarer} nsTricks={g.tricks.NS} ewTricks={g.tricks.EW} vulnerability={g.vul}
          subNote={g.claimed ? SEAT_NAME[g.claimed.by] + ' claimed ' + g.claimed.tricks + ' of the last ' + g.claimed.left + ' tricks.' : null}
          note={g.scores.length > 1 ? 'After ' + g.scores.length + ' boards: ' + (total === 0 ? 'level' : (total > 0 ? 'N-S' : 'E-W') + ' ahead by ' + Math.abs(total)) : null} />
        {t.isHost && hostRow}
      </div>
    );
  } else if (showAuction) {
    center = (
      <div data-tb-guard="" className="relative bg-white rounded-xl shadow-lg w-full h-full flex items-start justify-center" style={{ padding: 4 }}>
        <AuctionDisplay {...auctionProps} />
        {closeX}
      </div>
    );
  } else {
    center = (
      <div className="cursor-pointer w-full h-full" onClick={() => { if (g.lastTrick && !g.trick.length) setReview('last'); }}>
        <TrickDisplay currentTrick={placed(g.trick)} activePlayer={g.turn ? placeOf(g.turn) : null} useCards={true} trumpSuit={g.trumpSuit} centerW={centerW} centerH={centerH} minCardW={isNarrow ? Math.floor(unitW * 1.5) : unitW} />
      </div>
    );
  }

  // ---- the bidding screen (the Hand Viewer's v2.39 layout: the auction in the W/E row) ----
  const ewHidden = !g.hands[realAt('W')] && !g.hands[realAt('E')];
  const editCenterW = isNarrow ? Math.min(Math.floor(vw * 0.55), Math.floor(vh * 0.35)) : isLandMobile ? 180 : Math.min(unitW * 4, Math.floor(vh * 0.50));
  const editCenterH = isNarrow ? Math.min(Math.floor(vw * 0.55), Math.floor(vh * 0.34)) : isLandMobile ? 140 : Math.min(unitH * 3.5, Math.floor(vh * 0.42), 520);
  const panelH0 = ewHidden && !isLandMobile ? Math.max(editCenterH, Math.min(320, Math.floor(vh * 0.42))) : editCenterH;
  const panelH = Math.max(Math.min(panelH0, isLandMobile ? 130 : 160), panelH0 - squeeze);
  const felt = { background: 'radial-gradient(ellipse at center, #006637 0%, #00512C 55%, #003d20 100%)' };
  const canClaim = g.phase === 'play' && myTurn && !claim && !g.trickWinner;
  const claimDialog = claiming !== null && (
    <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-3" role="dialog" aria-modal="true" aria-label="Claim" onClick={() => setClaiming(null)}>
      <div className="bg-white rounded-xl shadow-lg p-4 w-full max-w-sm flex flex-col gap-3 font-serif" onClick={(e) => e.stopPropagation()}>
        <div className="text-lg font-bold text-slate-800">🏁 Claim</div>
        <div className="text-sm text-slate-700">How many of the remaining {g.tricksLeft} tricks will your side take? Your cards will be shown to everyone, and the opponents accept or reject the claim.</div>
        <div className="grid grid-cols-7 gap-1">
          {Array.from({ length: g.tricksLeft + 1 }, (_, n) => g.tricksLeft - n).map((n) => (
            <button key={n} type="button" aria-pressed={claiming === n} onClick={() => setClaiming(n)}
              className={'h-10 rounded-md border text-base font-semibold ' + (claiming === n ? 'border-2 border-green-700 bg-green-50' : 'border-slate-300 bg-white')}>{n}</button>
          ))}
        </div>
        <div className="flex gap-2">
          <button type="button" className="flex-1 rounded-lg py-2 text-sm font-semibold bg-slate-100 text-slate-700" onClick={() => setClaiming(null)}>Cancel</button>
          <button type="button" className="flex-1 rounded-lg py-2 text-sm font-semibold text-white" style={{ backgroundColor: ACTION }}
            onClick={() => { const n = claiming; setClaiming(null); act(api('POST', '/api/club/claim', { tricks: n })); }}>
            Claim {claiming} {claiming === 1 ? 'trick' : 'tricks'}</button>
        </div>
      </div>
    </div>
  );
  const chatSheet = chatOpen && (
    <div data-tb-guard="" className="absolute bottom-full left-0 right-0 sm:left-auto sm:right-3 sm:w-[400px] bg-white border border-slate-200 rounded-t-xl shadow-2xl p-3 flex flex-col gap-2 z-40"
      role="dialog" aria-label="Table chat" onClick={(e) => e.stopPropagation()}>
      <div className="flex items-center justify-between">
        <span className="font-bold text-slate-800">Table chat</span>
        <button type="button" aria-label="Close the chat" className="h-9 w-9 rounded-full hover:bg-slate-100 text-lg" onClick={() => setChatOpen(false)}>✕</button>
      </div>
      <ChatPanel chat={tableChat} user={user} compact listClass={isLandMobile ? 'max-h-[30vh]' : 'max-h-[35vh]'}
        note={!mySeat && !summary ? 'During a hand, only the other kibitzers see what you write.' : null} />
    </div>
  );
  const chatButton = (
    <button key="chat" type="button" aria-label="Table chat" aria-expanded={chatOpen} onClick={() => setChatOpen(!chatOpen)}
      className={(isLandMobile ? 'h-8' : 'h-11 sm:h-9') + (vw < 400 ? ' px-2' : ' px-3') + ' relative flex-shrink-0 rounded-full border text-base whitespace-nowrap ' + (chatOpen ? 'border-2 border-green-700 bg-green-50' : 'border-gray-400 bg-white')}>
      💬<span className="hidden sm:inline text-sm"> Chat</span>
      {chatUnread > 0 && !chatOpen && <span className="absolute -top-1.5 -right-1.5 min-w-[20px] h-5 px-1 rounded-full text-white text-xs font-semibold flex items-center justify-center" style={{ background: '#dc2626' }}>{chatUnread}</span>}
    </button>
  );
  const emoteBar = (mySeat || CHAT_IN_HAND) && (
    <div className={TOOLBAR_CLASS.replace('flex-wrap', 'flex-nowrap').replace('gap-2 px-3', vw < 400 ? 'gap-1.5 px-2' : 'gap-2 px-3').replace('py-2', isLandMobile ? 'py-1' : 'py-2') + ' relative bg-white border-t border-slate-200'}>
      {claimDialog}
      {CHAT_IN_HAND && chatSheet}
      {CHAT_IN_HAND && chatButton}
      {mySeat && Object.keys(EMOTE).map((kind) => (
        <button key={kind} type="button" aria-label={EMOTE[kind][1] || 'Heart'} onClick={() => act(api('POST', '/api/club/emote', { kind }))}
          className={(isLandMobile ? 'h-8' : 'h-11 sm:h-9') + (vw < 400 ? ' px-2' : ' px-3') + ' flex-shrink-0 rounded-full border border-gray-400 bg-white text-base whitespace-nowrap'}>{EMOTE[kind][0]}<span className="hidden sm:inline text-sm"> {EMOTE[kind][1]}</span></button>
      ))}
      {mySeat && g.phase === 'play' && (
        <button type="button" aria-label="Claim" disabled={!canClaim} onClick={() => setClaiming(g.tricksLeft)}
          title={canClaim ? 'Claim tricks' : 'You can claim when it is your turn to play'}
          className={(isLandMobile ? 'h-8' : 'h-11 sm:h-9') + (vw < 400 ? ' px-2' : ' px-3') + ' flex-shrink-0 rounded-full border border-gray-400 bg-white text-base whitespace-nowrap disabled:opacity-40'}>🏁<span className={'text-sm' + (vw < 360 ? ' sr-only' : '')}> Claim</span></button>
      )}
    </div>
  );

  if (bidding && !paused) {
    const panel = (
      <div data-tb-guard="" className="relative flex items-start justify-center bg-white rounded-xl shadow-lg" style={{ width: '100%', height: panelH, padding: isNarrow || isLandMobile ? 4 : 8 }}>
        <AuctionDisplay fillHeight={true} {...auctionProps} onBid={myTurn ? makeCall : undefined}
          preAlertSeats={myTurn ? mySeats : null} preAlert={preAlert} onPreAlert={setPreAlert} />
      </div>
    );
    return (
      <div className="flex-1 min-h-0 flex flex-col">
        <div ref={roomRef} className="flex-1 w-full min-h-0 overflow-y-auto">
          <div className={(isNarrow ? 'px-1 py-1' : isSmall ? 'px-2 py-2' : 'px-3 py-3') + ' shadow-2xl flex flex-col'} style={{ minHeight: '100%', justifyContent: 'safe center', ...felt }}>
            <div ref={contentRef} className="relative w-full flex flex-col items-center gap-1">
              <CardHandDisplay {...handProps('N')} />
              <div className="flex items-start justify-between w-full" style={ewHidden ? { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', alignItems: 'start' } : undefined}>
                <div style={{ flex: '1 1 0', minWidth: 0, display: 'flex', justifyContent: 'flex-start', gridArea: ewHidden ? '1 / 1' : undefined, maxHeight: ewHidden ? '1.5rem' : undefined }}>
                  <CardHandDisplay {...handProps('W')} align="start" />
                </div>
                {ewHidden
                  ? <div style={{ gridArea: '1 / 1', justifySelf: 'center', alignSelf: 'center', width: 'min(100%, ' + Math.max(editCenterW, 360) + 'px)', marginTop: isLandMobile ? 0 : '1.5rem', position: 'relative', zIndex: 1 }}>{panel}<NoticeBelow>{notices}</NoticeBelow></div>
                  : <div style={{ width: editCenterW, maxWidth: '90vw', flexShrink: 0, alignSelf: 'center', position: 'relative' }}>{panel}<NoticeBelow>{notices}</NoticeBelow></div>}
                <div style={{ flex: '1 1 0', minWidth: 0, display: 'flex', justifyContent: 'flex-end', gridArea: ewHidden ? '1 / 1' : undefined, maxHeight: ewHidden ? '1.5rem' : undefined }}>
                  <CardHandDisplay {...handProps('E')} align="end" />
                </div>
              </div>
              <div style={{ marginTop: isLandMobile ? '2rem' : '2.5rem' }}><CardHandDisplay {...handProps('S')} /></div>
            </div>
          </div>
        </div>
        {emoteBar}
      </div>
    );
  }

  // ---- card play and the score (the Hand Viewer's Play layout) ----
  const centerBox = (style) => (
    <div data-tb-guard="" className="flex-shrink-0 relative flex items-center justify-center" style={Object.assign({ width: centerW, height: summary ? undefined : centerH, minHeight: centerH }, style)}>
      {center}<NoticeBelow>{notices}</NoticeBelow>
    </div>
  );
  let table;
  if (isNarrow) {
    const ewFullH = 13 * unitW - 12 + 6;
    const nsPad = Math.max(4, Math.floor(unitW * 0.4));
    const sRoom = Math.max(0, Math.max(36, Math.min(56, Math.round(unitH))) - nsPad);
    const ewMinH = ewHidden ? Math.max(centerH + 40 + sRoom, ewFullH - sRoom) : (fit ? Math.min(ewFullH, Math.max(fit.row, centerH + 40)) : ewFullH);
    table = (
      <div className="relative flex flex-col items-center h-full">
        <div ref={nRef} style={{ paddingTop: nsPad, flexShrink: 0 }}><CardHandDisplay {...handProps('N')} /></div>
        <div ref={rowRef} className="flex-1 flex items-center justify-between w-full" style={{ flex: scroll ? '1 0 auto' : '1 1 auto', minHeight: ewMinH, paddingBottom: ewHidden ? sRoom : 0 }}>
          <CardHandDisplay {...handProps('W')} align="start" ewColMaxH={fit && fit.W || 0} />
          {centerBox()}
          <CardHandDisplay {...handProps('E')} align="end" ewColMaxH={fit && fit.E || 0} />
        </div>
        <div ref={sRef} style={{ paddingBottom: nsPad, flexShrink: 0 }}><CardHandDisplay {...handProps('S')} /></div>
        <div aria-hidden="true" style={{ flex: '1 1 0', minHeight: 0, maxHeight: sRoom }} />
      </div>
    );
  } else {
    table = (
      <div ref={contentRef} className="relative flex flex-col items-center gap-1">
        <CardHandDisplay {...handProps('N')} />
        <div className="flex items-center justify-between w-full">
          <div style={{ flex: '1 1 0', minWidth: 0, overflow: 'visible', display: 'flex', justifyContent: 'flex-start', alignSelf: ewHidden ? 'flex-start' : undefined, maxHeight: ewHidden ? '1.5rem' : undefined }}><CardHandDisplay {...handProps('W')} align="start" /></div>
          {centerBox({ zIndex: 2, margin: '0 ' + Math.max(4, Math.floor(unitW * 0.12)) + 'px', marginBottom: ewHidden ? (isLandMobile ? '1.75rem' : '2.25rem') : undefined })}
          <div style={{ flex: '1 1 0', minWidth: 0, overflow: 'visible', display: 'flex', justifyContent: 'flex-end', alignSelf: ewHidden ? 'flex-start' : undefined, maxHeight: ewHidden ? '1.5rem' : undefined }}><CardHandDisplay {...handProps('E')} align="end" /></div>
        </div>
        <CardHandDisplay {...handProps('S')} />
      </div>
    );
  }
  return (
    <div ref={pageRef} className="flex-1 min-h-0 flex flex-col">
      <div className="flex-1 w-full flex flex-col" style={scroll || !isNarrow ? { minHeight: 0 } : undefined}>
        <div className="w-full flex-1 flex flex-col" style={isNarrow ? { minHeight: '100%' } : { minHeight: 0 }}>
          <div ref={(el) => { feltRef.current = el; roomRef.current = el; }} className={'flex-1 ' + (isNarrow || isLandMobile ? 'px-1 py-1' : isSmall ? 'px-2 py-2' : 'px-3 py-3') + ' shadow-2xl relative overflow-hidden flex flex-col'}
            style={Object.assign({}, felt, scroll || !isNarrow ? { overflowY: 'auto', minHeight: 0 } : {}, isNarrow ? { justifyContent: isSmall ? 'flex-start' : 'center' } : { justifyContent: 'safe center' })}
            onClick={() => { if (review) setReview(null); }}>
            {table}
          </div>
        </div>
      </div>
      {emoteBar}
    </div>
  );
}

// An empty table in the lobby: choosing a seat opens the new table's settings.
function EmptyTableCard({ onPick }) {
  const cell = { N: 'col-start-2 row-start-1', W: 'col-start-1 row-start-2', E: 'col-start-3 row-start-2', S: 'col-start-2 row-start-3' };
  return (
    <Panel className="flex flex-col gap-3 !p-4 !bg-white/70">
      <div className="flex flex-wrap items-baseline justify-between gap-x-3">
        <strong className="text-lg">Empty table</strong>
        <span className="text-sm text-gray-700">Take a seat to open it</span>
      </div>
      <div className="grid grid-cols-3 grid-rows-3 gap-1 bg-gray-100 rounded-lg p-2 text-sm">
        {SEAT_ORDER.map((s) => (
          <div key={s} className={cell[s] + ' flex flex-col items-center justify-center min-h-[52px] text-center'}>
            <span className="text-xs font-bold">{SEAT_NAME[s]}</span>
            <button type="button" className="h-9 px-3 rounded-lg border font-semibold" style={{ borderColor: ACTION, color: ACTION }} onClick={() => onPick(s)}>Sit</button>
          </div>
        ))}
      </div>
    </Panel>
  );
}

function TableRoom({ user, club, t, act, go, side, leaveTable }) {
  const tableChat = useChat('table', true, t.id);
  const inHand = !!(t.playing && t.playing.midHand);
  const [confirmStart, setConfirmStart] = React.useState(false);
  const robot = (s, on) => act(api('POST', '/api/club/robot', { seat: s, on }));
  const start = () => { if (SEAT_ORDER.some((s) => !t.seats[s])) setConfirmStart(true); else act(api('POST', '/api/club/start', {})); };
  // Before play the table is shown by the compass, North at the top, for everyone.
  // (Once play starts, each player's own seat is at the bottom.)
  const mySeat = club.me.seat;                 // null for a kibitzer
  const place = { N: 'col-start-2 row-start-1', W: 'col-start-1 row-start-2', E: 'col-start-3 row-start-2', S: 'col-start-2 row-start-3' };
  const partner = mySeat ? SEAT_ORDER[(SEAT_ORDER.indexOf(mySeat) + 2) % 4] : null;
  const friendIds = SHOW_FRIENDS ? club.friends.map((f) => f.id) : [];
  const here = SEAT_ORDER.map((s) => t.seats[s]).filter((p) => p && !p.robot).map((p) => p.id);
  const busy = here.concat((t.invitedPlayers || []).map((p) => p.id), t.watchers.map((w) => w.id));
  const empty = SEAT_ORDER.filter((s) => !t.seats[s]);
  const setting = (body) => act(api('POST', '/api/club/tables/' + t.id + '/settings', body));
  const invite = (u) => act(api('POST', '/api/club/tables/' + t.id + '/invite', { userId: u.id }));
  const leave = () => (leaveTable ? leaveTable() : act(api('POST', '/api/club/leave', {})));   // asks first in the middle of a hand
  // The middle of the table: what happens next, in the style of the end-of-hand buttons.
  const btn = 'w-full min-w-0 whitespace-nowrap font-semibold rounded-lg py-2 px-2 text-sm';
  const centre = (
    <div className="col-start-2 row-start-2 flex items-center justify-center">
      <div data-tb-guard="" className="bg-white rounded-xl shadow-lg w-full max-w-[220px] flex flex-col overflow-hidden">
        <div className="px-2 pt-2 pb-1 text-center text-[13px] text-slate-600 leading-snug">
          {t.playing ? 'Hand ' + (inHand ? 'in play' : 'finished') + ' · board ' + t.playing.board
            : empty.length ? (t.isHost ? 'Waiting for players' : 'Waiting for the host') : (t.isHost ? 'All four seats are taken' : 'Waiting for the host to start')}
        </div>
        <div className="flex flex-col gap-2 px-2 pb-2 pt-1 border-t border-slate-100">
          {t.playing
            ? <button type="button" onClick={() => go('club')} className={btn + ' text-white'} style={{ backgroundColor: '#16a34a' }}>Back to the hand</button>
            : t.isHost && <button type="button" onClick={start} className={btn + ' text-white'} style={{ backgroundColor: '#16a34a' }}>Start</button>}
          <button type="button" onClick={leave} className={btn + ' bg-slate-100 hover:bg-slate-200 text-slate-700'}>{mySeat ? 'Leave table' : 'Stop kibitzing'}</button>
        </div>
      </div>
    </div>
  );
  return (
    <Page>
      <div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px] gap-5 content-start">
        <div className="flex flex-col gap-4 min-w-0">
        <Panel className="flex flex-col gap-3 !p-4">
          <div className="flex flex-wrap items-baseline justify-between gap-x-3">
            <h1 className="text-[2rem] leading-tight font-semibold m-0">{t.hostName}'s table</h1>
            <span className="text-sm text-gray-700">{tableLine(t)} · {t.open ? 'Open' : 'Private'}{t.beginnerFriendly ? ' · Beginner friendly' : ''}</span>
          </div>
          <div className="grid grid-cols-3 grid-rows-3 gap-2 rounded-xl p-2 sm:p-3" style={{ background: '#1f6b45' }}>
            {SEAT_ORDER.map((s) => {
              const p = t.seats[s];
              return (
                <div key={s} className={place[s] + ' bg-white rounded-lg p-2 min-h-[76px] flex flex-col items-center justify-center text-center min-w-0'}>
                  <span className="text-xs font-bold">{SEAT_NAME[s]}{s === partner ? ' · partner' : ''}</span>
                  {p && p.robot ? <React.Fragment>
                        <span className="font-semibold">Robot</span>
                        {t.isHost && !inHand && <button type="button" className="h-9 px-2 text-sm underline" onClick={() => robot(s, false)}>Remove</button>}
                      </React.Fragment>
                    : p ? <span className="font-semibold truncate max-w-full">{p.id === user.id ? 'You' : p.username}{p.id === t.hostId ? ' (host)' : ''}</span>
                    : <React.Fragment>
                        <span className="text-sm text-gray-600">Open seat</span>
                        {t.isHost && <button type="button" className="h-9 px-2 text-sm underline" style={{ color: ACTION }} onClick={() => robot(s, true)}>Add robot</button>}
                        {!inHand && <button type="button" className="h-9 px-2 text-sm underline" onClick={() => act(api('POST', '/api/club/tables/' + t.id + '/sit', { seat: s }))}>{mySeat ? 'Move here' : 'Sit here'}</button>}
                      </React.Fragment>}
                  {SHOW_FRIENDS && p && !p.robot && p.id !== user.id && !friendIds.includes(p.id) && (
                    <button type="button" className="h-9 px-2 text-sm underline" style={{ color: ACTION }} onClick={() => act(api('POST', '/api/friends', { userId: p.id }))}>+ Friend</button>
                  )}
                </div>
              );
            })}
            {centre}
          </div>
          <div className="text-sm text-gray-700">
            {t.playing ? 'Changes to the table settings apply from the next hand. '
              : t.isHost ? 'Press Start when you are ready. Robots play ' + SYSTEM_NAME[t.system] + '. ' : ''}
            {mySeat ? '' : 'You are kibitzing. '}{t.watchers.length ? 'Kibitzing: ' + t.watchers.map((w) => (w.id === user.id ? 'you' : w.username)).join(', ') + '.' : ''}
          </div>
        </Panel>
          {t.isHost && t.requests.length > 0 && (
            <Panel className="!p-4 flex flex-col gap-2">
              <h2 className="text-lg font-bold m-0">Requests to join</h2>
              {t.requests.map((q) => (
                <div key={q.userId} className="flex flex-wrap items-center justify-between gap-2">
                  <span>{q.username}{q.watch ? ' asks to kibitz' : q.seat ? ' asks to sit ' + SEAT_NAME[q.seat] : ' asks to join'}</span>
                  <span className="flex gap-2">
                    <ActionButton outline onClick={() => act(api('POST', '/api/club/tables/' + t.id + '/answer', { userId: q.userId, accept: true }))}>Accept</ActionButton>
                    <button type="button" className="h-11 px-3 rounded-lg border border-gray-400" onClick={() => act(api('POST', '/api/club/tables/' + t.id + '/answer', { userId: q.userId, accept: false }))}>Decline</button>
                  </span>
                </div>
              ))}
            </Panel>
          )}
          <Panel className="!p-4 flex flex-col gap-2">
            <h2 className="text-lg font-bold m-0">Table chat</h2>
            <ChatPanel chat={tableChat} user={user} listClass="max-h-[40vh] min-h-[80px]"
              note={club.me.seat ? 'Players, kibitzers and the host see this.' : t.playing ? 'During a hand, only the other kibitzers see what you write.' : 'Players, kibitzers and the host see this.'} />
          </Panel>
          {t.isHost && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start">
            <Panel className="!p-4 flex flex-col gap-3">
              <h2 className="text-lg font-bold m-0">Table settings</h2>
              <Choice label="Bidding system" options={SYSTEM_CHOICES} value={t.system} onChange={(v) => setting({ system: v })} />
              <Choice label="Ace asking" options={ACE_CHOICES} value={t.aceAsking} onChange={(v) => setting({ aceAsking: v })} />
              <label className="flex items-center gap-3 min-h-[44px] text-[15px]">
                <input type="checkbox" className="w-5 h-5" checked={t.beginnerFriendly} onChange={(e) => setting({ beginnerFriendly: e.target.checked })} /> Beginner friendly
              </label>
              <label className="flex items-start gap-3 min-h-[44px] text-[15px]">
                <input type="checkbox" className="w-5 h-5 mt-0.5" checked={!t.open} onChange={(e) => setting({ open: !e.target.checked })} />
                <span>Private table<span className="block text-[13px] text-gray-600">You approve each request to sit or to kibitz.</span></span>
              </label>
            </Panel>
            <Panel className="!p-4 flex flex-col gap-3">
              <h2 className="text-lg font-bold m-0">Invite players</h2>
              {SHOW_FRIENDS && club.friends.filter((f) => !busy.includes(f.id)).map((f) => (
                <div key={f.id} className="flex items-center justify-between gap-2">
                  <span className="truncate">{f.username} <span className="text-[13px] text-gray-600">· {whereText(f, club.tables)}</span></span>
                  <ActionButton outline onClick={() => invite(f)}>Invite</ActionButton>
                </div>
              ))}
              <UserSearch pickLabel="Invite" skipIds={busy} onPick={invite} />
              {t.invitedPlayers.length > 0 && <div className="text-sm text-gray-700">Invited: {t.invitedPlayers.map((p) => p.username).join(', ')}</div>}
              <div className="text-[13px] text-gray-600">Or invite anyone from Recent users. Invited players see the invitation in Play with Friends.</div>
            </Panel>
            </div>
          )}
        </div>
        {side}
      </div>
      {confirmStart && (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-3" role="dialog" aria-modal="true" aria-label="Start with robots?">
          <Panel className="w-full max-w-sm flex flex-col gap-3">
            <h2 className="text-xl font-bold m-0">Start with robots?</h2>
            <div>{SEAT_ORDER.filter((s) => !t.seats[s]).map((s) => SEAT_NAME[s]).join(' and ')} {SEAT_ORDER.filter((s) => !t.seats[s]).length > 1 ? 'are' : 'is'} empty. Fill with robots playing {SYSTEM_NAME[t.system]} and start now?</div>
            <div className="flex gap-2 justify-end">
              <button type="button" className="h-11 px-4 rounded-lg border border-gray-400" onClick={() => setConfirmStart(false)}>Keep waiting</button>
              <ActionButton onClick={() => { setConfirmStart(false); act(api('POST', '/api/club/start', { fillRobots: true })); }}>Yes, add robots</ActionButton>
            </div>
          </Panel>
        </div>
      )}
    </Page>
  );
}

// The right column of Play with Friends, the same in the room and at a table: the Room chat, then
// the players here now or lately. A host at a table can invite any of them from here.
const agoText = (iso) => {
  const m = Math.max(1, Math.round((Date.now() - new Date(iso).getTime()) / 60000));
  return m < 60 ? m + ' min ago' : Math.round(m / 60) + ' h ago';
};
function RoomColumn({ user, club, act, roomChat, chatBox, hostTable }) {
  const friendIds = club.friends.map((f) => f.id);
  const people = (club.recent || club.online.map((p) => Object.assign({ online: true }, p))).filter((p) => p.id !== user.id);
  const here = hostTable ? SEAT_ORDER.map((s) => hostTable.seats[s]).filter((p) => p && !p.robot).map((p) => p.id).concat(hostTable.watchers.map((w) => w.id)) : [];
  const invited = hostTable ? (hostTable.invitedPlayers || []).map((p) => p.id) : [];
  const nowHere = people.filter((p) => p.online).length;
  return (
    <div className="flex flex-col gap-4 min-w-0">
      <div ref={chatBox} style={{ scrollMarginTop: 8 }}>
        <Panel className="!p-4 flex flex-col gap-2 w-full">
          <h2 className="text-lg font-bold m-0">Room chat</h2>
          <ChatPanel chat={roomChat} user={user} threaded listClass="max-h-[50vh] lg:max-h-[calc(100vh-420px)] min-h-[120px]"
            note="Everyone in Play with Friends can read this. Conversations stay for 24 hours after their last message." />
        </Panel>
      </div>
      <Panel className="!p-4 flex flex-col gap-2 w-full">
        <h2 className="text-lg font-bold m-0">Recent users <span className="text-sm font-normal text-gray-600">({nowHere + 1} here now)</span></h2>
        {people.length === 0 && <div className="text-sm text-gray-700">Nobody else has been here in the last two hours.</div>}
        {people.map((p) => (
          <div key={p.id} className="flex items-center justify-between gap-2 min-h-[40px]">
            <span className="min-w-0 truncate">
              <span className={'inline-block w-2 h-2 rounded-full mr-2 align-middle ' + (p.online ? 'bg-green-600' : 'bg-gray-300')} aria-hidden="true" />
              {p.username} <span className="text-[13px] text-gray-600">· {p.online ? whereText(p, club.tables) : 'left ' + agoText(p.seenAt)}</span>
            </span>
            <span className="flex items-center gap-1 shrink-0">
              {hostTable && (here.includes(p.id) ? <span className="text-[13px] text-gray-600">at your table</span>
                : invited.includes(p.id) ? <span className="text-[13px] text-gray-600">invited</span>
                : <ActionButton outline onClick={() => act(api('POST', '/api/club/tables/' + hostTable.id + '/invite', { userId: p.id }))}>Invite</ActionButton>)}
              {SHOW_FRIENDS && !friendIds.includes(p.id) && !hostTable && (
                <button type="button" className="h-9 px-2 text-sm underline" style={{ color: ACTION }} onClick={() => act(api('POST', '/api/friends', { userId: p.id }))}>+ Friend</button>
              )}
              {SHOW_FRIENDS && friendIds.includes(p.id) && !hostTable && <span className="text-[13px] text-gray-600">friend</span>}
            </span>
          </div>
        ))}
        {hostTable && <div className="text-[13px] text-gray-600">Invited players see the invitation in Play with Friends.</div>}
      </Panel>
    </div>
  );
}

function Club({ user, club, refresh, review, setReview, go, showRoom, leaveTable }) {
  const [creating, setCreating] = React.useState(null);     // null, or { seat } while the new-table settings are open
  const [filter, setFilter] = React.useState('all');
  const [note, setNote] = React.useState('');
  const mineNow = club && club.me ? club.tables.find((x) => x.id === club.me.tableId) : null;
  const atHand = !!(mineNow && mineNow.game && !showRoom);    // the table fills the screen: no right column
  const inLobby = !!club && !atHand;
  const roomChat = useChat('club', inLobby);
  const chatBox = React.useRef(null);
  const [chatSeen, setChatSeen] = React.useState(false);     // the room chat has been on screen (phones: scrolled to)
  React.useEffect(() => {
    const el = chatBox.current;
    if (!el || typeof IntersectionObserver === 'undefined') { setChatSeen(true); return undefined; }
    const ob = new IntersectionObserver((es) => setChatSeen(es.some((e) => e.isIntersecting)), { threshold: 0.3 });
    ob.observe(el);
    return () => ob.disconnect();
  }, [inLobby, chatBox.current]);
  const roomUnread = useUnread(roomChat, user.id, chatSeen);
  if (!club) return <div className="flex-1 flex items-center justify-center text-gray-700" role="status">Opening Play with Friends…</div>;
  const act = (p) => { setNote(''); return p.then(refresh).catch((e) => { setNote(errorText(e.message)); refresh(); }); };
  const mine = club.me ? club.tables.find((x) => x.id === club.me.tableId) : null;
  if (mine) {
    return (
      <React.Fragment>
        {note && <div role="alert" className="text-center text-sm text-red-700 bg-white py-1">{note}</div>}
        {mine.game && !showRoom ? <HVTable user={user} club={club} t={mine} act={act} refresh={refresh} review={review} setReview={setReview} />
          : <TableRoom user={user} club={club} t={mine} act={act} go={go} leaveTable={leaveTable}
              side={<RoomColumn user={user} club={club} act={act} roomChat={roomChat} chatBox={chatBox} hostTable={mine.isHost ? mine : null} />} />}
      </React.Fragment>
    );
  }
  const friendIds = SHOW_FRIENDS ? club.friends.map((f) => f.id) : [];
  const hasFriend = (t) => SEAT_ORDER.some((s) => t.seats[s] && friendIds.includes(t.seats[s].id));
  const shown = club.tables.filter((t) => filter === 'all' || (filter === 'open' && SEAT_ORDER.some((s) => !t.seats[s]))
    || (filter === 'beginner' && t.beginnerFriendly) || (filter === 'friends' && hasFriend(t)));
  const sorted = shown.slice().sort((a, b) => (b.invited ? 1 : 0) - (a.invited ? 1 : 0));
  const chip = (id, text) => (
    <button key={id} type="button" aria-pressed={filter === id} onClick={() => setFilter(id)}
      className={'h-9 px-3 rounded-full border text-sm ' + (filter === id ? 'bg-gray-800 text-white border-gray-800' : 'bg-white border-gray-400')}>{text}</button>
  );
  return (
    <Page title="Play with Friends" sub="Sit at an open table, or create a new one."
      action={<React.Fragment>
        <button type="button" className="xl:hidden h-11 px-3 rounded-lg border border-gray-400 bg-white whitespace-nowrap"
          onClick={() => chatBox.current && chatBox.current.scrollIntoView({ behavior: 'smooth', block: 'start' })}>
          💬 Chat{roomUnread > 0 && <span className="ml-1 rounded-full text-white text-xs px-1.5 py-0.5" style={{ background: '#dc2626' }}>{roomUnread}</span>}
        </button>
        <ActionButton onClick={() => setCreating({ seat: null })}>+ Create a table</ActionButton>
      </React.Fragment>}>
      <div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px] gap-5 content-start">
        <div className="flex flex-col gap-3 min-w-0">
          <div className="flex flex-wrap gap-2">{chip('all', 'All tables')}{chip('open', 'Open seats')}{chip('beginner', 'Beginner friendly')}{SHOW_FRIENDS && chip('friends', 'Friends')}</div>
          {note && <div role="alert" className="text-sm text-red-700 bg-white rounded px-2 py-1">{note}</div>}
          {sorted.length === 0 && filter !== 'all' && filter !== 'open' && (
            <Panel className="text-center text-gray-700 !p-4">No tables match that filter.</Panel>
          )}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {sorted.map((t) => <TableCard key={t.id} t={t} friendIds={friendIds} act={act} />)}
            {/* The room always shows at least four tables; the rest are empty ones to open. */}
            {(filter === 'all' || filter === 'open') && Array.from({ length: Math.max(0, 4 - club.tables.length) }).map((_, i) => (
              <EmptyTableCard key={'empty' + i} onPick={(seat) => setCreating({ seat })} />
            ))}
          </div>
        </div>
        <RoomColumn user={user} club={club} act={act} roomChat={roomChat} chatBox={chatBox} hostTable={null} />
      </div>
      {creating && <CreateTable user={user} seat0={creating.seat} onClose={() => setCreating(null)} onCreated={() => { setCreating(null); refresh(); }} />}
    </Page>
  );
}

function ClubApp() {
  const [user, setUser] = React.useState(undefined);      // undefined = loading, null = signed out
  // ?view=settings / admin opens that page (the Practice menu links here, with from=play).
  const [view, setView] = React.useState(() => {
    const v = new URLSearchParams(location.search).get('view');
    if (location.pathname === '/hand-creator') return 'creator';
    if (v === 'profile') return 'settings';
    return ['settings', 'admin', 'club', 'practice'].includes(v) ? v : 'home';
  });
  // Hand Creator: what to open ({ item, version }); n changes each time something is opened.
  const [creatorStart, setCreatorStart] = React.useState(() => {
    const q = new URLSearchParams(location.search);
    return { item: location.pathname === '/hand-creator' ? Number(q.get('item')) || null : null, version: null, n: 0 };
  });
  const [fromPractice, setFromPractice] = React.useState(() => new URLSearchParams(location.search).get('from') === 'play');
  const [welcome, setWelcome] = React.useState(() => new URLSearchParams(location.search).get('welcome'));   // first arrival from WordPress
  const [wpNote] = React.useState(() => new URLSearchParams(location.search).get('wp'));
  React.useEffect(() => { if (location.search && location.pathname !== '/hand-creator') history.replaceState(null, '', '/'); }, []);
  // The pages visited, so "Leave …" can go back to wherever the player came from. Going to a page
  // already on the trail cuts the trail back to it (no loops).
  const [trail, setTrail] = React.useState([]);
  const go = (v) => {
    if (v === view) return;
    if (view === 'creator') {
      if (creatorDirty.current && !window.confirm('Leave the Hand Creator? Your unsaved changes will be lost.')) return;
      creatorDirty.current = false;
      history.replaceState(null, '', '/');
    }
    if (v === 'creator') history.replaceState(null, '', '/hand-creator' + (creatorStart.item ? '?item=' + creatorStart.item : ''));
    setTrail((tr) => { const i = tr.indexOf(v); return i >= 0 ? tr.slice(0, i) : tr.concat(view).slice(-20); });
    setView(v);
  };
  const back = (fallback) => {
    if (trail.length) { setView(trail[trail.length - 1]); setTrail(trail.slice(0, -1)); return; }
    if (fromPractice) { location.href = '/play'; return; }
    setView(fallback || 'home');
  };
  React.useEffect(() => {
    api('GET', '/api/me').then((r) => setUser(r.user)).catch(() => setUser(null));
    console.log('LBO Play v' + CLUB_VERSION + ' loaded');
  }, []);
  const [club, refresh] = useClub(!!user, () => setUser(null));
  const [review, setReview] = React.useState(null);      // at the table: 'auction' or 'last' (trick) shown in the centre
  const myTable = club && club.me ? club.tables.find((x) => x.id === club.me.tableId) : null;
  const playing = view === 'club' && !!(myTable && myTable.game);   // the table fills the screen, as the Hand Viewer's Play does
  const { vw, isLandMobile } = useScreenSize();
  const docked = vw >= 1024;                                  // the sidebar beside the page (narrower: a drawer from ☰)
  const [drawer, setDrawer] = React.useState(false);
  const [sideOpen, setSideOpenState] = React.useState(() => { try { return localStorage.getItem('lbo.sideOpen') !== '0'; } catch (e) { return true; } });
  const setSideOpen = (v) => { setSideOpenState(v); try { localStorage.setItem('lbo.sideOpen', v ? '1' : '0'); } catch (e) {} };
  const [adminTab, setAdminTab] = React.useState('activity');
  // EB Garamond, one size up, everywhere but the table during a hand (drawn as in Practice).
  React.useEffect(() => { document.documentElement.classList.toggle('lbo-serif', !playing); }, [playing]);
  React.useEffect(() => { setDrawer(false); }, [view]);
  if (user === undefined) return <div className="lbo-wash flex flex-col" style={{ height: PAGE_HEIGHT }}><TopBar onLogo={() => {}} /><div className="flex-1 flex items-center justify-center text-[20px]" role="status" style={{ color: '#1d4f7a', fontFamily: SERIF }}>Loading…</div></div>;
  if (!user && welcome) return <WelcomeFromWp token={welcome} onSignedIn={(u) => { setWelcome(null); setUser(u); setView('home'); }} />;
  if (!user) return <SignIn wpNote={wpNote} onSignedIn={(u) => { setUser(u); setView('home'); }} />;
  const signOut = () => api('POST', '/api/logout', {}).finally(() => setUser(null));
  // The logo opens and closes the sidebar: beside the page on wide screens, over it on narrow ones
  // and during a hand.
  const overlay = !docked || playing;
  const onLogo = () => { if (overlay) setDrawer(!drawer); else setSideOpen(!sideOpen); };
  const leaveTable = () => {
    const t = myTable;
    const mid = t && t.game && t.game.phase !== 'summary' && club.me.seat;
    if (!mid || window.confirm('Leave in the middle of the hand?')) api('POST', '/api/club/leave', {}).then(refresh).catch(refresh);
  };
  // Menu → Play with Friends: the room; at a table, its page; with a hand being played, the hand
  // (and from the hand, the table's page).
  const onFriends = () => go(myTable && myTable.game ? (view === 'club' ? 'tableSettings' : 'club') : 'club');
  // Menu → Practice / Exit: another page, in this tab. A player in the middle of a hand is asked first.
  const leaveSite = (url) => {
    const mid = myTable && myTable.game && myTable.game.phase !== 'summary' && club.me.seat;
    if (view === 'creator' && creatorDirty.current && !window.confirm('Leave the Hand Creator? Your unsaved changes will be lost.')) return;
    creatorDirty.current = false;
    if (!mid || window.confirm('Leave while a hand is being played? Your seat is given up if you are away for more than a minute and a half.')) location.href = url;
  };
  const navItems = [
    { id: 'home', label: 'Home', icon: 'home' },
    { id: 'club', label: 'Play with Friends', icon: 'club' },
    { id: 'practice', label: 'Practice', icon: 'practice' },
    isTeacher(user) && { id: 'creator', label: 'Hand Creator', icon: 'creator' },
    { id: 'settings', label: 'Settings', icon: 'settings' },
    user.role === 'admin' && { id: 'admin', label: 'Admin', icon: 'admin' },
  ].filter(Boolean);
  const pickNav = (it) => { setDrawer(false); if (it.id === 'club') onFriends(); else go(it.id); };
  const account = { user, onSignOut: signOut, leaveSite };
  const playSide = <SideBar items={navItems} active={view === 'tableSettings' ? 'club' : view} onPick={pickNav} account={account} />;
  const side = view === 'admin' && user.role === 'admin'
    ? <SideBar back={{ label: 'Home', onClick: () => go('home') }} heading="Admin" active={adminTab} account={account}
        items={ADMIN_TABS.map(([id, label, icon]) => ({ id, label, icon }))} onPick={(it) => { setAdminTab(it.id); setDrawer(false); }} />
    : playSide;

  // The Hand Creator draws its own frame (the editor's header is its top bar).
  if (view === 'creator' && isTeacher(user)) {
    return (
      <div className="lbo-wash flex flex-col text-gray-800" style={{ height: PAGE_HEIGHT, overflow: 'hidden' }}>
        <HandCreator start={creatorStart} go={go} user={user} account={account}
          onOpened={(id) => setCreatorStart((c) => Object.assign({}, c, { item: id, version: null }))} />
      </div>
    );
  }
  const showSide = !overlay && sideOpen;
  return (
    <div className="lbo-wash flex flex-col text-gray-800" style={playing ? { height: PAGE_HEIGHT, overflow: 'hidden', backgroundColor: '#faf8f5', backgroundImage: 'none' } : { height: PAGE_HEIGHT, overflow: 'hidden' }}>
      <TopBar onLogo={onLogo} sideShown={overlay ? drawer : sideOpen} slim={playing && isLandMobile}
        middle={playing ? <GameHeading g={myTable.game} review={review} setReview={setReview} kibitzing={!club.me.seat} /> : null} />
      <div className="flex-1 min-h-0 flex relative">
        {showSide && <div className="shrink-0 h-full">{side}</div>}
        <main className={'flex-1 min-w-0 flex flex-col ' + (playing ? 'overflow-hidden' : 'overflow-y-auto')}>
          {view === 'home' && <Home go={go} myTable={myTable} user={user} onFriends={onFriends} />}
          {(view === 'club' || view === 'tableSettings') && <Club user={user} club={club} refresh={refresh} review={review} setReview={setReview} go={go} showRoom={view === 'tableSettings'} leaveTable={leaveTable} />}
          {view === 'practice' && <Practice user={user} onUser={setUser} />}
          {view === 'settings' && <Settings user={user} onUser={setUser} onSignOut={signOut} club={club} refresh={refresh} />}
          {view === 'creator' && <Page title="Hand Creator" sub="The Hand Creator is for teachers. Ask Learn Bridge Online if you would like to use it." />}
          {view === 'admin' && user.role === 'admin' && <Admin me={user} tab={adminTab} />}
        </main>
        {overlay && (
          <div className="absolute inset-0 z-30" style={{ pointerEvents: drawer ? 'auto' : 'none' }} aria-hidden={!drawer}>
            <button type="button" aria-label="Close the menu" tabIndex={drawer ? 0 : -1} onClick={() => setDrawer(false)}
              className="absolute inset-0 w-full h-full bg-black/40" style={{ opacity: drawer ? 1 : 0, transition: 'opacity 180ms' }} />
            <div className="absolute left-0 top-0 bottom-0 shadow-xl" style={{ transform: drawer ? 'none' : 'translateX(-105%)', transition: 'transform 200ms ease-out', width: 'min(85vw, 300px)' }}>
              {React.cloneElement(side, { width: '100%' })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// The Hand Viewer's components read the screen size from its provider.
window.ClubApp = function ClubAppRoot() { return <ScreenSizeProvider><ClubApp /></ScreenSizeProvider>; };
})();
