// Shared shell: nav context, crest, header, footer, small UI atoms.
const CTSCShell = (function () {
  const NavCtx = React.createContext(null);
  function useNav() { return React.useContext(NavCtx); }

  // Council crest mark (fallback when no logo uploaded)
  const CREST_SVG = "data:image/svg+xml," + encodeURIComponent(
    "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect width='100' height='100' rx='12' fill='#E8A33D'/><text x='50' y='50' font-family='Archivo,Arial,sans-serif' font-size='44' font-weight='900' fill='#0c4594' text-anchor='middle' dominant-baseline='central' letter-spacing='-3'>CT</text></svg>");

  function Crest({ size = 50 }) {
    return (
      <div style={{ width: size, height: size, background: 'var(--gold)', color: 'var(--navy)', display: 'grid',
        placeItems: 'center', fontWeight: 900, fontSize: size * 0.4, borderRadius: 5, letterSpacing: '-.05em', flex: '0 0 auto' }}>CT</div>
    );
  }

  // Real CTSC logo — Table Mountain + disa orchid emblem (blends on royal-blue chrome)
  function LogoMark({ size = 38 }) {
    return (
      <img src="assets/logo-mark.png" alt="Cape Town Sport Council"
        style={{ height: size, width: 'auto', display: 'block', flex: '0 0 auto' }} />
    );
  }

  function StatusBadge({ status }) {
    const map = { Approved: 'badge-approved', Pending: 'badge-pending', Draft: 'badge-draft' };
    const dot = { Approved: '●', Pending: '◐', Draft: '○' };
    return <span className={'badge ' + (map[status] || 'badge-draft')}>{dot[status] || '○'} {status}</span>;
  }

  // Table-Mountain photo placeholder (decorative) — shows uploaded src if provided
  function Photo({ h = 200, tag = 'Photo', style = {}, src, children }) {
    if (src) {
      return (
        <div className="photo" style={{ height: h, ...style }}>
          <img src={src} alt={tag} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          {children}
        </div>
      );
    }
    return (
      <div className="photo" style={{ height: h, ...style }}>
        <div className="grain"></div><div className="mtn"></div>
        {tag && <div className="ptag">◳ {tag}</div>}
        {children}
      </div>
    );
  }

  function Avatar({ name, sport, size = 64, src }) {
    const initials = name.split(' ').map(w => w[0]).slice(0, 2).join('');
    if (src) {
      return <div style={{ width: size, height: size, borderRadius: '50%', flex: '0 0 auto', overflow: 'hidden', border: '2px solid #fff', boxShadow: 'var(--shadow)' }}><img src={src} alt={name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /></div>;
    }
    return (
      <div style={{ width: size, height: size, borderRadius: '50%', flex: '0 0 auto', position: 'relative',
        overflow: 'hidden', background: 'linear-gradient(140deg,#2a6cb3,#0c4594)', display: 'grid', placeItems: 'center',
        color: '#fff', fontWeight: 800, fontSize: size * 0.32, border: '2px solid #fff', boxShadow: 'var(--shadow)' }}>
        <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: '46%', background: '#08315f',
          clipPath: 'polygon(0 65%,28% 30%,55% 52%,80% 22%,100% 48%,100% 100%,0 100%)', opacity: .55 }}></div>
        <span style={{ position: 'relative', zIndex: 1 }}>{initials}</span>
      </div>
    );
  }

  // Federation logo — shows uploaded logo if present, else the sport-initial monogram.
  function FedLogo({ fed, size = 48, radius = 6, fontSize }) {
    const fs = fontSize || size * 0.42;
    if (fed && fed.logo) {
      return (
        <div style={{ width: size, height: size, borderRadius: radius, flex: '0 0 auto', overflow: 'hidden', background: '#fff', border: '1px solid var(--line2)', display: 'grid', placeItems: 'center' }}>
          <img src={fed.logo} alt={(fed.name || '') + ' logo'} style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
        </div>
      );
    }
    return (
      <div style={{ width: size, height: size, borderRadius: radius, flex: '0 0 auto', background: 'var(--navy)', display: 'grid', placeItems: 'center', color: 'var(--gold)', fontWeight: 900, fontSize: fs }}>{((fed && fed.sport) || '?')[0]}</div>
    );
  }

  const NAV = [
    ['home', 'Home'], ['about', 'About'], ['federations', 'Federations'], ['heroes', 'Heroes'],
    ['awards', 'Awards'], ['resources', 'Resources'], ['events', 'Events'], ['transformation', 'Transformation'], ['news', 'News'], ['blog', 'Blog'],
  ];

  function Header() {
    const { route, go } = useNav();
    const { user, actions } = CTSCStore.useStore();
    const [menu, setMenu] = React.useState(false);
    return (
      <>
        <div style={{ background: 'var(--ink)', color: '#cdd9e2', fontSize: 12, letterSpacing: '.12em',
          textTransform: 'uppercase', fontWeight: 700 }}>
          <div className="wrap" style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 32px' }}>
            <span>Governance · Workflow · Transformation</span>
            <span style={{ color: 'var(--gold)' }}>Affiliated to SASCOC · Est. 2000</span>
          </div>
        </div>
        <header style={{ background: 'var(--navy)', color: '#fff', position: 'sticky', top: 0, zIndex: 50,
          boxShadow: '0 2px 12px rgba(6,25,42,.25)' }}>
          <div className="wrap" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20, padding: '22px 32px 18px' }}>
            <button onClick={() => go('home')} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, color: '#fff' }}>
              <LogoMark size={48} />
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 23, fontWeight: 900, lineHeight: 1.05, letterSpacing: '-.01em' }}>Cape Town Sport Council</div>
                <div style={{ fontSize: 11, letterSpacing: '.24em', textTransform: 'uppercase', color: '#8fb0c4', marginTop: 7 }}>The home for sport in Cape Town</div>
              </div>
            </button>
            <nav style={{ display: 'flex', gap: 26, alignItems: 'center', flexWrap: 'wrap', justifyContent: 'center' }}>
              {NAV.slice(1).filter(([id]) => (id !== 'resources' && id !== 'transformation') || user).map(([id, label]) => (
                <button key={id} onClick={() => go(id)} style={{ color: route.view === id ? 'var(--gold)' : '#cdd9e2',
                  fontSize: 14, fontWeight: 700 }}>{label}</button>
              ))}
              {user ? (
                <div style={{ position: 'relative' }}>
                  <button className="btn btn-gold btn-sm" onClick={() => setMenu(m => !m)}>
                    {user.role === 'council' ? '⚖ Council Admin' : '⊕ My Federation'} ▾
                  </button>
                  {menu && (
                    <div className="card" style={{ position: 'absolute', right: 0, top: 44, width: 220, padding: 8, zIndex: 60,
                      boxShadow: 'var(--shadow-lg)', color: 'var(--navy)' }}>
                      <div style={{ padding: '8px 10px', fontSize: 12, color: 'var(--muted)' }}>Signed in as<br /><b style={{ color: 'var(--navy)', fontSize: 13 }}>{user.name}</b></div>
                      <button onClick={() => { setMenu(false); go('admin'); }} style={menuItem}>Admin Dashboard</button>
                      <button onClick={() => { setMenu(false); go('admin', { tab: 'colours' }); }} style={menuItem}>Colours Commission</button>
                      <button onClick={() => { setMenu(false); go('admin', { tab: 'workflow' }); }} style={menuItem}>Approvals & Workflow</button>
                      <button onClick={() => { setMenu(false); actions.logout(); go('home'); }} style={{ ...menuItem, color: '#b4452f' }}>Sign out</button>
                    </div>
                  )}
                </div>
              ) : (
                <button className="btn btn-gold btn-sm" onClick={() => go('login')}>Member Login</button>
              )}
            </nav>
          </div>
        </header>
      </>
    );
  }
  const menuItem = { display: 'block', width: '100%', textAlign: 'left', padding: '9px 10px', fontSize: 14,
    fontWeight: 700, color: 'var(--navy)', borderRadius: 5 };

  function Footer() {
    const { go } = useNav();
    const { user } = CTSCStore.useStore();
    return (
      <footer style={{ background: 'var(--navy)', color: '#bcd3ee', marginTop: 60 }}>
        <div className="wrap" style={{ padding: '50px 32px 30px', display: 'grid', gridTemplateColumns: '1.5fr 1fr 1fr 1fr', gap: 30 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
              <LogoMark size={40} /><b style={{ color: '#fff', fontSize: 16 }}>Cape Town Sport Council</b>
            </div>
            <p style={{ fontSize: 14, lineHeight: 1.6, maxWidth: 320, margin: 0 }}>The official governing home for organised sport across the Cape — federations, clubs, coaches and the heroes who carry the city's colours.</p>
          </div>
          {[['Explore', [['about', 'About the Council'], ['federations', 'Federations'], ['heroes', 'Sport Heroes'], ['awards', 'Sport Awards & Honours'], ['resources', 'Documents & Calendar'], ['events', 'Events'], ['fundraising', 'Fundraising'], ['news', 'News'], ['blog', 'Blog']]],
            ['Governance', [['transformation', 'Transformation'], ['login', 'Member Login'], ['login', 'Colours Commission'], ['login', 'Approvals & Workflow'], ['news', 'Policies']]],
            ['Contact', [['', 'info@ctsc.org.za'], ['', '+27 21 000 0000'], ['', 'Athlone Sports Precinct'], ['', 'Cape Town, 7764']]]].map(([h, items]) => (
            <div key={h}>
              <div style={{ color: 'var(--gold)', fontSize: 12, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.12em', marginBottom: 14 }}>{h}</div>
              {items.filter(([v]) => !((v === 'resources' || v === 'transformation') && !user)).map(([v, label], i) => (
                <button key={i} onClick={() => v && go(v)} style={{ display: 'block', color: '#9fb6c4', fontSize: 14, padding: '5px 0', textAlign: 'left', lineHeight: 1.4 }}>{label}</button>
              ))}
            </div>
          ))}
        </div>
        <div className="wrap" style={{ padding: '18px 32px', borderTop: '1px solid #143246', fontSize: 12.5, display: 'flex', justifyContent: 'space-between' }}>
          <span>© 2026 Cape Town Sport Council. Prototype.</span>
          <span>Affiliated to SASCOC</span>
        </div>
      </footer>
    );
  }

  return { NavCtx, useNav, Crest, LogoMark, StatusBadge, Photo, Avatar, FedLogo, Header, Footer, NAV };
})();
window.CTSCShell = CTSCShell;
