// ============================================================
// ScreenAdmin — full system management for admin account
// ============================================================

// PIN hash (same as app.jsx — defined here to avoid load-order dependency)
const _hashPin = (pin) => {
  let h = 5381;
  for (const c of pin) h = (((h << 5) + h) ^ c.charCodeAt(0)) >>> 0;
  return h.toString(16).padStart(8, '0');
};

// ── Subcomponents ────────────────────────────────────────────

const AdminSection = ({ title, children, action }) => (
  <section style={{ marginBottom: 36 }}>
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, paddingBottom: 8, borderBottom: '1px solid var(--line-0)' }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, letterSpacing: '0.14em', color: 'var(--gold-1)' }}>{title}</div>
      {action}
    </div>
    {children}
  </section>
);

// Inline editable text field
const InlineEdit = ({ value, onSave, style = {} }) => {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(value);
  React.useEffect(() => { setDraft(value); }, [value]);
  if (editing) return (
    <input
      className="input"
      value={draft}
      autoFocus
      onChange={e => setDraft(e.target.value)}
      onBlur={() => { setEditing(false); if (draft.trim() !== value) onSave(draft.trim()); }}
      onKeyDown={e => {
        if (e.key === 'Enter') { setEditing(false); if (draft.trim() !== value) onSave(draft.trim()); }
        if (e.key === 'Escape') { setEditing(false); setDraft(value); }
      }}
      style={{ fontSize: 12, padding: '2px 6px', ...style }}
    />
  );
  return (
    <span
      onClick={() => setEditing(true)}
      title="Клікни щоб редагувати"
      style={{ cursor: 'text', borderBottom: '1px dashed var(--line-0)', paddingBottom: 1, ...style }}
    >{value}</span>
  );
};

// PIN change inline form
const PinChangeForm = ({ userId, onSave, onCancel }) => {
  const [pin1, setPin1] = React.useState('');
  const [pin2, setPin2] = React.useState('');
  const [err, setErr] = React.useState('');
  const handleSave = () => {
    if (pin1.length !== 4) { setErr('PIN має бути 4 цифри'); return; }
    if (pin1 !== pin2) { setErr('PIN не збігається'); return; }
    onSave(_hashPin(pin1));
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
      <input className="input" type="password" inputMode="numeric" maxLength={4} placeholder="Новий PIN"
        value={pin1} onChange={e => { setPin1(e.target.value.replace(/\D/g, '').slice(0, 4)); setErr(''); }}
        style={{ width: 90, fontSize: 13, letterSpacing: '0.3em', textAlign: 'center' }}/>
      <input className="input" type="password" inputMode="numeric" maxLength={4} placeholder="Ще раз"
        value={pin2} onChange={e => { setPin2(e.target.value.replace(/\D/g, '').slice(0, 4)); setErr(''); }}
        style={{ width: 90, fontSize: 13, letterSpacing: '0.3em', textAlign: 'center' }}/>
      <Btn primary onClick={handleSave} style={{ fontSize: 11 }}>Зберегти</Btn>
      <Btn ghost onClick={onCancel} style={{ fontSize: 11 }}>✕</Btn>
      {err && <span style={{ fontSize: 10, color: 'var(--crimson-1)', fontFamily: 'var(--font-mono)' }}>{err}</span>}
    </div>
  );
};

// ── Main component ───────────────────────────────────────────

const ScreenAdmin = ({
  campaigns, members, users, onlineUsers,
  characters, activeCampaignId,
  onCreateUser, onUpdateUser, onDeleteUser,
  onCreateCampaign, onDeleteCampaign,
  onAddMember, onRemoveMember, onSetMemberDM, onSetMemberCharIds,
  onMigrate, onDownloadBackup, onStorageReset,
}) => {
  const { push } = useToast();

  // ── Accounts state
  const [creatingUser, setCreatingUser] = React.useState(false);
  const [newUserId, setNewUserId]     = React.useState('');
  const [newUserName, setNewUserName] = React.useState('');
  const [newUserRole, setNewUserRole] = React.useState('Гравець');
  const [newUserPin, setNewUserPin]   = React.useState('');
  const [changingPinFor, setChangingPinFor] = React.useState(null);

  // ── Campaigns state
  const [creatingCamp, setCreatingCamp] = React.useState(false);
  const [newCampName, setNewCampName]   = React.useState('');
  const [newCampIcon, setNewCampIcon]   = React.useState('⚔');
  const [newCampId, setNewCampId]       = React.useState('');

  // ── Members: which campaign tab is active in the members section
  const [membersCampId, setMembersCampId] = React.useState(activeCampaignId || campaigns[0]?.id);

  const campMembers = members[membersCampId] || {};
  const nonAdminUsers = users.filter(u => u.id !== 'admin');

  // users NOT yet in membersCampId
  const nonMembers = nonAdminUsers.filter(u => !(u.id in campMembers));

  const handleCreateUser = () => {
    const id = newUserId.trim() ||
      newUserName.trim().toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '').slice(0, 20);
    const name = newUserName.trim();
    if (!id || !name) { push({ label: '⚠ Вкажи ID та ім\'я' }); return; }
    if (newUserPin.length !== 4) { push({ label: '⚠ PIN має бути 4 цифри' }); return; }
    if (users.find(u => u.id === id)) { push({ label: `⚠ ID "${id}" вже існує` }); return; }
    onCreateUser(id, name, newUserRole, _hashPin(newUserPin));
    setCreatingUser(false); setNewUserId(''); setNewUserName(''); setNewUserRole('Гравець'); setNewUserPin('');
    push({ label: `Акаунт "${name}" створено` });
  };

  const handleCreateCamp = () => {
    const name = newCampName.trim();
    const id = newCampId.trim() ||
      name.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').slice(0, 24);
    if (!id || !name) return;
    if (campaigns.find(c => c.id === id)) { push({ label: `⚠ ID "${id}" вже існує` }); return; }
    onCreateCampaign(id, name, newCampIcon || '⚔');
    setCreatingCamp(false); setNewCampName(''); setNewCampIcon('⚔'); setNewCampId('');
    push({ label: `Кампанію "${name}" створено` });
  };

  const row = (children) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px',
      background: 'var(--bg-elv)', border: '1px solid var(--line-0)', borderRadius: 8 }}>
      {children}
    </div>
  );

  return (
    <div style={{ padding: '24px 28px', maxWidth: 720, margin: '0 auto' }}>

      {/* ══ АКАУНТИ ══════════════════════════════════════════════ */}
      <AdminSection title="Акаунти" action={
        <Btn onClick={() => setCreatingUser(v => !v)}><Icon name="plus" size={12}/> Новий акаунт</Btn>
      }>

        {creatingUser && (
          <div style={{ padding: 14, marginBottom: 10, background: 'var(--bg-elv)', border: '1px solid var(--gold-2)', borderRadius: 8 }}>
            <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
              <div style={{ flex: 1 }}>
                <div className="field-label mb-4">Ім'я</div>
                <input className="input" placeholder="Руслан" value={newUserName} autoFocus
                  onChange={e => setNewUserName(e.target.value)}/>
              </div>
              <div style={{ flex: 1 }}>
                <div className="field-label mb-4">Роль</div>
                <input className="input" placeholder="Гравець" value={newUserRole}
                  onChange={e => setNewUserRole(e.target.value)}/>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
              <div style={{ flex: 1 }}>
                <div className="field-label mb-4">ID (авто)</div>
                <input className="input" placeholder="ruslan" value={newUserId}
                  onChange={e => setNewUserId(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, ''))}
                  style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}/>
              </div>
              <div style={{ flex: 1 }}>
                <div className="field-label mb-4">PIN (4 цифри)</div>
                <input className="input" type="password" inputMode="numeric" maxLength={4}
                  placeholder="• • • •" value={newUserPin}
                  onChange={e => setNewUserPin(e.target.value.replace(/\D/g, '').slice(0, 4))}
                  onKeyDown={e => e.key === 'Enter' && handleCreateUser()}
                  style={{ textAlign: 'center', letterSpacing: '0.4em' }}/>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <Btn primary onClick={handleCreateUser}>Створити</Btn>
              <Btn ghost onClick={() => { setCreatingUser(false); setNewUserId(''); setNewUserName(''); setNewUserPin(''); }}>Скасувати</Btn>
            </div>
          </div>
        )}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {users.map(u => {
            const isOnline = !!onlineUsers[u.id];
            const isAdmin = u.id === 'admin';
            return (
              <div key={u.id}>
                {row(<>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
                    background: isOnline ? '#4ae04a' : 'var(--ink-3)',
                    boxShadow: isOnline ? '0 0 6px #4ae04a88' : 'none' }}/>

                  <div style={{ minWidth: 110 }}>
                    <InlineEdit value={u.name}
                      onSave={v => { onUpdateUser(u.id, { name: v }); push({ label: `Ім'я змінено → ${v}` }); }}
                      style={{ fontSize: 13, color: 'var(--ink-0)' }}/>
                  </div>

                  <div style={{ flex: 1 }}>
                    <InlineEdit value={u.role}
                      onSave={v => { onUpdateUser(u.id, { role: v }); push({ label: 'Роль оновлено' }); }}
                      style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}/>
                  </div>

                  <code style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-3)',
                    background: 'var(--bg-0)', padding: '1px 5px', borderRadius: 3 }}>{u.id}</code>

                  {isOnline && <Chip label="online" style={{ background: '#1a3a1a', color: '#4ae04a', fontSize: 9 }}/>}

                  <button onClick={() => setChangingPinFor(changingPinFor === u.id ? null : u.id)}
                    style={{ background: 'none', border: '1px solid var(--line-0)', borderRadius: 4,
                      cursor: 'pointer', color: 'var(--ink-3)', fontSize: 10, padding: '3px 7px',
                      fontFamily: 'var(--font-mono)' }} title="Змінити PIN">PIN</button>

                  {!isAdmin && (
                    <button onClick={() => {
                      if (!confirm(`Видалити акаунт "${u.name}"?\nКампанії та персонажі залишаться.`)) return;
                      onDeleteUser(u.id);
                      push({ label: `Акаунт "${u.name}" видалено` });
                    }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 4 }}>
                      <Icon name="trash" size={13}/>
                    </button>
                  )}
                </>)}

                {changingPinFor === u.id && (
                  <div style={{ padding: '8px 12px 8px 30px', background: 'var(--bg-0)', borderRadius: '0 0 8px 8px', border: '1px solid var(--line-0)', borderTop: 'none', marginTop: -4 }}>
                    <PinChangeForm userId={u.id}
                      onSave={hash => { onUpdateUser(u.id, { pinHash: hash }); setChangingPinFor(null); push({ label: `PIN для "${u.name}" змінено` }); }}
                      onCancel={() => setChangingPinFor(null)}/>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </AdminSection>

      {/* ══ КАМПАНІЇ ═════════════════════════════════════════════ */}
      <AdminSection title="Кампанії" action={
        <Btn onClick={() => setCreatingCamp(v => !v)}><Icon name="plus" size={12}/> Нова кампанія</Btn>
      }>

        {creatingCamp && (
          <div style={{ padding: 14, marginBottom: 10, background: 'var(--bg-elv)', border: '1px solid var(--gold-2)', borderRadius: 8 }}>
            <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
              <input className="input" value={newCampIcon} onChange={e => setNewCampIcon(e.target.value)}
                style={{ width: 52, textAlign: 'center', fontSize: 20 }} placeholder="⚔"/>
              <input className="input" value={newCampName} onChange={e => setNewCampName(e.target.value)}
                placeholder="Назва кампанії" style={{ flex: 1 }} autoFocus
                onKeyDown={e => e.key === 'Enter' && handleCreateCamp()}/>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <div style={{ flex: 1 }}>
                <div className="field-label mb-4">ID (авто)</div>
                <input className="input" value={newCampId}
                  onChange={e => setNewCampId(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
                  style={{ fontFamily: 'var(--font-mono)', fontSize: 11, width: '100%' }} placeholder="my-campaign"/>
              </div>
              <div style={{ display: 'flex', gap: 6, alignSelf: 'flex-end' }}>
                <Btn primary onClick={handleCreateCamp}>Створити</Btn>
                <Btn ghost onClick={() => { setCreatingCamp(false); setNewCampName(''); setNewCampId(''); }}>✕</Btn>
              </div>
            </div>
          </div>
        )}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {campaigns.map(c => (
            <div key={c.id}>
              {row(<>
                <span style={{ fontSize: 20 }}>{c.icon}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 14, color: 'var(--ink-0)' }}>{c.name}</div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--ink-3)', marginTop: 2 }}>
                    {c.id} · {Object.keys(members[c.id] || {}).length} учасників
                  </div>
                </div>
                <button onClick={() => { if (confirm(`Видалити кампанію "${c.name}"?\nДані персонажів залишаться в Firebase.`)) onDeleteCampaign(c.id); }}
                  style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 4 }}>
                  <Icon name="trash" size={14}/>
                </button>
              </>)}
            </div>
          ))}
        </div>
      </AdminSection>

      {/* ══ УЧАСНИКИ ══════════════════════════════════════════════ */}
      <AdminSection title="Учасники кампаній">

        {/* Campaign tabs */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 14, flexWrap: 'wrap' }}>
          {campaigns.map(c => (
            <button key={c.id}
              onClick={() => setMembersCampId(c.id)}
              style={{
                padding: '5px 12px', borderRadius: 20, border: 'none', cursor: 'pointer',
                fontFamily: 'var(--font-mono)', fontSize: 11,
                background: membersCampId === c.id ? 'var(--gold-1)' : 'var(--bg-elv)',
                color: membersCampId === c.id ? 'var(--bg-0)' : 'var(--ink-2)',
                border: '1px solid ' + (membersCampId === c.id ? 'var(--gold-1)' : 'var(--line-0)'),
              }}
            >{c.icon} {c.name}</button>
          ))}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {Object.entries(campMembers).map(([userId, m]) => {
            const u = users.find(u => u.id === userId);
            if (!u) return null;
            const isOnline = !!onlineUsers[userId];
            const charIds = m.charIds || '';
            return (
              <div key={userId} style={{ background: 'var(--bg-elv)', border: '1px solid var(--line-0)', borderRadius: 8, padding: '8px 12px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: m.isDM ? 0 : 8 }}>
                  <span style={{ width: 7, height: 7, borderRadius: '50%', flexShrink: 0,
                    background: isOnline ? '#4ae04a' : 'var(--ink-3)' }}/>
                  <span style={{ flex: 1, fontSize: 13, color: 'var(--ink-0)' }}>{u.name}</span>
                  <span style={{ fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>{u.role}</span>

                  {/* DM toggle */}
                  <label style={{ display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer', fontSize: 11, color: m.isDM ? 'var(--gold-1)' : 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>
                    <input type="checkbox" checked={!!m.isDM}
                      onChange={e => onSetMemberDM(membersCampId, userId, e.target.checked)}
                      style={{ cursor: 'pointer' }}/>
                    ДМ
                  </label>

                  <button onClick={() => { if (confirm(`Видалити ${u.name} з кампанії?`)) onRemoveMember(membersCampId, userId); }}
                    style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 4 }}>
                    <Icon name="trash" size={12}/>
                  </button>
                </div>

                {/* CharIds field (only for non-DM) */}
                {!m.isDM && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', minWidth: 60 }}>charIds:</span>
                    <input className="input"
                      style={{ flex: 1, fontSize: 11, fontFamily: 'var(--font-mono)', padding: '3px 8px' }}
                      placeholder="charId1,charId2"
                      defaultValue={charIds}
                      key={charIds}
                      onBlur={e => onSetMemberCharIds(membersCampId, userId, e.target.value.trim())}
                      onKeyDown={e => e.key === 'Enter' && e.target.blur()}
                    />
                  </div>
                )}
              </div>
            );
          })}

          {/* Add member */}
          {nonMembers.length > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 12px', border: '1px dashed var(--line-0)', borderRadius: 8 }}>
              <Icon name="plus" size={14} style={{ color: 'var(--ink-3)' }}/>
              <select className="input" defaultValue=""
                onChange={e => {
                  if (!e.target.value) return;
                  onAddMember(membersCampId, e.target.value);
                  e.target.value = '';
                }}
                style={{ flex: 1, fontSize: 12 }}>
                <option value="">+ Додати учасника…</option>
                {nonMembers.map(u => (
                  <option key={u.id} value={u.id}>{u.name} ({u.role})</option>
                ))}
              </select>
            </div>
          )}

          {Object.keys(campMembers).length === 0 && (
            <div style={{ fontSize: 12, color: 'var(--ink-3)', fontStyle: 'italic', padding: '8px 12px' }}>
              У цій кампанії ще немає учасників
            </div>
          )}
        </div>
      </AdminSection>

      {/* ══ ПЕРСОНАЖІ ════════════════════════════════════════════ */}
      <AdminSection title={`Персонажі (поточна кампанія)`}>
        <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 8, fontFamily: 'var(--font-mono)' }}>
          Скопіюй ID щоб вставити в поле charIds вище
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {characters.length === 0
            ? <div style={{ fontSize: 12, color: 'var(--ink-3)', fontStyle: 'italic' }}>Немає персонажів</div>
            : characters.map(c => (
              <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px',
                background: 'var(--bg-0)', border: '1px solid var(--line-0)', borderRadius: 6 }}>
                <div style={{ width: 26, height: 26, borderRadius: '50%', background: 'var(--bg-elv)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--ink-2)', flexShrink: 0 }}>
                  {c.name?.split(' ').map(p => p[0]).slice(0, 2).join('')}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: 'var(--ink-0)' }}>{c.name}</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>{c.klass} {c.level} · {c.race}</div>
                </div>
                <code
                  onClick={() => navigator.clipboard?.writeText(c.id).then(() => {})}
                  title="Клікни щоб скопіювати"
                  style={{ fontFamily: 'var(--font-mono)', fontSize: 11, background: 'var(--bg-elv)',
                    padding: '3px 8px', borderRadius: 4, color: 'var(--gold-1)',
                    cursor: 'pointer', border: '1px solid var(--line-0)', userSelect: 'all' }}
                >{c.id}</code>
              </div>
            ))
          }
        </div>
      </AdminSection>

      {/* ══ ІНСТРУМЕНТИ ══════════════════════════════════════════ */}
      <AdminSection title="Інструменти">
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <Btn onClick={onMigrate}><Icon name="refresh" size={12}/> Мігрувати v3 → campaigns</Btn>
          <Btn onClick={onDownloadBackup}><Icon name="save" size={12}/> Backup localStorage</Btn>
          <Btn onClick={onStorageReset} style={{ color: 'var(--crimson-1)' }}><Icon name="trash" size={12}/> Скинути сховище PartyKit</Btn>
        </div>
      </AdminSection>

    </div>
  );
};

window.ScreenAdmin = ScreenAdmin;
