/* ============================================================
   ADMIN STORE - single source of truth for the admin module
   Mock in-memory data + the event lifecycle state machine.
   Pattern matches the rest of the project: no imports, attaches to window.
   ============================================================ */

/* ---------- Event lifecycle ----------
   Draft → Scheduled → Open for submissions → Under review
        → Confirmed lineup → Live → Completed → Archived
   Each stage knows its color, label, and which stage(s) it can advance to.
*/
const LIFECYCLE = [
  { key: 'draft',       label: 'Draft',              color: '#6e6783', next: ['scheduled'] },
  { key: 'scheduled',   label: 'Scheduled',          color: 'var(--purple)', next: ['open'] },
  { key: 'open',        label: 'Open for submissions',color: '#2CC7A8', next: ['review'] },
  { key: 'review',      label: 'Under review',        color: 'var(--warning)', next: ['confirmed'] },
  { key: 'confirmed',   label: 'Confirmed lineup',    color: 'var(--green)', next: ['live'] },
  { key: 'live',        label: 'Live',                color: 'var(--danger)', next: ['completed'] },
  { key: 'completed',   label: 'Completed',           color: 'var(--muted)', next: ['archived'] },
  { key: 'archived',    label: 'Archived',            color: 'var(--faint)', next: [] },
];
const stageOf = (key) => LIFECYCLE.find(s => s.key === key) || LIFECYCLE[0];
const stageIndex = (key) => LIFECYCLE.findIndex(s => s.key === key);

const EVENT_TYPES = [
  { key: 'builders', label: "Builders Hub",  hint: 'Weekly · builder demos', recurring: true },
  { key: 'shark',    label: 'Shark Tank',    hint: 'Pitch + gang vote',      recurring: false },
  { key: 'special',  label: 'Special Event', hint: 'AMAs, drops, IRL',       recurring: false },
];

/* ---------- Seed events ---------- */
const seedEvents = [
  {
    id: 'evt-001', title: 'Builders Hub #14', type: 'builders',
    desc: 'Weekly builder demos. 5 slots, 8 min each, gang Q&A after.',
    date: '2026-06-04', time: '19:00', tz: 'UTC+1', discord: true, recurring: 'weekly',
    stage: 'review', slots: 5, assigned: ['sub-002', 'sub-004'],
    attendance: 0, peak: 0,
  },
  {
    id: 'evt-002', title: 'Shark Tank: AI x NFT', type: 'shark',
    desc: 'Three teams pitch. Gang votes live. Winner gets the motion fund boost.',
    date: '2026-06-07', time: '20:00', tz: 'UTC+1', discord: true, recurring: null,
    stage: 'scheduled', slots: 3, assigned: [],
    attendance: 0, peak: 0,
  },
  {
    id: 'evt-003', title: 'Builders Hub #13', type: 'builders',
    desc: 'Weekly builder demos.', date: '2026-05-28', time: '19:00', tz: 'UTC+1',
    discord: true, recurring: 'weekly', stage: 'live', slots: 5, assigned: ['sub-001'],
    attendance: 86, peak: 112,
  },
  {
    id: 'evt-004', title: 'Builders Hub #12', type: 'builders',
    desc: 'Weekly builder demos.', date: '2026-05-21', time: '19:00', tz: 'UTC+1',
    discord: true, recurring: 'weekly', stage: 'completed', slots: 5, assigned: ['sub-003'],
    attendance: 94, peak: 121,
  },
  {
    id: 'evt-005', title: 'Eid Special: Gang Pulse', type: 'special',
    desc: 'Community celebration + recap of the month.', date: '2026-05-10', time: '18:00',
    tz: 'UTC+1', discord: true, recurring: null, stage: 'archived', slots: 0, assigned: [],
    attendance: 140, peak: 168,
  },
];

/* ---------- Seed builder submissions ---------- */
const seedSubs = [
  { id: 'sub-001', name: 'adaeze.eth', handle: '@adaeze', region: 'Lagos, NG',
    project: 'On-chain bounty escrow', stack: 'Solana · Rust', quality: 'high',
    status: 'approved', note: 'Shipped twice. Reliable.', when: '3d ago' },
  { id: 'sub-002', name: 'kelvin_codes', handle: '@kelvin', region: 'Accra, GH',
    project: 'AI signal aggregator', stack: 'Next · Python', quality: 'high',
    status: 'pending', note: '', when: '1d ago' },
  { id: 'sub-003', name: 'zaynab.sol', handle: '@zaynab', region: 'Abuja, NG',
    project: 'NFT mint analytics', stack: 'React · The Graph', quality: 'mid',
    status: 'approved', note: 'Good demo, light docs.', when: '5d ago' },
  { id: 'sub-004', name: 'tobi.base', handle: '@tobibuilds', region: 'Nairobi, KE',
    project: 'Telegram trading agent', stack: 'Node · Bun', quality: 'high',
    status: 'pending', note: '', when: '6h ago' },
  { id: 'sub-005', name: 'mira.xyz', handle: '@mira', region: 'Lagos, NG',
    project: 'Creator payout splitter', stack: 'Solidity · Viem', quality: 'mid',
    status: 'hold', note: 'Revisit after testnet.', when: '2d ago' },
  { id: 'sub-006', name: 'dre.eth', handle: '@dre', region: 'Cape Town, ZA',
    project: 'DeFi exit guardian', stack: 'Rust · Anchor', quality: 'low',
    status: 'pending', note: '', when: '4h ago' },
];

/* ---------- useAdminData hook ----------
   Owns events + submissions state, exposes mutations.
   Lives at the AdminApp level and is threaded down via props.
*/
function useAdminData() {
  const [events, setEvents] = useState(seedEvents);
  const [subs, setSubs] = useState(seedSubs);

  const createEvent = (draft) => {
    const id = 'evt-' + Math.random().toString(36).slice(2, 7);
    setEvents(prev => [{
      id, stage: draft.publishNow ? 'scheduled' : 'draft',
      assigned: [], attendance: 0, peak: 0,
      ...draft,
    }, ...prev]);
    return id;
  };

  const advanceEvent = (id, toKey) => setEvents(prev => prev.map(e =>
    e.id === id ? { ...e, stage: toKey } : e));

  const updateEvent = (id, patch) => setEvents(prev => prev.map(e =>
    e.id === id ? { ...e, ...patch } : e));

  const setSubStatus = (id, status) => setSubs(prev => prev.map(s =>
    s.id === id ? { ...s, status } : s));

  const assignToEvent = (eventId, subId) => setEvents(prev => prev.map(e => {
    if (e.id !== eventId) return e;
    const has = e.assigned.includes(subId);
    return { ...e, assigned: has ? e.assigned.filter(x => x !== subId) : [...e.assigned, subId] };
  }));

  return { events, subs, createEvent, advanceEvent, updateEvent, setSubStatus, assignToEvent };
}

window.LIFECYCLE = LIFECYCLE;
window.stageOf = stageOf;
window.stageIndex = stageIndex;
window.EVENT_TYPES = EVENT_TYPES;
window.useAdminData = useAdminData;
