// Admin managers for the Resources hub — Documents (file upload) + Calendar.
const HUBADMIN = (function () {
  const fileSize = (bytes) => bytes < 1024 ? bytes + ' B' : bytes < 1048576 ? (bytes / 1024).toFixed(0) + ' KB' : (bytes / 1048576).toFixed(1) + ' MB';
  const extOf = (name) => { const m = (name || '').match(/\.([a-z0-9]+)$/i); return m ? m[1].toUpperCase() : 'FILE'; };

  function Dialog({ title, onClose, children, footer }) {
    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(560px,100%)', maxHeight: '88vh', 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 }}>{title}</h3>
            <button onClick={onClose} style={{ fontSize: 22, color: 'var(--muted)' }}>✕</button>
          </div>
          <div style={{ padding: 26 }}>{children}</div>
          <div style={{ padding: '16px 26px', borderTop: '1px solid var(--line2)', display: 'flex', gap: 10, justifyContent: 'flex-end', position: 'sticky', bottom: 0, background: '#fff' }}>{footer}</div>
        </div>
      </div>
    );
  }

  // ---------------- Documents ----------------
  function DocForm({ item, onClose }) {
    const { data, actions } = CTSCStore.useStore();
    const { DOC_CATS } = CTSCHub;
    const [v, setV] = React.useState(item ? { ...item } : { title: '', category: 'Constitution', fedId: '', date: '2026-06-09', note: '', ext: '', size: '', data: '' });
    const set = (k, val) => setV(s => ({ ...s, [k]: val }));
    const ref = React.useRef();
    const pick = (e) => {
      const f = e.target.files[0]; if (!f) return;
      const r = new FileReader();
      r.onload = () => setV(s => ({ ...s, data: r.result, ext: extOf(f.name), size: fileSize(f.size), title: s.title || f.name.replace(/\.[a-z0-9]+$/i, '') }));
      r.readAsDataURL(f);
    };
    const save = () => {
      const payload = { ...v, fedId: v.fedId || null, status: 'Published' };
      if (item) actions.updateItem('documents', item.id, payload); else actions.addItem('documents', payload);
      onClose();
    };
    const valid = v.title.trim() && (v.data || item);
    return (
      <Dialog title={item ? 'Edit document' : 'Upload document'} onClose={onClose}
        footer={<><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' : 'Publish document'}</button></>}>
        <div className="field">
          <label>File</label>
          <div onClick={() => ref.current.click()} style={{ border: '1.5px dashed var(--line)', borderRadius: 8, padding: 22, textAlign: 'center', cursor: 'pointer', background: '#fbfcfe' }}>
            {v.data
              ? <div style={{ color: 'var(--navy)', fontWeight: 800 }}><span style={{ fontSize: 22, color: CTSCHub.extColor(v.ext) }}>▤</span><div style={{ fontSize: 13.5, marginTop: 6 }}>{v.ext} file ready · {v.size}</div><div style={{ fontSize: 12, color: 'var(--ocean)', marginTop: 3 }}>Click to replace</div></div>
              : <div style={{ color: 'var(--muted)' }}><div style={{ fontSize: 26 }}>↥</div><div style={{ fontSize: 13, fontWeight: 700, marginTop: 6 }}>Click to upload a file</div><div style={{ fontSize: 12, marginTop: 3 }}>PDF, Word or Excel</div></div>}
          </div>
          <input ref={ref} type="file" accept=".pdf,.doc,.docx,.xls,.xlsx" onChange={pick} style={{ display: 'none' }} />
        </div>
        <div className="field"><label>Document title</label><input value={v.title} onChange={e => set('title', e.target.value)} placeholder="e.g. CTSC Constitution 2024" /></div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div className="field" style={{ margin: 0 }}><label>Category</label><select value={v.category} onChange={e => set('category', e.target.value)}>{DOC_CATS.map(c => <option key={c}>{c}</option>)}</select></div>
          <div className="field" style={{ margin: 0 }}><label>Date</label><input type="date" value={v.date} onChange={e => set('date', e.target.value)} /></div>
        </div>
        <div className="field"><label>Visible to</label>
          <select value={v.fedId || ''} onChange={e => set('fedId', e.target.value)}>
            <option value="">All federations</option>
            {data.federations.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
          </select>
        </div>
        <div className="field" style={{ marginBottom: 0 }}><label>Note (optional)</label><textarea value={v.note} onChange={e => set('note', e.target.value)} placeholder="Short description shown to federations" /></div>
      </Dialog>
    );
  }

  function DocumentsManager() {
    const { data, actions } = CTSCStore.useStore();
    const { fmtDate, fedName } = CTSCStore;
    const { DOC_CATS, DOC_META } = CTSCHub;
    const [editing, setEditing] = React.useState(null);
    const [cat, setCat] = React.useState('All');
    const docs = (data.documents || []).filter(d => cat === 'All' || d.category === cat).sort((a, b) => (a.date < b.date ? 1 : -1));

    return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
          <div>
            <h2 style={{ fontSize: 26, fontWeight: 900, margin: 0 }}>Documents</h2>
            <p style={{ fontSize: 14, color: 'var(--muted)', margin: '4px 0 0' }}>Publish documents for federations to view — constitutions, notices, agendas, minutes, correspondence &amp; policies.</p>
          </div>
          <button className="btn btn-navy" onClick={() => setEditing('new')}>↥ Upload document</button>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', margin: '18px 0 16px' }}>
          {['All', ...DOC_CATS].map(c => <button key={c} className={'chip' + (cat === c ? ' active' : '')} onClick={() => setCat(c)}>{c}</button>)}
        </div>
        {docs.length === 0 ? (
          <div className="card" style={{ padding: 40, textAlign: 'center', color: 'var(--muted)' }}>
            <div style={{ fontSize: 30, marginBottom: 8 }}>☷</div><div style={{ fontWeight: 700, color: 'var(--navy)' }}>No documents yet</div>
            <p style={{ fontSize: 14, margin: '6px 0 16px' }}>Upload your first document for federations.</p>
            <button className="btn btn-gold" style={{ margin: '0 auto' }} onClick={() => setEditing('new')}>↥ Upload document</button>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {docs.map(d => {
              const meta = DOC_META[d.category] || { ic: '◆', c: 'var(--navy)' };
              return (
                <div key={d.id} className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 14 }}>
                  <div style={{ width: 44, height: 50, borderRadius: 6, flex: '0 0 auto', background: 'var(--sky-tint)', border: '1px solid var(--sky-soft)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 3 }}>
                    <span style={{ fontSize: 17, color: meta.c }}>{meta.ic}</span>
                    <span style={{ fontSize: 8, fontWeight: 900, color: CTSCHub.extColor(d.ext) }}>{(d.ext || 'PDF').toUpperCase()}</span>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 15, fontWeight: 800, color: 'var(--navy)', lineHeight: 1.2 }}>{d.title}</div>
                    <div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 600, marginTop: 3 }}>{d.category} · {d.fedId ? fedName(data, d.fedId) : 'All federations'} · {fmtDate(d.date)}{d.size ? ' · ' + d.size : ''}</div>
                  </div>
                  <a className="btn btn-ghost btn-sm" href={d.data || '#'} download={(d.title || 'document') + '.' + (d.ext || 'pdf').toLowerCase()}>↓</a>
                  <button className="btn btn-ghost btn-sm" onClick={() => setEditing(d)}>Edit</button>
                  <button onClick={() => { if (confirm('Delete this document?')) actions.deleteItem('documents', d.id); }} style={{ color: '#b4452f', fontWeight: 800, fontSize: 18, padding: '0 4px' }}>×</button>
                </div>
              );
            })}
          </div>
        )}
        {editing && <DocForm item={editing === 'new' ? null : editing} onClose={() => setEditing(null)} />}
      </div>
    );
  }

  // ---------------- Calendar ----------------
  function CalForm({ item, onClose }) {
    const { data, actions } = CTSCStore.useStore();
    const { CAL_TYPES } = CTSCHub;
    const [v, setV] = React.useState(item ? { ...item } : { title: '', type: 'Meeting', date: '2026-06-09', time: '18:00', end: '', venue: '', fedId: '', desc: '' });
    const set = (k, val) => setV(s => ({ ...s, [k]: val }));
    const save = () => {
      const payload = { ...v, fedId: v.fedId || null };
      if (item) actions.updateItem('calendar', item.id, payload); else actions.addItem('calendar', payload);
      onClose();
    };
    const valid = v.title.trim() && v.date;
    return (
      <Dialog title={item ? 'Edit calendar item' : 'Add to calendar'} onClose={onClose}
        footer={<><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' : 'Add to calendar'}</button></>}>
        <div className="field"><label>Title</label><input value={v.title} onChange={e => set('title', e.target.value)} placeholder="e.g. Quarterly Council Meeting" /></div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div className="field" style={{ margin: 0 }}><label>Type</label><select value={v.type} onChange={e => set('type', e.target.value)}>{CAL_TYPES.map(t => <option key={t}>{t}</option>)}</select></div>
          <div className="field" style={{ margin: 0 }}><label>Date</label><input type="date" value={v.date} onChange={e => set('date', e.target.value)} /></div>
          <div className="field" style={{ margin: 0 }}><label>Start time</label><input type="time" value={v.time} onChange={e => set('time', e.target.value)} /></div>
          <div className="field" style={{ margin: 0 }}><label>End time</label><input type="time" value={v.end} onChange={e => set('end', e.target.value)} /></div>
        </div>
        <div className="field"><label>Venue</label><input value={v.venue} onChange={e => set('venue', e.target.value)} placeholder="e.g. Athlone Sports Precinct — Boardroom" /></div>
        <div className="field"><label>For</label>
          <select value={v.fedId || ''} onChange={e => set('fedId', e.target.value)}>
            <option value="">All federations</option>
            {data.federations.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
          </select>
        </div>
        <div className="field" style={{ marginBottom: 0 }}><label>Details (optional)</label><textarea value={v.desc} onChange={e => set('desc', e.target.value)} /></div>
      </Dialog>
    );
  }

  function CalendarManager() {
    const { data, actions } = CTSCStore.useStore();
    const { fmtDate } = CTSCStore;
    const { TYPE_META, MonthCalendar } = CTSCHub;
    const today = new Date();
    const [month, setMonth] = React.useState(new Date(today.getFullYear(), today.getMonth(), 1));
    const [editing, setEditing] = React.useState(null);
    const cal = (data.calendar || []).slice().sort((a, b) => (a.date + (a.time || '')).localeCompare(b.date + (b.time || '')));
    const upcoming = cal.filter(e => e.date >= CTSCHub.ymd(today));

    return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
          <div>
            <h2 style={{ fontSize: 26, fontWeight: 900, margin: 0 }}>Calendar</h2>
            <p style={{ fontSize: 14, color: 'var(--muted)', margin: '4px 0 0' }}>Plot meetings and workshops. Published to the Resources page for federations.</p>
          </div>
          <button className="btn btn-navy" onClick={() => setEditing('new')}>+ Add to calendar</button>
        </div>
        <MonthCalendar events={cal} month={month}
          onPrev={() => setMonth(m => new Date(m.getFullYear(), m.getMonth() - 1, 1))}
          onNext={() => setMonth(m => new Date(m.getFullYear(), m.getMonth() + 1, 1))} />
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', margin: '14px 0 26px' }}>
          {Object.entries(TYPE_META).map(([k, v]) => (
            <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12.5, fontWeight: 700, color: 'var(--muted)' }}>
              <span style={{ width: 12, height: 12, borderRadius: 3, background: v.c }}></span>{v.label}
            </div>
          ))}
        </div>
        <div className="sech"><h2 style={{ fontSize: 18 }}>Scheduled items</h2><span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 700 }}>{upcoming.length} upcoming</span></div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {cal.map(e => (
            <div key={e.id} className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 14, opacity: e.date < CTSCHub.ymd(today) ? .6 : 1 }}>
              <div style={{ width: 4, alignSelf: 'stretch', borderRadius: 3, background: TYPE_META[e.type].c, flex: '0 0 auto' }}></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 800, color: 'var(--navy)', lineHeight: 1.2 }}>{e.title}</div>
                <div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 600, marginTop: 3 }}>{fmtDate(e.date)}{e.time ? ' · ' + e.time + (e.end ? '–' + e.end : '') : ''}{e.venue ? ' · ' + e.venue : ''}</div>
              </div>
              <span className="badge" style={{ background: 'var(--sky-tint)', color: TYPE_META[e.type].c }}>{e.type}</span>
              <button className="btn btn-ghost btn-sm" onClick={() => setEditing(e)}>Edit</button>
              <button onClick={() => { if (confirm('Delete this calendar item?')) actions.deleteItem('calendar', e.id); }} style={{ color: '#b4452f', fontWeight: 800, fontSize: 18, padding: '0 4px' }}>×</button>
            </div>
          ))}
        </div>
        {editing && <CalForm item={editing === 'new' ? null : editing} onClose={() => setEditing(null)} />}
      </div>
    );
  }

  return { DocumentsManager, CalendarManager };
})();
window.DocumentsManager = HUBADMIN.DocumentsManager;
window.CalendarManager = HUBADMIN.CalendarManager;
