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61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Client } from '@gradio/client';

interface Me {
  username: string | null;
  member: boolean;
}

interface Poll {
  id: string;
  question: string;
  options: string[];
  counts: number[];
  total: number;
  created_by: string;
  created_at: string;
  my_vote: number | null;
  voters: Record<string, number>;
}

type Notice = { kind: 'ok' | 'err'; text: string } | null;
type Tab = 'polls' | 'create';

async function callApi<T>(client: unknown, name: string, args: unknown[]): Promise<T> {
  const c = client as { predict: (n: string, a: unknown[]) => Promise<{ data: unknown[] }> };
  const res = await c.predict(name, args);
  return res.data[0] as T;
}

const PollApp: React.FC = () => {
  const clientRef = useRef<unknown>(null);
  const [ready, setReady] = useState(false);
  const [backendError, setBackendError] = useState<string | null>(null);
  const [me, setMe] = useState<Me>({ username: null, member: false });
  const [polls, setPolls] = useState<Poll[]>([]);
  const [busy, setBusy] = useState(false);
  const [tab, setTab] = useState<Tab>('polls');
  const [editingId, setEditingId] = useState<string | null>(null);
  const [question, setQuestion] = useState('');
  const [options, setOptions] = useState<string[]>(['', '']);
  const [notice, setNotice] = useState<Notice>(null);

  const MAX_OPTIONS = 20;

  const setOption = (idx: number, value: string) => {
    setOptions((prev) => prev.map((o, i) => (i === idx ? value : o)));
  };
  const addOption = () => {
    setOptions((prev) => (prev.length >= MAX_OPTIONS ? prev : [...prev, '']));
  };
  const removeOption = (idx: number) => {
    setOptions((prev) => (prev.length <= 1 ? prev : prev.filter((_, i) => i !== idx)));
  };

  const refresh = useCallback(async () => {
    const client = clientRef.current;
    if (!client) return;
    try {
      const data = await callApi<{ me: Me; polls: Poll[] }>(client, '/polls', []);
      setMe(data.me);
      setPolls(data.polls);
      setBackendError(null);
    } catch {
      setBackendError('Cannot reach the voting backend.');
    }
  }, []);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        clientRef.current = await Client.connect(window.location.origin + '/gradio');
        if (!cancelled) {
          setReady(true);
          await refresh();
        }
      } catch {
        if (!cancelled) setBackendError('Cannot reach the voting backend.');
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [refresh]);

  const doVote = async (pollId: string, idx: number) => {
    if (busy || !clientRef.current) return;
    setBusy(true);
    try {
      const data = await callApi<{ ok: boolean; message: string; poll: Poll | null }>(
        clientRef.current,
        '/vote',
        [pollId, idx]
      );
      setNotice({ kind: data.ok ? 'ok' : 'err', text: data.message });
      if (data.ok && data.poll) {
        setPolls((prev) => prev.map((p) => (p.id === data.poll!.id ? data.poll! : p)));
      } else {
        await refresh();
      }
    } catch {
      setNotice({ kind: 'err', text: 'Vote failed — please retry.' });
    } finally {
      setBusy(false);
    }
  };

  const startEdit = (poll: Poll) => {
    setEditingId(poll.id);
    setQuestion(poll.question);
    setOptions(poll.options.length > 0 ? [...poll.options] : ['', '']);
    setNotice(null);
    setTab('create');
  };

  const cancelEdit = () => {
    setEditingId(null);
    setQuestion('');
    setOptions(['', '']);
    setNotice(null);
  };

  const doSubmit = async () => {
    if (busy || !clientRef.current) return;
    setBusy(true);
    const optsArg = options.filter((o) => o.trim()).join('\n');
    const api = editingId ? '/edit_poll' : '/create_poll';
    const args = editingId ? [editingId, question, optsArg] : [question, optsArg];
    try {
      const data = await callApi<{ ok: boolean; message: string; poll: Poll | null }>(
        clientRef.current,
        api,
        args
      );
      setNotice({ kind: data.ok ? 'ok' : 'err', text: data.message });
      if (data.ok) {
        setEditingId(null);
        setQuestion('');
        setOptions(['', '']);
        await refresh();
        setTab('polls');
      }
    } catch {
      setNotice({ kind: 'err', text: 'Could not save poll — please retry.' });
    } finally {
      setBusy(false);
    }
  };

  const doDelete = async (poll: Poll) => {
    if (busy || !clientRef.current) return;
    if (!window.confirm(`Delete poll “${poll.question}” and its ${poll.total} vote(s)?`)) return;
    setBusy(true);
    try {
      const data = await callApi<{ ok: boolean; message: string }>(
        clientRef.current,
        '/delete_poll',
        [poll.id]
      );
      setNotice({ kind: data.ok ? 'ok' : 'err', text: data.message });
      await refresh();
    } catch {
      setNotice({ kind: 'err', text: 'Could not delete poll — please retry.' });
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="page">
      <div className="bg" aria-hidden="true">
        <div className="bg-orb bg-orb-a" />
        <div className="bg-orb bg-orb-b" />
        <div className="bg-orb bg-orb-c" />
        <div className="bg-grid" />
      </div>

      <div className="shell">
        <header className="top">
          <h1>
            <span className="logo" aria-hidden="true">🗳️</span> SLM Consortium Polls
          </h1>
          <div className="auth">
            {me.username ? (
              <span className={`chip ${me.member ? 'chip-ok' : 'chip-warn'}`}>
                @{me.username}
                {me.member ? '' : ' · not a member'}
              </span>
            ) : (
              <a
                className="btn"
                href="/gradio/login/huggingface?_target_url=/"
              >
                Sign in with Hugging Face
              </a>
            )}
            <button className="btn quiet" onClick={() => void refresh()}>
              Refresh
            </button>
          </div>
        </header>

        <p className="lede">
          Hugging Face sign-in required. Only <code>slmconsortium</code> members can vote or create
          polls. Click to vote, and click another option to change your vote.
        </p>

        <nav className="tabs" role="tablist" aria-label="Sections">
          <button
            role="tab"
            aria-selected={tab === 'polls'}
            className={tab === 'polls' ? 'active' : ''}
            onClick={() => setTab('polls')}
          >
            🗳️ Polls
          </button>
          <button
            role="tab"
            aria-selected={tab === 'create'}
            className={tab === 'create' ? 'active' : ''}
            onClick={() => setTab('create')}
          >
            ➕ Create poll
          </button>
        </nav>

        {backendError && <p className="notice err">{backendError}</p>}
        {notice && <p className={`notice ${notice.kind}`}>{notice.text}</p>}
        {!ready && !backendError && <p className="muted">Loading…</p>}

        {tab === 'polls' && (
          <div className="tabpanel" role="tabpanel">
            {ready && polls.length === 0 && <p className="muted">No polls yet.</p>}
            {polls.map((poll) => (
              <section key={poll.id} className="card">
                <h2>{poll.question}</h2>
                <p className="meta">
                  {poll.total} vote{poll.total === 1 ? '' : 's'} · by @{poll.created_by}
                  {me.member && (
                    <span className="card-actions">
                      <button
                        className="icon-btn"
                        disabled={busy}
                        title="Edit poll (votes for edited/removed options are dropped)"
                        aria-label={`Edit poll ${poll.question}`}
                        onClick={() => startEdit(poll)}
                      >
                        ✏️
                      </button>
                      <button
                        className="icon-btn danger"
                        disabled={busy}
                        title="Delete poll"
                        aria-label={`Delete poll ${poll.question}`}
                        onClick={() => void doDelete(poll)}
                      >
                        🗑️
                      </button>
                    </span>
                  )}
                </p>
                <ul className="opts">
                  {poll.options.map((opt, idx) => {
                    const pct = poll.total ? (poll.counts[idx] / poll.total) * 100 : 0;
                    const mine = poll.my_vote === idx;
                    const voters = Object.entries(poll.voters ?? {})
                      .filter(([, v]) => v === idx)
                      .map(([u]) => u)
                      .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
                    return (
                      <li key={idx}>
                        <button
                          className={mine ? 'mine' : ''}
                          disabled={!me.member || busy}
                          title={
                            !me.username
                              ? 'Sign in to vote'
                              : !me.member
                                ? 'Only slmconsortium members can vote'
                                : `Vote for ${opt}`
                          }
                          onClick={() => void doVote(poll.id, idx)}
                        >
                          <span className="opt-top">
                            <span>
                              {opt}
                              {mine ? ' ✓' : ''}
                            </span>
                            <span className="num">
                              {poll.counts[idx]} · {pct.toFixed(0)}%
                            </span>
                          </span>
                          <span className="bar">
                            <i style={{ width: `${pct}%` }} />
                          </span>
                          {voters.length > 0 && (
                            <span className="voters">
                              {voters.map((u) => (
                                <span key={u} className={`voter ${u === me.username ? 'me' : ''}`}>
                                  @{u}
                                </span>
                              ))}
                            </span>
                          )}
                        </button>
                      </li>
                    );
                  })}
                </ul>
              </section>
            ))}
          </div>
        )}

        {tab === 'create' && (
          <div className="tabpanel" role="tabpanel">
            <section className="card">
              <h2>{editingId ? 'Edit poll' : 'New poll'}</h2>
              {!me.member && (
                <p className="muted">
                  {!me.username ? 'Sign in first.' : 'Only slmconsortium members can create polls.'}
                </p>
              )}
              <label>
                Question
                <input
                  value={question}
                  onChange={(e) => setQuestion(e.target.value)}
                  placeholder="Which meeting time works best?"
                  disabled={!me.member}
                />
              </label>
              <div className="field">
                <span className="field-label">
                  Options
                  <span className="field-hint">
                    {options.length}/{MAX_OPTIONS}
                  </span>
                </span>
                <ul className="opt-editor">
                  {options.map((opt, idx) => (
                    <li key={idx}>
                      <input
                        value={opt}
                        onChange={(e) => setOption(idx, e.target.value)}
                        placeholder={`Option ${idx + 1}`}
                        disabled={!me.member}
                        aria-label={`Option ${idx + 1}`}
                      />
                      <button
                        type="button"
                        className="icon-btn"
                        onClick={() => removeOption(idx)}
                        disabled={!me.member || options.length <= 1}
                        aria-label={`Remove option ${idx + 1}`}
                        title={options.length <= 1 ? 'Need at least one option row' : 'Remove option'}
                      >
                        ✕
                      </button>
                    </li>
                  ))}
                </ul>
                <button
                  type="button"
                  className="btn quiet add-opt"
                  onClick={addOption}
                  disabled={!me.member || options.length >= MAX_OPTIONS}
                >
                  + Add option
                </button>
              </div>
              <div className="form-actions">
                <button
                  className="btn"
                  disabled={
                    !me.member ||
                    busy ||
                    question.trim().length < 3 ||
                    options.filter((o) => o.trim()).length < 2
                  }
                  onClick={() => void doSubmit()}
                >
                  {busy ? 'Working…' : editingId ? 'Save changes' : 'Create poll'}
                </button>
                {editingId && (
                  <button className="btn quiet" onClick={cancelEdit} disabled={busy}>
                    Cancel
                  </button>
                )}
              </div>
            </section>
          </div>
        )}

        <footer className="muted">
          <a href="/gradio/">Classic UI</a>
        </footer>
      </div>
    </div>
  );
};

export default PollApp;