// Council: manage award EVENTS and their CATEGORIES (add / amend / remove).
const AWARD_SETUP = (function () {
  const COLORS = [
    ['var(--navy)', 'var(--navy)', 'Navy'],
    ['var(--ocean)', 'var(--navy)', 'Ocean'],
    ['var(--gold)', 'var(--gold-d)', 'Red'],
    ['var(--ok)', 'var(--ok)', 'Green'],
    ['var(--warn)', '#9c6a16', 'Amber'],
    ['var(--navy2)', 'var(--navy)', 'Royal'],
  ];
  const ICONS = ['♛', '★', '◈', '♦', '✦', '◎', '✎', '❦', '◆', '▲'];
  const uid = () => 'c_' + Math.random().toString(36).slice(2, 8);

  function EventEditor({ item, onClose }) {
    const { actions } = CTSCStore.useStore();
    const [v, setV] = React.useState(item ? JSON.parse(JSON.stringify(item)) : { name: '', eyebrow: '', blurb: '', explainer: false, categories: [] });
    const set = (k, val) => setV(s => ({ ...s, [k]: val }));
    const setCat = (id, patch) => setV(s => ({ ...s, categories: s.categories.map(c => c.id === id ? { ...c, ...patch } : c) }));
    const addCat = () => setV(s => ({ ...s, categories: [...s.categories, { id: uid(), name: '', desc: '', ic: '★', acc: 'var(--navy)', accD: 'var(--navy)' }] }));
    const delCat = (id) => setV(s => ({ ...s, categories: s.categories.filter(c => c.id !== id) }));
    const save = () => {
      const payload = { ...v, categories: v.categories.filter(c => c.name.trim()) };
      if (item) actions.updateItem('awardEvents', item.id, payload); else actions.addItem('awardEvents', payload);
      onClose();
    };
    const valid = v.name.trim() && v.categories.some(c => c.name.trim());
    return (
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(6,25,42,.55)', zIndex: 200, display: 'grid', placeItems: 'center', padding: 24 }}>
        <div onClick={e => e.stopPropagation()} className="fade-in" style={{ background: '#fff', borderRadius: 14, width: 'min(640px,100%)', maxHeight: '90vh', overflow: 'auto', boxShadow: 'var(--shadow-lg)' }}>
          <div style={{ padding: '20px 26px', borderBottom: '1px solid var(--line2)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', position: 'sticky', top: 0, background: '#fff', zIndex: 2 }}>
            <h3 style={{ fontSize: 19, fontWeight: 900, margin: 0 }}>{item ? 'Edit award event' : 'New award event'}</h3>
            <button onClick={onClose} style={{ fontSize: 22, color: 'var(--muted)' }}>✕</button>
          </div>
          <div style={{ padding: 26 }}>
            <div className="field"><label>Event name</label><input value={v.name} onChange={e => set('name', e.target.value)} placeholder="e.g. CTSC Sport Awards" /></div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div className="field" style={{ margin: 0 }}><label>Eyebrow / strapline</label><input value={v.eyebrow} onChange={e => set('eyebrow', e.target.value)} placeholder="e.g. Annual Sport Awards" /></div>
              <div className="field" style={{ margin: 0 }}><label>Show category cards</label>
                <select value={v.explainer ? 'yes' : 'no'} onChange={e => set('explainer', e.target.value === 'yes')}><option value="no">No — list only</option><option value="yes">Yes — explainer cards</option></select>
              </div>
            </div>
            <div className="field"><label>Intro blurb</label><textarea value={v.blurb} onChange={e => set('blurb', e.target.value)} placeholder="Short description shown under the title" /></div>

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '8px 0 12px' }}>
              <label style={{ fontSize: 13, fontWeight: 800, color: 'var(--navy)' }}>Categories</label>
              <button className="btn btn-ghost btn-sm" onClick={addCat}>+ Add category</button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {v.categories.length === 0 && <div style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600, padding: '8px 0' }}>No categories yet — add one.</div>}
              {v.categories.map(c => (
                <div key={c.id} style={{ border: '1px solid var(--line2)', borderRadius: 10, padding: 14, background: '#fbfcfe' }}>
                  <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 10 }}>
                    <div style={{ width: 38, height: 38, borderRadius: 8, background: c.acc, color: '#fff', display: 'grid', placeItems: 'center', fontSize: 18, flex: '0 0 auto' }}>{c.ic}</div>
                    <input value={c.name} onChange={e => setCat(c.id, { name: e.target.value })} placeholder="Category name" style={{ flex: 1, fontFamily: 'inherit', fontSize: 14, fontWeight: 700, padding: '9px 12px', border: '1.5px solid var(--line)', borderRadius: 6, color: 'var(--navy)' }} />
                    <button onClick={() => delCat(c.id)} style={{ color: '#b4452f', fontWeight: 800, fontSize: 18, padding: '0 4px' }} title="Remove category">×</button>
                  </div>
                  <textarea value={c.desc} onChange={e => setCat(c.id, { desc: e.target.value })} placeholder="Short description (shown on category cards)" style={{ width: '100%', fontFamily: 'inherit', fontSize: 13, padding: '9px 12px', border: '1.5px solid var(--line)', borderRadius: 6, minHeight: 48, resize: 'vertical', boxSizing: 'border-box' }} />
                  <div style={{ display: 'flex', gap: 18, marginTop: 10, flexWrap: 'wrap' }}>
                    <div>
                      <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 6 }}>Icon</div>
                      <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
                        {ICONS.map(ic => <button key={ic} onClick={() => setCat(c.id, { ic })} style={{ width: 28, height: 28, borderRadius: 6, fontSize: 15, border: '1.5px solid ' + (c.ic === ic ? 'var(--navy)' : 'var(--line)'), background: c.ic === ic ? 'var(--sky-tint)' : '#fff', color: 'var(--navy)' }}>{ic}</button>)}
                      </div>
                    </div>
                    <div>
                      <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 6 }}>Colour</div>
                      <div style={{ display: 'flex', gap: 6 }}>
                        {COLORS.map(([acc, accD, label]) => <button key={label} title={label} onClick={() => setCat(c.id, { acc, accD })} style={{ width: 26, height: 26, borderRadius: '50%', background: acc, border: c.acc === acc ? '2px solid var(--navy)' : '2px solid #fff', boxShadow: '0 0 0 1px var(--line)' }}></button>)}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ padding: '16px 26px', borderTop: '1px solid var(--line2)', display: 'flex', gap: 10, justifyContent: 'flex-end', position: 'sticky', bottom: 0, background: '#fff' }}>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button className="btn btn-gold" disabled={!valid} style={{ opacity: valid ? 1 : .45, pointerEvents: valid ? 'auto' : 'none' }} onClick={save}>{item ? 'Save changes' : 'Create event'}</button>
          </div>
        </div>
      </div>
    );
  }

  function AwardSetup() {
    const { data, actions } = CTSCStore.useStore();
    const events = data.awardEvents || [];
    const [editing, setEditing] = React.useState(null);
    const recCount = (evName, catName) => (data.awards || []).filter(a => a.event === evName && a.category === catName).length;

    return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
          <div>
            <h3 style={{ fontSize: 20, fontWeight: 900, margin: 0 }}>Award setup</h3>
            <p style={{ fontSize: 13.5, color: 'var(--muted)', margin: '4px 0 0' }}>Add or amend award events and their categories. Changes appear on the public Awards page and in nomination forms.</p>
          </div>
          <button className="btn btn-navy" onClick={() => setEditing('new')}>+ New event</button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {events.map(ev => (
            <div key={ev.id} className="card" style={{ padding: 20 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
                <div>
                  <div style={{ fontSize: 17, fontWeight: 900, color: 'var(--navy)' }}>{ev.name}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--muted)', fontWeight: 600, marginTop: 2 }}>{ev.eyebrow} · {ev.categories.length} categories</div>
                </div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <button onClick={() => actions.updateItem('awardEvents', ev.id, { nominationsOpen: !ev.nominationsOpen })}
                    className="badge" style={{ cursor: 'pointer', background: ev.nominationsOpen ? '#e6f4ec' : 'var(--line2)', color: ev.nominationsOpen ? 'var(--ok)' : 'var(--muted)', padding: '6px 12px' }}
                    title="Click to open or close nominations">
                    Nominations {ev.nominationsOpen ? '● Open' : '○ Closed'}
                  </button>
                  <button className="btn btn-ghost btn-sm" onClick={() => setEditing(ev)}>Edit</button>
                  {events.length > 1 && <button onClick={() => { if (confirm('Delete the event "' + ev.name + '" and its categories? Recipients already published will remain on record.')) actions.deleteItem('awardEvents', ev.id); }} style={{ color: '#b4452f', fontWeight: 800, fontSize: 18, padding: '0 4px' }}>×</button>}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {ev.categories.map(c => (
                  <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 12px 6px 8px', borderRadius: 20, background: 'var(--sky-tint)', border: '1px solid var(--sky-soft)' }}>
                    <span style={{ width: 22, height: 22, borderRadius: 5, background: c.acc, color: '#fff', display: 'grid', placeItems: 'center', fontSize: 12, flex: '0 0 auto' }}>{c.ic}</span>
                    <span style={{ fontSize: 12.5, fontWeight: 800, color: 'var(--navy)' }}>{c.name}</span>
                    <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)' }}>{recCount(ev.name, c.name)}</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
        {editing && <EventEditor item={editing === 'new' ? null : editing} onClose={() => setEditing(null)} />}
      </div>
    );
  }

  return { AwardSetup };
})();
window.AwardSetup = AWARD_SETUP.AwardSetup;
