// Dedicated Sports landing page. Routed via `#/sports`.
// Sub-grouped by `tool.group` into Calculators / Routes / Files / Race Day.

(function () {
  const { useMemo, useState, useEffect } = React;

  function SportsPage({ onOpenTool, favorites, toggleFav, pricing, entitlements, theme, query = '' }) {
    const [, t] = window.useI18n();
    const [activeGroup, setActiveGroup] = useState('all');
    // Admin-editable settings (featured tool, hero copy, group overrides). Falls
    // back to baked-in defaults if Supabase is offline or rows aren't set.
    const [config, setConfig] = useState({});

    useEffect(() => {
      if (theme) document.documentElement.dataset.theme = theme;
    }, [theme]);

    useEffect(() => {
      const sb = window.getSupabase?.();
      if (!sb) return;
      sb.from('settings').select('key, value').in('key', [
        'featured_sports_tool',
        'sports.hero_badge',
        'sports.hero_title',
        'sports.hero_title_hl',
        'sports.hero_sub',
        'sports.groups',
      ]).then(({ data }) => {
        if (!Array.isArray(data)) return;
        const m = {}; for (const r of data) m[r.key] = r.value;
        setConfig(m);
      });
    }, []);

    // Merge group overrides into the baked-in defaults — admin can set a
    // sparse diff (just the fields they changed) per group id.
    const groupOverrides = Array.isArray(config['sports.groups']) ? config['sports.groups'] : null;
    const effectiveGroups = (window.SPORT_GROUPS || []).map((g) => {
      const override = groupOverrides?.find((o) => o.id === g.id);
      return override ? { ...g, ...override } : g;
    });

    const sportsTools = useMemo(() => window.TOOLS.filter((x) => x.cat === 'sports'), []);
    const filtered = useMemo(() => {
      let list = sportsTools;
      if (activeGroup !== 'all') list = list.filter((x) => x.group === activeGroup);
      const q = query.trim().toLowerCase();
      if (q) list = list.filter((x) => x.name.toLowerCase().includes(q) || x.desc.toLowerCase().includes(q));
      return list;
    }, [sportsTools, activeGroup, query]);

    const groupCounts = useMemo(() => {
      const m = { all: sportsTools.length };
      effectiveGroups.forEach((g) => { m[g.id] = sportsTools.filter((x) => x.group === g.id).length; });
      return m;
    }, [sportsTools, effectiveGroups]);

    const featuredId = config['featured_sports_tool'] || 'pace-calculator';
    const featured = sportsTools.find((x) => x.id === featuredId) || sportsTools.find((x) => x.id === 'pace-calculator');

    const isToolLocked = (id) => {
      const p = pricing?.[id];
      if (!p || !p.active || p.tier === 'free') return false;
      return !(entitlements || []).includes(p.tier);
    };
    const tierOf = (id) => pricing?.[id]?.tier || 'free';

    return (
      <>
        <main className="container sports-page">
          <section className="sports-hero">
            <div className="sports-hero-deco" aria-hidden="true">
              <span className="sd1" /><span className="sd2" /><span className="sd3" />
              <span className="sd4" /><span className="sd5" />
            </div>
            <div className="sports-hero-tag">
              <window.Icon name="run" size={14} strokeWidth={2} />
              <span>{config['sports.hero_badge'] || 'FOR RUNNERS · CYCLISTS · TRIATHLETES'}</span>
            </div>
            <h1 className="sports-hero-title">
              {config['sports.hero_title'] || 'Train smarter.'}{' '}
              <span className="hl">{config['sports.hero_title_hl'] || 'Run further.'}</span>
            </h1>
            <p className="sports-hero-sub">
              {config['sports.hero_sub']
                || `${sportsTools.length} privacy-first tools for athletes — pace, zones, GPX, hydration and training load. Everything runs in your browser.`}
            </p>
            <div className="sports-hero-stats">
              <div className="shs-item">
                <div className="shs-v">{sportsTools.length}</div>
                <div className="shs-l">tools</div>
              </div>
              <div className="shs-item">
                <div className="shs-v">{effectiveGroups.length}</div>
                <div className="shs-l">categories</div>
              </div>
              <div className="shs-item">
                <div className="shs-v">0</div>
                <div className="shs-l">uploads</div>
              </div>
              <div className="shs-item">
                <div className="shs-v">100%</div>
                <div className="shs-l">private</div>
              </div>
            </div>
          </section>

          {featured && (
            <section className="sports-featured" onClick={() => onOpenTool(featured)}
                     role="button" tabIndex={0}
                     onKeyDown={(e) => { if (e.key === 'Enter') onOpenTool(featured); }}>
              <div className="sf-left">
                <div className="sf-tag">FEATURED</div>
                <h2 className="sf-title">Pace Calculator</h2>
                <p className="sf-desc">Convert between pace, time and distance instantly.
                  Switch between min/km and min/mile, share the result with your training group.</p>
                <button className="btn btn-primary sf-cta" onClick={(e) => { e.stopPropagation(); onOpenTool(featured); }}>
                  <window.Icon name="stopwatch" size={16} /> Open Pace Calculator
                </button>
              </div>
              <div className="sf-visual" aria-hidden="true">
                <div className="sf-ring sf-ring-1" />
                <div className="sf-ring sf-ring-2" />
                <div className="sf-ring sf-ring-3" />
                <div className="sf-core"><window.Icon name="run" size={56} strokeWidth={1.5} /></div>
              </div>
            </section>
          )}

          <section className="sports-groups">
            {effectiveGroups.map((g) => {
              const items = sportsTools.filter((x) => x.group === g.id).slice(0, 4);
              return (
                <button key={g.id} className="sports-group-card" style={{ '--sg-tint': g.tint }}
                        onClick={() => { setActiveGroup(g.id); document.getElementById('sports-grid')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); }}>
                  <div className="sgc-head">
                    <div className="sgc-icon"><window.Icon name={g.icon} size={20} /></div>
                    <span className="sgc-count">{groupCounts[g.id]} tools</span>
                  </div>
                  <div className="sgc-name">{g.name}</div>
                  <div className="sgc-desc">{g.desc}</div>
                  <div className="sgc-tools">
                    {items.map((x) => <span key={x.id} className="sgc-tag">{x.name}</span>)}
                  </div>
                  <div className="sgc-arrow"><window.Icon name="arrow" size={14} /></div>
                </button>
              );
            })}
          </section>

          <section id="sports-grid" className="sports-grid-section">
            <div className="sports-filter-row">
              <button className={`filter-pill ${activeGroup === 'all' ? 'active' : ''}`}
                      onClick={() => setActiveGroup('all')}
                      style={activeGroup === 'all' ? { background: '#16a34a', boxShadow: '0 4px 12px -4px rgba(22,163,74,.5)' } : {}}>
                <span className="fpc-icon"><window.Icon name="grid" size={14} /></span>
                All sports tools <span style={{ opacity: 0.6, fontWeight: 500 }}>· {groupCounts.all}</span>
              </button>
              {effectiveGroups.map((g) => (
                <button key={g.id} className={`filter-pill ${activeGroup === g.id ? 'active' : ''}`}
                        onClick={() => setActiveGroup(g.id)}
                        style={activeGroup === g.id ? { background: g.tint, boxShadow: `0 4px 12px -4px ${g.tint}80` } : {}}>
                  <span className="fpc-icon" style={{ color: activeGroup === g.id ? 'white' : g.tint }}>
                    <window.Icon name={g.icon} size={14} />
                  </span>
                  {g.name} <span style={{ opacity: 0.6, fontWeight: 500 }}>· {groupCounts[g.id]}</span>
                </button>
              ))}
            </div>

            <div className="tools-grid">
              {filtered.length === 0 ? (
                <div className="empty-state">
                  <div className="em-icon"><window.Icon name="search" size={48} strokeWidth={1.25} /></div>
                  <div style={{ fontWeight: 700, marginBottom: 4, color: 'var(--id-text)' }}>No tools found</div>
                  <div>Try a different keyword or category.</div>
                </div>
              ) : filtered.map((tool) => (
                <SportsToolCard key={tool.id} tool={tool}
                  isFav={favorites?.has(tool.id)}
                  onFav={toggleFav}
                  onClick={() => onOpenTool(tool)}
                  tier={tierOf(tool.id)}
                  locked={isToolLocked(tool.id)} />
              ))}
            </div>
          </section>

          <section className="sports-tips">
            <h2>Why athletes love MiniMagics</h2>
            <div className="sports-tips-grid">
              <div className="st-card">
                <div className="st-ico"><window.Icon name="lock" size={18} /></div>
                <div className="st-name">100% private</div>
                <div className="st-desc">Your GPX files, weight, heart rate — none of it ever leaves your device.</div>
              </div>
              <div className="st-card">
                <div className="st-ico"><window.Icon name="bolt" size={18} /></div>
                <div className="st-name">No login required</div>
                <div className="st-desc">Open a tool and use it — sign-in is only there if you want to sync favourites.</div>
              </div>
              <div className="st-card">
                <div className="st-ico"><window.Icon name="check" size={18} /></div>
                <div className="st-name">Works offline</div>
                <div className="st-desc">Once loaded, the calculators work even without a signal — pack them for race day.</div>
              </div>
              <div className="st-card">
                <div className="st-ico"><window.Icon name="run" size={18} /></div>
                <div className="st-name">Built by runners</div>
                <div className="st-desc">Formulas from Daniels, Riegel, Karvonen and Maffetone — the ones coaches actually use.</div>
              </div>
            </div>
          </section>
        </main>
      </>
    );
  }

  function SportsToolCard({ tool, isFav, onFav, onClick, tier = 'free', locked = false }) {
    const group = window.SPORT_GROUPS.find((g) => g.id === tool.group) || window.SPORT_GROUPS[0];
    const cardStyle = { '--tc-tint': group.tint, '--tc-soft': '#dcfce7' };
    const classes = ['tool-card'];
    if (tool.featured) classes.push('has-badge');
    if (locked) classes.push('tc-locked');
    return (
      <div className={classes.join(' ')} data-id={tool.id} data-tier={tier} style={cardStyle}
           onClick={onClick} role="button" tabIndex={0}
           onKeyDown={(e) => { if (e.key === 'Enter') onClick(); }}>
        {tool.featured && <span className="tc-badge"><window.Icon name="sparkle" size={10} strokeWidth={2} /> Featured</span>}
        {tier !== 'free' && (
          <span className={`tc-tier tc-tier-${tier}`}>
            {locked ? <window.Icon name="lock" size={10} strokeWidth={2.5} /> : <window.Icon name="bolt" size={10} strokeWidth={2.5} />}
            {tier.toUpperCase()}
          </span>
        )}
        <button className={`tc-fav ${isFav ? 'active' : ''}`} onClick={(e) => { e.stopPropagation(); onFav?.(tool.id); }} aria-label="Favorite">
          <window.Icon name="sparkle" size={14} strokeWidth={isFav ? 2.2 : 1.75} />
        </button>
        <div className="tc-head">
          <div className="tc-icon"><window.Icon name={tool.icon} size={20} /></div>
          <div>
            <div className="tc-name">{tool.name}</div>
            <div className="tc-cat">{group.name}</div>
          </div>
        </div>
        <div className="tc-desc">{tool.desc}</div>
        {tool.working && <span className="try-pill"><window.Icon name="check" size={10} strokeWidth={2.5} /> Live demo</span>}
      </div>
    );
  }

  window.SportsPage = SportsPage;
})();
