// Federation Resources hub — document library + meetings/workshops calendar (public, federation-facing).
const CTSCHub = (function () {
  const DOC_CATS = ['Constitution', 'Meeting Notice', 'Agenda', 'Minutes', 'Correspondence', 'Policy'];
  const DOC_META = {
    'Constitution': { ic: '§', c: 'var(--navy)' },
    'Meeting Notice': { ic: '◷', c: 'var(--gold-d)' },
    'Agenda': { ic: '☷', c: 'var(--ocean)' },
    'Minutes': { ic: '✎', c: 'var(--ok)' },
    'Correspondence': { ic: '✉', c: 'var(--warn)' },
    'Policy': { ic: '◆', c: 'var(--navy2)' },
  };
  const TYPE_META = {
    'Meeting': { c: 'var(--navy)', label: 'Meeting' },
    'Workshop': { c: 'var(--ocean)', label: 'Workshop' },
    'AGM': { c: 'var(--gold)', label: 'AGM' },
    'Deadline': { c: 'var(--warn)', label: 'Deadline' },
    'Event': { c: 'var(--ok)', label: 'Event' },
  };
  const CAL_TYPES = ['Meeting', 'Workshop', 'AGM', 'Deadline', 'Event'];
  const extColor = (ext) => ({ PDF: '#b21f1f', DOCX: '#1453a6', DOC: '#1453a6', XLSX: '#1f8a5b', XLS: '#1f8a5b' }[(ext || '').toUpperCase()] || 'var(--muted)');
  const WD = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const ymd = (d) => d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');

  // ---- Reusable month calendar grid ----
  function MonthCalendar({ events, month, onPrev, onNext, selected, onSelect }) {
    const first = new Date(month.getFullYear(), month.getMonth(), 1);
    const lead = (first.getDay() + 6) % 7; // Mon=0
    const daysIn = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
    const todayStr = ymd(new Date());
    const byDay = {};
    events.forEach(e => { (byDay[e.date] = byDay[e.date] || []).push(e); });

    const cells = [];
    for (let i = 0; i < lead; i++) cells.push(null);
    for (let d = 1; d <= daysIn; d++) cells.push(d);
    while (cells.length % 7 !== 0) cells.push(null);

    return (
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 20px', background: 'var(--navy)', color: '#fff' }}>
          <button onClick={onPrev} className="btn btn-sm" style={{ background: 'rgba(255,255,255,.12)', color: '#fff', padding: '7px 13px' }}>‹</button>
          <div style={{ fontSize: 17, fontWeight: 900, letterSpacing: '-.01em' }}>{MONTHS[month.getMonth()]} {month.getFullYear()}</div>
          <button onClick={onNext} className="btn btn-sm" style={{ background: 'rgba(255,255,255,.12)', color: '#fff', padding: '7px 13px' }}>›</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', borderBottom: '1px solid var(--line2)' }}>
          {WD.map(w => <div key={w} style={{ textAlign: 'center', padding: '10px 0', fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--muted)' }}>{w}</div>)}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)' }}>
          {cells.map((d, i) => {
            if (d === null) return <div key={i} style={{ minHeight: 92, background: '#fbfcfe', borderRight: (i % 7 !== 6) ? '1px solid var(--line2)' : 'none', borderBottom: '1px solid var(--line2)' }}></div>;
            const ds = ymd(new Date(month.getFullYear(), month.getMonth(), d));
            const evs = byDay[ds] || [];
            const isToday = ds === todayStr;
            const isSel = ds === selected;
            return (
              <button key={i} onClick={() => onSelect && onSelect(isSel ? null : ds)} style={{ minHeight: 92, textAlign: 'left', padding: '7px 8px', verticalAlign: 'top',
                borderRight: (i % 7 !== 6) ? '1px solid var(--line2)' : 'none', borderBottom: '1px solid var(--line2)',
                background: isSel ? 'var(--sky-tint)' : '#fff', cursor: evs.length || onSelect ? 'pointer' : 'default', position: 'relative' }}>
                <div style={{ display: 'inline-grid', placeItems: 'center', width: 24, height: 24, borderRadius: '50%', fontSize: 12.5, fontWeight: isToday ? 900 : 700,
                  background: isToday ? 'var(--gold)' : 'transparent', color: isToday ? '#fff' : 'var(--navy)', marginBottom: 3 }}>{d}</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
                  {evs.slice(0, 2).map(e => (
                    <div key={e.id} title={e.title} style={{ fontSize: 10.5, fontWeight: 700, color: '#fff', background: TYPE_META[e.type].c, borderRadius: 3, padding: '2px 5px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.title}</div>
                  ))}
                  {evs.length > 2 && <div style={{ fontSize: 10.5, fontWeight: 800, color: 'var(--ocean)' }}>+{evs.length - 2} more</div>}
                </div>
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  return { DOC_CATS, DOC_META, TYPE_META, CAL_TYPES, extColor, MonthCalendar, MONTHS, ymd };
})();
window.CTSCHub = CTSCHub;

// ---- Public Resources page ----
function ResourcesPage() {
  const { data } = CTSCStore.useStore();
  const { fmtDate, fedName } = CTSCStore;
  const { DOC_CATS, DOC_META, TYPE_META, MonthCalendar, MONTHS } = CTSCHub;
  const [view, setView] = React.useState('documents');

  // documents
  const [q, setQ] = React.useState('');
  const [cat, setCat] = React.useState('All');
  const docs = (data.documents || []).filter(d => d.status !== 'Draft');
  const filtered = docs.filter(d => {
    if (cat !== 'All' && d.category !== cat) return false;
    if (q.trim() && !((d.title + ' ' + (d.note || '')).toLowerCase().includes(q.toLowerCase().trim()))) return false;
    return true;
  }).sort((a, b) => (a.date < b.date ? 1 : -1));

  // calendar
  const today = new Date();
  const [month, setMonth] = React.useState(new Date(today.getFullYear(), today.getMonth(), 1));
  const [sel, setSel] = 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)).slice(0, 6);
  const selEvents = sel ? cal.filter(e => e.date === sel) : null;

  return (
    <div className="fade-in">
      {/* hero */}
      <section className="tx-topo" style={{ background: 'linear-gradient(180deg,var(--navy),var(--navy2))', color: '#fff' }}>
        <div className="wrap" style={{ padding: '46px 32px 0' }}>
          <div className="eyebrow gold" style={{ color: 'var(--gold)' }}>Federation Resources</div>
          <h1 style={{ fontSize: 46, fontWeight: 900, margin: '14px 0 8px', letterSpacing: '-.02em' }}>Documents &amp; Calendar</h1>
          <p style={{ fontSize: 16.5, color: '#bcd0de', maxWidth: 660, margin: 0, lineHeight: 1.55 }}>
            Official documents the Council shares with affiliated federations — constitutions, meeting notices, agendas, minutes and correspondence — plus the calendar of meetings and workshops.
          </p>
          <div style={{ display: 'flex', gap: 4, marginTop: 26 }}>
            {[['documents', '☷ Documents'], ['calendar', '◷ Calendar']].map(([id, label]) => (
              <button key={id} onClick={() => setView(id)} style={{ padding: '13px 22px', fontSize: 14.5, fontWeight: 800, color: view === id ? 'var(--navy)' : '#cfe1ec',
                background: view === id ? 'var(--sand)' : 'transparent', borderRadius: '8px 8px 0 0',
                borderTop: '1px solid ' + (view === id ? 'transparent' : 'rgba(255,255,255,.18)'),
                borderLeft: '1px solid ' + (view === id ? 'transparent' : 'rgba(255,255,255,.18)'),
                borderRight: '1px solid ' + (view === id ? 'transparent' : 'rgba(255,255,255,.18)'),
                borderBottom: 'none' }}>{label}</button>
            ))}
          </div>
        </div>
      </section>

      {view === 'documents' ? (
        <div className="wrap" style={{ padding: '30px 32px 0' }}>
          {/* toolbar */}
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap', marginBottom: 14 }}>
            <div style={{ position: 'relative', flex: '1 1 280px', minWidth: 240 }}>
              <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted2)', fontSize: 15 }}>⌕</span>
              <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search documents…"
                style={{ width: '100%', fontFamily: 'inherit', fontSize: 15, color: 'var(--navy)', padding: '12px 14px 12px 38px', border: '1.5px solid var(--line)', borderRadius: 7, background: '#fff', outline: 'none' }} />
            </div>
            <div style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 700 }}>{filtered.length} document{filtered.length !== 1 ? 's' : ''}</div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 22 }}>
            {['All', ...DOC_CATS].map(c => <button key={c} className={'chip' + (cat === c ? ' active' : '')} onClick={() => setCat(c)}>{c}</button>)}
          </div>
          {/* list */}
          {filtered.length === 0 ? (
            <div className="card" style={{ padding: 48, textAlign: 'center', color: 'var(--muted)' }}>
              <div style={{ fontSize: 28, marginBottom: 8 }}>☷</div>
              <div style={{ fontWeight: 800, color: 'var(--navy)' }}>No documents match your filters</div>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, paddingBottom: 8 }} className="stagger">
              {filtered.map(d => {
                const meta = DOC_META[d.category] || { ic: '◆', c: 'var(--navy)' };
                return (
                  <div key={d.id} className="card card-hover" style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 16 }}>
                    <div style={{ width: 50, height: 58, borderRadius: 7, flex: '0 0 auto', background: 'var(--sky-tint)', border: '1px solid var(--sky-soft)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4 }}>
                      <span style={{ fontSize: 20, color: meta.c }}>{meta.ic}</span>
                      <span style={{ fontSize: 8.5, fontWeight: 900, letterSpacing: '.04em', color: CTSCHub.extColor(d.ext) }}>{(d.ext || 'PDF').toUpperCase()}</span>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexWrap: 'wrap' }}>
                        <span style={{ fontSize: 15.5, fontWeight: 800, color: 'var(--navy)', lineHeight: 1.25 }}>{d.title}</span>
                        <span className="badge" style={{ background: 'var(--sky-tint)', color: meta.c }}>{d.category}</span>
                      </div>
                      {d.note && <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4, lineHeight: 1.5 }}>{d.note}</div>}
                      <div style={{ fontSize: 12, color: 'var(--muted2)', fontWeight: 600, marginTop: 5 }}>
                        {d.fedId ? fedName(data, d.fedId) : 'All federations'} · {fmtDate(d.date)} · {d.size || '—'}
                      </div>
                    </div>
                    <a className="btn btn-navy btn-sm" href={d.data || '#'} download={(d.title || 'document') + '.' + (d.ext || 'pdf').toLowerCase()} style={{ flex: '0 0 auto' }}>↓ Download</a>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      ) : (
        <div className="wrap" style={{ padding: '30px 32px 0' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1.7fr 1fr', gap: 20, alignItems: 'start' }}>
            <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))}
                selected={sel} onSelect={setSel} />
              <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', marginTop: 14 }}>
                {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>
            <div className="card" style={{ padding: 22 }}>
              <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--ocean)', textTransform: 'uppercase', letterSpacing: '.1em', marginBottom: 14 }}>
                {sel ? CTSCStore.fmtDate(sel) : 'Upcoming'}
              </div>
              {(selEvents || upcoming).length === 0 ? (
                <p style={{ fontSize: 13.5, color: 'var(--muted)', margin: 0 }}>{sel ? 'Nothing scheduled this day.' : 'No upcoming items.'}</p>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {(selEvents || upcoming).map(e => (
                    <div key={e.id} style={{ display: 'flex', gap: 12, paddingBottom: 12, borderBottom: '1px solid var(--line2)' }}>
                      <div style={{ width: 4, borderRadius: 3, background: TYPE_META[e.type].c, flex: '0 0 auto' }}></div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--navy)', lineHeight: 1.25 }}>{e.title}</div>
                        <div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 600, marginTop: 3 }}>
                          {!sel && fmtDate(e.date)}{!sel && (e.time ? ' · ' : '')}{e.time && (e.time + (e.end ? '–' + e.end : ''))}
                        </div>
                        {e.venue && <div style={{ fontSize: 12, color: 'var(--muted2)', fontWeight: 600, marginTop: 2 }}>⚲ {e.venue}</div>}
                        <span className="badge" style={{ marginTop: 6, background: 'var(--sky-tint)', color: TYPE_META[e.type].c }}>{TYPE_META[e.type].label}</span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
              {sel && <button className="btn btn-ghost btn-sm" style={{ marginTop: 14 }} onClick={() => setSel(null)}>Show all upcoming</button>}
            </div>
          </div>
          <div style={{ height: 24 }}></div>
        </div>
      )}
    </div>
  );
}
window.ResourcesPage = ResourcesPage;
