// admin-svs.jsx — SVS Details management (repurposed Events tab).

function SVSView({ session }) {
  const [events, setEvents] = React.useState([]);
  const [alliances, setAlliances] = React.useState([]);
  const [rotation, setRotation] = React.useState([]);
  const [editing, setEditing] = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(null);
  const [ready, setReady] = React.useState(false);

  React.useEffect(() => {
    Promise.all([
      ATS.loadSvsEvents(),
      ATS.loadAlliances(),
      ATS.loadRotation(),
    ]).then(([e, a, r]) => {
      setEvents(e);
      setAlliances(a);
      setRotation(r);
      setReady(true);
    }).catch(() => setReady(true));
  }, []);

  const canManage = ATS.roleAtLeast(session.role, 'alliance_admin');

  const allyName = (id) => alliances.find((a) => a.id === id)?.name || '—';
  const allyTag = (id) => alliances.find((a) => a.id === id)?.tag || '???';

  const save = async (ev) => {
    if (ev.id) {
      await fetch(`/api/svs/${ev.id}`, {
        method: 'PATCH',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(ev),
      });
    } else {
      await fetch('/api/svs', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(ev),
      });
    }
    const fresh = await ATS.loadSvsEvents();
    setEvents(fresh);
    setEditing(null);
    setCreating(false);
  };

  const remove = async (id) => {
    await fetch(`/api/svs/${id}`, { method: 'DELETE', credentials: 'include' });
    const fresh = await ATS.loadSvsEvents();
    setEvents(fresh);
    setConfirmDel(null);
  };

  const rotationAlliances = rotation
    .sort((a, b) => a.position - b.position)
    .map((r) => ({
      position: r.position,
      alliance_id: r.alliance_id,
      alliance_name: allyName(r.alliance_id),
      alliance_tag: allyTag(r.alliance_id),
    }));

  if (!ready) return <div className="admin-content"><div className="empty"><h3>Loading SVS data…</h3></div></div>;

  return (
    <>
      {/* Rotation display */}
      <div className="panel-head" style={{ marginBottom: 12 }}>
        <h3>SVS Rotations</h3>
        {canManage &&
          <button className="btn btn-primary btn-sm" onClick={() => {
            setEditing({ alliance_id: '', rotation: rotation.length + 1 });
          }}>
            <ADMIN_ICONS.plus width="13" height="13" /> Add rotation slot
          </button>
        }
      </div>

      <div className="rotation-grid">
        {rotationAlliances.length === 0 && (
          <div className="empty"><h3>No rotations set up.</h3><p>Add SVS rotation slots to display on the site.</p></div>
        )}
        {rotationAlliances.map((r) => (
          <div key={r.position} className="rotation-card glass-strong">
            <div className="rotation-pos">#{r.position}</div>
            <div className="rotation-ally">{r.alliance_name}</div>
            <div className="rotation-tag">{r.alliance_tag}</div>
          </div>
        ))}
      </div>

      {/* SVS Events list */}
      <div className="panel-head" style={{ marginBottom: 12, marginTop: 24 }}>
        <h3>SVS Events</h3>
        {canManage &&
          <button className="btn btn-primary btn-sm" onClick={() => {
            setCreating(true);
            setEditing({ title: '', description: '', date: '', alliance_ids: [], result: '' });
          }}>
            <ADMIN_ICONS.plus width="13" height="13" /> New SVS event
          </button>
        }
      </div>

      {events.length === 0 && (
        <div className="empty"><h3>No SVS events yet.</h3></div>
      )}
      {events.map((ev) => (
        <div key={ev.id} className="svs-event-card glass-strong" style={{ marginBottom: 12 }}>
          <div className="svs-heading">
            <div>
              <div className="svs-title">{ev.title}</div>
              <div className="svs-date">{ATS.fmtDate(ev.date)}</div>
            </div>
            <div className="svs-result">{ev.result || '???'}</div>
            {canManage && (
              <div className="svs-actions">
                <button className="btn btn-ghost btn-xs" onClick={() => { setEditing(ev); setCreating(false); }}>
                  <ADMIN_ICONS.edit width="12" height="12" />
                </button>
                <button className="btn btn-ghost btn-xs" style={{ color: '#f87171' }}
                  onClick={() => setConfirmDel(ev)}>
                  <ADMIN_ICONS.trash width="12" height="12" />
                </button>
              </div>
            )}
          </div>
          {ev.description && <div className="svs-desc">{ev.description}</div>}
          {ev.alliance_ids && ev.alliance_ids.length > 0 && (
            <div className="svs-alliances">
              {ev.alliance_ids.map((aid) => (
                <span key={aid} className="svs-ally-tag">{allyTag(aid)}</span>
              ))}
            </div>
          )}
        </div>
      ))}

      {/* SVS editor modal */}
      {editing && (
        <div className="scrim open" onMouseDown={(e) => {
          if (e.target === e.currentTarget) { setEditing(null); setCreating(false); }
        }}>
          <div className="modal glass-strong" style={{ width: '100%', maxWidth: 520 }}>
            <h3 style={{ marginBottom: 16 }}>{creating ? 'New SVS event' : 'Edit SVS event'}</h3>
            <div className="form-grid">
              <div className="form-row" style={{ gridColumn: '1 / -1' }}>
                <label>Title</label>
                <input value={editing.title || ''} onChange={(e) => setEditing((p) => ({ ...p, title: e.target.value }))} placeholder="KvK S1 opening" />
              </div>
              <div className="form-row">
                <label>Date</label>
                <input type="date" value={editing.date || ''} onChange={(e) => setEditing((p) => ({ ...p, date: e.target.value }))} />
              </div>
              <div className="form-row" style={{ gridColumn: '1 / -1' }}>
                <label>Result</label>
                <input value={editing.result || ''} onChange={(e) => setEditing((p) => ({ ...p, result: e.target.value }))} placeholder="Victory / Defeat / Ongoing" />
              </div>
              <div className="form-row" style={{ gridColumn: '1 / -1' }}>
                <label>Description</label>
                <textarea value={editing.description || ''} onChange={(e) => setEditing((p) => ({ ...p, description: e.target.value }))}
                  rows={4} placeholder="Event highlights, notes…" />
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 20 }}>
              <button className="btn btn-ghost btn-sm" onClick={() => { setEditing(null); setCreating(false); }}>Cancel</button>
              <button className="btn btn-primary btn-sm" onClick={() => save(editing)}>
                {creating ? 'Create' : 'Save'}
              </button>
            </div>
          </div>
        </div>
      )}

      <Confirm open={!!confirmDel}
        title={`Delete event?`}
        confirmText="Delete"
        danger
        onConfirm={() => remove(confirmDel.id)}
        onClose={() => setConfirmDel(null)}>
        <p>Permanently removes <b>{confirmDel?.title}</b>.</p>
      </Confirm>
    </>
  );
}

Object.assign(window, { SVSView });