// Research page: 4 themes deep, tag filtering, cross-links to team

function ResearchHero() {
  return (
    <section className="research-hero">
      <div className="upper-mono" style={{ marginBottom: 16 }}>§ Research index</div>
      <h1>
        How we work, by <em style={{ fontStyle: 'italic', color: 'var(--moss-600)' }}>theme</em>.
      </h1>
      <p>
        Four lines of research that share methods and people. Filter by tag below
        to find connected work, or click a project to jump to its team lead.
      </p>
    </section>
  );
}

function TagBar({ allTags, activeTags, toggle, clear }) {
  return (
    <div className="tag-bar" style={{ padding: '16px var(--pad-x)' }}>
      <div style={{ maxWidth: 'var(--max-w)', margin: '0 auto', display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center', width: '100%' }}>
        <span className="tag-bar__label">Filter</span>
        {allTags.map(t => (
          <button key={t} type="button"
                  className={`tag ${activeTags.includes(t) ? 'tag--active' : ''}`}
                  onClick={() => toggle(t)}>
            {t}
          </button>
        ))}
        {activeTags.length > 0 && (
          <button className="tag-bar__clear" onClick={clear}>Clear ✕</button>
        )}
      </div>
    </div>
  );
}

function ProjectCard({ p }) {
  const t = window.LAB.THEMES[p.themes[0]];
  const lead = p.lead ? window.LAB.PEOPLE[p.lead] : null;
  return (
    <article className="proj-card">
      <div className="proj-card__fig" style={{
        background: t.soft,
        color: t.color,
        backgroundImage: `repeating-linear-gradient(135deg, ${t.soft} 0, ${t.soft} 11px, ${t.color}22 11px, ${t.color}22 12px)`
      }}>
        {p.figure}
      </div>
      <div className="proj-card__body">
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
          <ThemeBadge theme={p.themes[0]} />
          {p.methods.slice(0,2).map(m => (
            <span key={m} className="tag" style={{ fontSize: 10 }}>{m}</span>
          ))}
        </div>
        <h3 className="serif" style={{ fontSize: 22, margin: '8px 0' }}>{p.title}</h3>
        <p style={{ color: 'var(--ink-soft)', fontSize: 14, marginBottom: 12 }}>{p.blurb}</p>
        <div className="proj-card__meta upper-mono">
          {lead ? <a href={`team.html#${lead.id}`} style={{textDecoration:'underline', textUnderlineOffset:3}}>Lead · {lead.name}</a> : <span>Collaborative</span>}
          <span>{p.venue}</span>
        </div>
      </div>
    </article>
  );
}

function ThemeSection({ theme, projects, hl }) {
  return (
    <section className={`theme-section ${hl ? 'theme-section--hl' : ''}`} id={theme.id}>
      <div className="theme-section__inner">
        <div className="theme-section__head">
          <div className="theme-section__num" style={{ color: theme.color }}>
            ◆ {theme.num} / {theme.short}
          </div>
          <div>
            <h2 className="theme-section__title">{theme.title}</h2>
            <p style={{ color: 'var(--ink-soft)', fontSize: 17, maxWidth: '60ch' }}>{theme.blurb}</p>
            <div className="theme-section__topics">
              {theme.topics.map(top => <span key={top} className="tag tag--keyword">{top}</span>)}
            </div>
          </div>
        </div>
        <div className="theme-projects">
          {projects.length === 0 ? (
            <div style={{ padding: 32, color: 'var(--ink-soft)', fontStyle: 'italic', gridColumn: '1 / -1' }}>
              No projects match the current filter.
            </div>
          ) : projects.map(p => <ProjectCard key={p.id} p={p} />)}
        </div>
      </div>
    </section>
  );
}

function ResearchApp() {
  const [activeTags, setActiveTags] = React.useState([]);

  React.useEffect(() => {
    const hash = window.location.hash.slice(1);
    if (!hash) return;
    const id = setTimeout(() => {
      const el = document.getElementById(hash);
      if (el) {
        const top = el.getBoundingClientRect().top + window.pageYOffset;
        window.scrollTo({ top, behavior: 'smooth' });
      }
    }, 50);
    return () => clearTimeout(id);
  }, []);

  const allTags = React.useMemo(() => {
    const counts = new Map();
    window.LAB.PROJECTS.forEach(p => p.methods.forEach(m => counts.set(m, (counts.get(m) || 0) + 1)));
    return [...counts.keys()].sort((a, b) => {
      if (a === 'GWAS') return -1;
      if (b === 'GWAS') return 1;
      const d = counts.get(b) - counts.get(a);
      return d !== 0 ? d : a.localeCompare(b);
    });
  }, []);

  const toggle = (t) => setActiveTags(a => a.includes(t) ? a.filter(x => x !== t) : [...a, t]);
  const clear = () => setActiveTags([]);

  const filtered = window.LAB.PROJECTS.filter(p =>
    activeTags.length === 0 || p.methods.some(m => activeTags.includes(m))
  );

  return (
    <>
      <SiteHeader active="research" />
      <ResearchHero />
      <TagBar allTags={allTags} activeTags={activeTags} toggle={toggle} clear={clear} />
      {Object.values(window.LAB.THEMES).map((t, i) => (
        <ThemeSection
          key={t.id}
          theme={t}
          hl={i % 2 === 1}
          projects={filtered.filter(p => p.themes.includes(t.id))}
        />
      ))}
      <SiteFooter />
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<ResearchApp />);
