// admin-alliances-events.jsx — Alliance CRUD + per-alliance event scheduling, and global Events.

const UTC_TIME_OPTIONS = (() => {
  const out = [];
  for (let h = 0; h < 24; h++) {
    for (let m = 0; m < 60; m += 15) {
      out.push(String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0'));
    }
  }
  return out;
})();

// ── Alliances ───────────────────────────────────────────────
function AlliancesView({ session }) {
  const [alliances, setAlliances] = React.useState([]);
  const [events, setEvents] = React.useState([]);
  const [eventTimes, setET] = React.useState([]);
  const [editing, setEditing] = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const [scheduleFor, setSchedFor] = React.useState(null);
  const [confirmDel, setConfirmDel] = React.useState(null);
  const [ready, setReady] = React.useState(false);

  React.useEffect(() => {
    Promise.all([
      ATS.loadAlliances(),
      ATS.loadEvents(),
      ATS.loadEventTimes(),
    ]).then(([a, e, et]) => {
      setAlliances(a);
      setEvents(e);
      setET(et);
      setReady(true);
    }).catch(() => setReady(true));
  }, []);

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

  const save = async (ally) => {
    if (ally.id) {
      await fetch(`/api/alliances/${ally.id}`, {
        method: 'PATCH',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: ally.name, tag: ally.tag, description: ally.description }),
      });
    } else {
      await fetch('/api/alliances', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: ally.name, tag: ally.tag, description: ally.description }),
      });
    }
    const fresh = await ATS.loadAlliances();
    setAlliances(fresh);
    setEditing(null);
    setCreating(false);
  };

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

  const saveTimes = async (allianceId, timeMap) => {
    await fetch(`/api/event-times/${allianceId}`, {
      method: 'PUT',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(timeMap),
    });
    const fresh = await ATS.loadEventTimes();
    setET(fresh);
  };

  const allyEventTimes = (aid) => eventTimes.find((et) => et.alliance_id === aid);

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

  return (
    <>
      <StatStrip>
        <StatCard lbl="Alliances" val={alliances.length} />
        <StatCard lbl="Events" val={events.length} color="#67e8f9" />
      </StatStrip>

      <div className="panel-head" style={{ marginBottom: 12 }}>
        <h3>All alliances</h3>
        {canManage &&
          <button className="btn btn-primary btn-sm" onClick={() => {
            setCreating(true);
            setEditing({ name: '', tag: '', description: '' });
          }}>
            <ADMIN_ICONS.plus width="13" height="13" /> Add alliance
          </button>
        }
      </div>

      <div className="alliance-grid">
        {alliances.length === 0 && (
          <div className="empty"><h3>No alliances yet.</h3><p>Add your first alliance to get started.</p></div>
        )}
        {alliances.map((ally) => (
          <div key={ally.id} className="alliance-card glass-strong">
            <div className="ally-head">
              <div className="ally-mark">{ally.tag || ally.name.slice(0, 3).toUpperCase()}</div>
              <div className="ally-info">
                <div><b>{ally.name}</b></div>
                {ally.tag && <div className="ally-tag">{ally.tag}</div>}
                {ally.description && <div className="ally-desc">{ally.description}</div>}
              </div>
              {canManage && (
                <div className="ally-actions">
                  <button className="btn btn-ghost btn-xs" onClick={() => { setEditing(ally); setCreating(false); }}>
                    <ADMIN_ICONS.edit width="12" height="12" />
                  </button>
                  <button className="btn btn-ghost btn-xs" style={{ color: '#f87171' }}
                    onClick={() => setConfirmDel(ally)}>
                    <ADMIN_ICONS.trash width="12" height="12" />
                  </button>
                </div>
              )}
            </div>
            <button className="btn btn-ghost btn-xs" style={{ marginTop: 8 }}
              onClick={() => setSchedFor(scheduleFor === ally.id ? null : ally.id)}>
              {scheduleFor === ally.id ? 'Done scheduling' : 'Schedule events'}
            </button>
            {scheduleFor === ally.id && (
              <ScheduleEditor allianceId={ally.id} eventTimes={allyEventTimes(ally.id)} events={events} onSave={saveTimes} />
            )}
          </div>
        ))}
      </div>

      {/* Alliance editor modal */}
      {editing && (
        <div className="scrim open" onMouseDown={(e) => {
          if (e.target === e.currentTarget) { setEditing(null); setCreating(false); }
        }}>
          <div className="modal glass-strong compact">
            <h3 style={{ marginBottom: 16 }}>{creating ? 'Add alliance' : 'Edit alliance'}</h3>
            <div className="form-grid">
              <div className="form-row">
                <label>Name</label>
                <input value={editing.name} onChange={(e) => setEditing((p) => ({ ...p, name: e.target.value }))} />
              </div>
              <div className="form-row">
                <label>Tag</label>
                <input value={editing.tag || ''} onChange={(e) => setEditing((p) => ({ ...p, tag: e.target.value }))} placeholder="GRD" />
              </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={3} placeholder="Brief description of the alliance…" />
              </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 ? 'Add alliance' : 'Save changes'}
              </button>
            </div>
          </div>
        </div>
      )}

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

// ── Schedule editor (inline on alliance card) ──────────────
function ScheduleEditor({ allianceId, eventTimes, events, onSave }) {
  const [draft, setDraft] = React.useState(() => {
    if (eventTimes && eventTimes.times) {
      const map = {};
      eventTimes.times.forEach((t) => { map[t.event_id] = t.time; });
      return map;
    }
    return {};
  });

  const setFor = (eventId, time) => {
    setDraft((d) => ({ ...d, [String(eventId)]: time }));
  };

  const save = () => onSave(allianceId, draft);

  return (
    <div style={{ marginTop: 10, borderTop: '1px solid var(--border)', paddingTop: 10 }}>
      <div style={{ fontSize: '0.82rem', color: 'var(--text-dim)', marginBottom: 8 }}>Event times (UTC):</div>
      {events.length === 0 && <div style={{ color: 'var(--text-faint)', fontSize: '0.82rem' }}>No events defined yet.</div>}
      {events.map((ev) => (
        <div key={ev.id} className="schedule-row" style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
          <span style={{ flex: 1, fontSize: '0.85rem' }}>{ev.name}</span>
          <select value={draft[String(ev.id)] || ''} onChange={(e) => setFor(ev.id, e.target.value)}
            style={{ fontSize: '0.82rem' }}>
            <option value="">— Off —</option>
            {UTC_TIME_OPTIONS.map((t) => <option key={t} value={t}>{t}</option>)}
          </select>
        </div>
      ))}
      <button className="btn btn-primary btn-xs" style={{ marginTop: 6 }} onClick={save}>Save schedule</button>
    </div>
  );
}

// ── Events (global) ─────────────────────────────────────────
function EventsView({ session }) {
  const [eventTimes, setET] = React.useState([]);
  const [events, setEvents] = React.useState([]);
  const [alliances, setAlliances] = 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.loadEvents(),
      ATS.loadEventTimes(),
      ATS.loadAlliances(),
    ]).then(([e, et, a]) => {
      setEvents(e);
      setET(et);
      setAlliances(a);
      setReady(true);
    }).catch(() => setReady(true));
  }, []);

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

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

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

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

  return (
    <>
      <div className="panel-head" style={{ marginBottom: 12 }}>
        <h3>All events</h3>
        {canManage &&
          <button className="btn btn-primary btn-sm" onClick={() => {
            setCreating(true);
            setEditing({ name: '', category: 'daily' });
          }}>
            <ADMIN_ICONS.plus width="13" height="13" /> Add event
          </button>
        }
      </div>

      {events.length === 0 && (
        <div className="empty"><h3>No events yet.</h3><p>Add daily/weekly events that show on each alliance's schedule.</p></div>
      )}
      {events.map((ev) => (
        <div key={ev.id} className="event-row glass-strong" style={{ marginBottom: 8, padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 12 }}>
          <span className="app-status" style={{ fontSize: '0.72rem' }}>{ev.category}</span>
          <span><b>{ev.name}</b></span>
          {canManage && (
            <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
              <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>
      ))}

      {/* Event editor modal */}
      {editing && (
        <div className="scrim open" onMouseDown={(e) => {
          if (e.target === e.currentTarget) { setEditing(null); setCreating(false); }
        }}>
          <div className="modal glass-strong compact">
            <h3 style={{ marginBottom: 16 }}>{creating ? 'Add event' : 'Edit event'}</h3>
            <div className="form-grid">
              <div className="form-row">
                <label>Name</label>
                <input value={editing.name} onChange={(e) => setEditing((p) => ({ ...p, name: e.target.value }))} />
              </div>
              <div className="form-row">
                <label>Category</label>
                <select value={editing.category} onChange={(e) => setEditing((p) => ({ ...p, category: e.target.value }))}>
                  <option value="daily">Daily</option>
                  <option value="weekly">Weekly</option>
                  <option value="special">Special</option>
                </select>
              </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={() => saveEvent(editing)}>
                {creating ? 'Add event' : 'Save changes'}
              </button>
            </div>
          </div>
        </div>
      )}

      <Confirm open={!!confirmDel}
        title={`Delete event?`}
        confirmText="Delete"
        danger
        onConfirm={() => removeEvent(confirmDel.id)}
        onClose={() => setConfirmDel(null)}>
        <p>Permanently removes <b>{confirmDel?.name}</b>. This will also remove event time settings from all alliances.</p>
      </Confirm>

      {/* Cross-alliance schedule table */}
      <div className="panel-head" style={{ marginBottom: 12, marginTop: 24 }}>
        <h3>Schedule overview</h3>
      </div>
      <div className="glass-strong" style={{ borderRadius: 14, overflow: 'hidden' }}>
        <table className="users-tbl">
          <thead>
            <tr>
              <th>Event</th>
              {alliances.map((a) => <th key={a.id}>{a.tag || a.name}</th>)}
            </tr>
          </thead>
          <tbody>
            {events.map((ev) => (
              <tr key={ev.id}>
                <td><b>{ev.name}</b></td>
                {alliances.map((a) => {
                  const et = eventTimes.find((x) => x.alliance_id === a.id);
                  const time = et?.times?.[String(ev.id)];
                  return <td key={a.id} style={{ textAlign: 'center' }}>{time || '—'}</td>;
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ── Drafts view ────────────────────────────────────────────
function DraftsView({ session }) {
  const [apps, setApps] = React.useState([]);
  const [ready, setReady] = React.useState(false);

  React.useEffect(() => {
    ATS.loadApplications().then((a) => { setApps(a); setReady(true); }).catch(() => setReady(true));
  }, []);

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

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

  const pendingForStaff = apps.filter((a) => a.status === 'pending');

  return (
    <>
      <StatStrip>
        <StatCard lbl="Pending approval" val={pendingForStaff.length} color="#fbbf24" />
        <StatCard lbl="Published" val={apps.filter((a) => a.status === 'published').length} color="#5eead4" />
      </StatStrip>

      <div className="panel-head" style={{ marginBottom: 12 }}>
        <h3>Pending submissions</h3>
      </div>

      <div className="content-draft-list">
        {pendingForStaff.length === 0 && (
          <div className="empty"><h3>No pending drafts.</h3><p>Content submitted by staff will appear here for review.</p></div>
        )}
        {pendingForStaff.map((a) => (
          <div key={a.id} className="content-draft-card glass-strong">
            <div className="cd-name">{a.player_name}</div>
            <div className="cd-actions">
              <button className="btn btn-primary btn-xs"
                onClick={() => console.log('Approve', a.id)}>
                <ADMIN_ICONS.check width="11" height="11" /> Approve
              </button>
              <button className="btn btn-ghost btn-xs" style={{ color: '#f87171' }}>
                Reject
              </button>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

Object.assign(window, { AlliancesView, EventsView, ScheduleEditor, DraftsView });