// Federations directory + federation detail
function FederationsPage() {
  const { go } = CTSCShell.useNav();
  const { data } = CTSCStore.useStore();
  const { FedLogo } = CTSCShell;
  const [q, setQ] = React.useState('');
  const [status, setStatus] = React.useState('All');
  const statuses = ['All', 'Transformation reported', 'Awaiting report', 'SASCOC affiliated'];
  const match = (f) => status === 'All' ? true
    : status === 'Transformation reported' ? !!f.tr
    : status === 'Awaiting report' ? !f.tr
    : f.sascoc;
  const list = data.federations.filter(f =>
    match(f) &&
    (f.name.toLowerCase().includes(q.toLowerCase()) || f.sport.toLowerCase().includes(q.toLowerCase()) || (f.abbr || '').toLowerCase().includes(q.toLowerCase())));

  return (
    <div className="fade-in">
      <PageHead title="Affiliated Federations" sub={`${data.federations.length} member federations governing organised sport across the Cape.`} />
      <div className="wrap" style={{ padding: '0 32px 20px' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap', marginBottom: 22 }}>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search federations or sports…"
            style={{ flex: 1, minWidth: 240, fontFamily: 'inherit', fontSize: 15, padding: '12px 16px', border: '1.5px solid var(--line)', borderRadius: 6, background: '#fff' }} />
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {statuses.map(r => <button key={r} className={'chip' + (status === r ? ' active' : '')} onClick={() => setStatus(r)}>{r}</button>)}
          </div>
        </div>
        <div style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600, marginBottom: 16 }}>{list.length} federation{list.length !== 1 ? 's' : ''}</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16 }} className="stagger">
          {list.map((f, i) => (
            <button key={f.id} className="card card-hover" onClick={() => go('federation', { id: f.id })}
              style={{ textAlign: 'left', overflow: 'hidden', animationDelay: i * 30 + 'ms' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 20, borderBottom: '1px solid var(--line2)' }}>
                <div style={{ width: 48, height: 48, flex: '0 0 auto' }}><FedLogo fed={f} size={48} /></div>
                <div>
                  <div style={{ fontSize: 16.5, fontWeight: 800, lineHeight: 1.2 }}>{f.name}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--ocean)', fontWeight: 700, marginTop: 2 }}>{f.sport}</div>
                </div>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 20px', fontSize: 12.5, color: 'var(--muted)', fontWeight: 700 }}>
                <span>{f.abbr}{f.sascoc ? ' · SASCOC' : ''}</span>
                <span className={'badge ' + (f.tr ? 'badge-approved' : 'badge-draft')}>{f.tr ? '● Reported' : '○ Awaiting'}</span>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function FederationDetail({ id }) {
  const { go } = CTSCShell.useNav();
  const { data, user } = CTSCStore.useStore();
  const { fmtDate } = CTSCStore;
  const { Photo, Avatar, StatusBadge, FedLogo } = CTSCShell;
  const f = data.federations.find(x => x.id === id);
  if (!f) return <PageHead title="Federation not found" sub="" />;
  const heroes = data.heroes.filter(h => h.fedId === id && h.status === 'Approved');
  const events = data.events.filter(e => e.fedId === id && e.status === 'Approved');
  const news = data.news.filter(n => n.fedId === id && n.status === 'Approved');

  const TR = f.tr ? [['Women & girls', f.tr.women], ['Youth (U18)', f.tr.youth], ['Para / disability', f.tr.disability]] : null;

  return (
    <div className="fade-in">
      <section style={{ background: 'linear-gradient(180deg,var(--navy),var(--navy2))', color: '#fff' }}>
        <div className="wrap" style={{ padding: '28px 32px 40px' }}>
          <button onClick={() => go('federations')} style={{ color: '#8fb0c4', fontSize: 13, fontWeight: 700, marginBottom: 22 }}>‹ All federations</button>
          <div style={{ display: 'flex', gap: 22, alignItems: 'center' }}>
            <FedLogo fed={f} size={76} radius={10} fontSize={34} />
            <div>
              <div className="eyebrow gold" style={{ color: 'var(--gold)' }}>{f.sport}{f.sascoc ? ' · SASCOC Member' : ''}</div>
              <h1 style={{ fontSize: 40, fontWeight: 900, margin: '10px 0 6px', letterSpacing: '-.02em' }}>{f.name}</h1>
              <div style={{ fontSize: 14, color: '#bcd0de', fontWeight: 600 }}>{f.abbr !== '—' ? f.abbr + ' · ' : ''}{f.region} · {f.tr ? 'Transformation reported' : 'Transformation report outstanding'}</div>
            </div>
          </div>
        </div>
      </section>

      <div className="wrap" style={{ padding: '40px 32px 0', display: 'grid', gridTemplateColumns: '1fr 320px', gap: 40, alignItems: 'start' }}>
        <div>
          <h3 style={{ fontSize: 20, fontWeight: 900, margin: '0 0 12px' }}>About</h3>
          <p style={{ fontSize: 16, lineHeight: 1.65, color: '#3c4f5a', margin: '0 0 36px' }}>{f.about}</p>

          {heroes.length > 0 && <>
            <div className="sech"><h2 style={{ fontSize: 22 }}>Heroes</h2></div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14, marginBottom: 36 }}>
              {heroes.map(h => (
                <button key={h.id} className="card card-hover" onClick={() => go('hero', { id: h.id })} style={{ padding: 16, display: 'flex', gap: 14, alignItems: 'center', textAlign: 'left' }}>
                  <Avatar name={h.name} size={50} src={h.photo} />
                  <div><div style={{ fontSize: 15, fontWeight: 800 }}>{h.name}</div><div style={{ fontSize: 12.5, color: 'var(--muted)', fontWeight: 600 }}>{h.achievement}</div></div>
                </button>
              ))}
            </div>
          </>}

          <div className="sech"><h2 style={{ fontSize: 22 }}>Upcoming Events</h2></div>
          {events.length ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 36 }}>
              {events.map(e => (
                <button key={e.id} className="card card-hover" onClick={() => go('event', { id: e.id })} style={{ padding: 16, textAlign: 'left', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16 }}>
                  <div><div style={{ fontSize: 15, fontWeight: 800 }}>{e.title}</div><div style={{ fontSize: 12.5, color: 'var(--muted)', fontWeight: 600, marginTop: 3 }}>{e.venue}</div></div>
                  <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--ocean)', whiteSpace: 'nowrap' }}>{fmtDate(e.date)}</div>
                </button>
              ))}
            </div>
          ) : <p style={{ color: 'var(--muted)', fontSize: 14, marginBottom: 36 }}>No upcoming events listed.</p>}

          {news.length > 0 && <>
            <div className="sech"><h2 style={{ fontSize: 22 }}>Federation News</h2></div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {news.map(n => (
                <button key={n.id} className="card card-hover" onClick={() => go('article', { id: n.id })} style={{ padding: 16, textAlign: 'left' }}>
                  <div style={{ fontSize: 11.5, fontWeight: 800, color: 'var(--ocean)', textTransform: 'uppercase' }}>{n.category} · {fmtDate(n.date)}</div>
                  <div style={{ fontSize: 15.5, fontWeight: 800, marginTop: 5 }}>{n.title}</div>
                </button>
              ))}
            </div>
          </>}
        </div>

        {/* sidebar */}
        <aside style={{ display: 'flex', flexDirection: 'column', gap: 16, position: 'sticky', top: 92 }}>
          <div className="card" style={{ padding: 22 }}>
            <h4 style={{ fontSize: 13, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--navy)', margin: '0 0 16px' }}>Transformation Snapshot</h4>
            {TR ? <>
              {TR.map(([label, v]) => (
                <div key={label} style={{ marginBottom: 14 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, fontWeight: 700, marginBottom: 5 }}><span>{label}</span><span style={{ color: 'var(--ocean)' }}>{v}%</span></div>
                  <div style={{ height: 8, background: 'var(--line2)', borderRadius: 5, overflow: 'hidden' }}><div style={{ width: v + '%', height: '100%', background: 'linear-gradient(90deg,var(--ocean),var(--gold))', borderRadius: 5 }}></div></div>
                </div>
              ))}
              <div style={{ fontSize: 11.5, color: 'var(--muted)', fontWeight: 600, marginBottom: 8 }}>Last updated {fmtDate(f.trUpdated)}</div>
              {f.trDoc && <a className="btn btn-ghost btn-sm" href={f.trDoc} download={f.trDocName || 'transformation-report'} style={{ width: '100%', justifyContent: 'center', marginBottom: 8 }}>↓ Transformation report</a>}
              {user && <button className="btn btn-ghost btn-sm" style={{ width: '100%', justifyContent: 'center' }} onClick={() => go('transformation')}>Full transformation report ›</button>}
            </> : <>
              <div style={{ textAlign: 'center', padding: '8px 0 4px' }}>
                <div style={{ fontSize: 26, marginBottom: 6 }}>◔</div>
                <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--navy)' }}>Not yet reported</div>
                <p style={{ fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.5, margin: '6px 0 14px' }}>This federation hasn't submitted its transformation figures yet.</p>
                <button className="btn btn-gold btn-sm" style={{ width: '100%', justifyContent: 'center' }} onClick={() => go('login')}>Log in to submit ›</button>
              </div>
            </>}
          </div>
          <div className="card" style={{ padding: 22 }}>
            <h4 style={{ fontSize: 13, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--navy)', margin: '0 0 14px' }}>Compliance Standing</h4>
            {(() => {
              const ev = window.evalCompliance(f);
              const c = ev.compliant ? 'var(--ok)' : ev.passed >= 5 ? 'var(--warn)' : '#b4452f';
              return (
                <>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                    <div style={{ width: 46, height: 46, borderRadius: '50%', flex: '0 0 auto', background: 'conic-gradient(' + c + ' ' + (ev.pct * 3.6) + 'deg, var(--line2) 0)', display: 'grid', placeItems: 'center' }}>
                      <div style={{ width: 36, height: 36, borderRadius: '50%', background: '#fff', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 900, color: c }}>{ev.passed}/{ev.total}</div>
                    </div>
                    <div>
                      <div style={{ fontSize: 14.5, fontWeight: 900, color: c }}>{ev.compliant ? 'Compliant' : 'Action required'}</div>
                      <div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 600 }}>{ev.compliant && ev.until ? 'Good standing to ' + fmtDate(ev.until) : ev.passed + ' of ' + ev.total + ' requirements met'}</div>
                    </div>
                  </div>
                  {ev.compliant && ev.from && ev.until && <div style={{ fontSize: 11.5, fontWeight: 800, color: 'var(--ok)', background: '#f1f8f3', border: '1px solid #cfe8d6', borderRadius: 6, padding: '7px 10px', textAlign: 'center' }}>✓ Letter of Good Standing on file</div>}
                </>
              );
            })()}
          </div>
          <div className="card" style={{ padding: 22 }}>
            <h4 style={{ fontSize: 13, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--navy)', margin: '0 0 14px' }}>Governance & Contacts</h4>
            {f.president && <ContactBlock role="Chairperson / President" name={f.president} phone={f.presidentPhone} email={f.presidentEmail} />}
            {f.secretary && <ContactBlock role="Secretary" name={f.secretary} phone={f.secretaryPhone} email={f.secretaryEmail} />}
            <Row k="SASCOC member" v={f.sascoc ? 'Yes' : 'Not listed'} />
            <Row k="Region" v={f.region} />
          </div>
        </aside>
      </div>
    </div>
  );
}
function Row({ k, v }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '7px 0', borderBottom: '1px solid var(--line2)', fontSize: 13.5 }}>
    <span style={{ color: 'var(--muted)', fontWeight: 600, flex: '0 0 auto' }}>{k}</span><span style={{ fontWeight: 700, color: 'var(--navy)', textAlign: 'right', wordBreak: 'break-word' }}>{v}</span></div>;
}
function ContactBlock({ role, name, phone, email }) {
  return (
    <div style={{ padding: '0 0 12px', marginBottom: 12, borderBottom: '1px solid var(--line2)' }}>
      <div style={{ fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ocean)', marginBottom: 4 }}>{role}</div>
      {name && <div style={{ fontSize: 14.5, fontWeight: 800, color: 'var(--navy)' }}>{name}</div>}
      {phone && <div style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600, marginTop: 2 }}>{phone}</div>}
      {email && <a href={'mailto:' + email} style={{ fontSize: 13, color: 'var(--ocean)', fontWeight: 700, wordBreak: 'break-all', display: 'inline-block', marginTop: 2 }}>{email}</a>}
    </div>
  );
}

// shared page header
function PageHead({ title, sub }) {
  return (
    <section style={{ background: 'linear-gradient(180deg,var(--navy),var(--navy2))', color: '#fff' }}>
      <div className="wrap" style={{ padding: '46px 32px' }}>
        <h1 style={{ fontSize: 42, fontWeight: 900, margin: 0, letterSpacing: '-.02em' }}>{title}</h1>
        {sub && <p style={{ fontSize: 16.5, color: '#bcd0de', margin: '12px 0 0', maxWidth: 600, lineHeight: 1.5 }}>{sub}</p>}
      </div>
    </section>
  );
}
window.FederationsPage = FederationsPage;
window.FederationDetail = FederationDetail;
window.PageHead = PageHead;
