// Writing index — /writing
// Filterable by tag, and by project through ?project= (the links from project pages).

function WritingPage({ route }) {
  const [tag, setTag] = React.useState('');
  const projectId = route.query.project || '';

  const filtered = POSTS.filter((p) =>
    (!projectId || p.project === projectId) && (!tag || p.tags.includes(tag)));

  // All tags across posts, most used first.
  const tagFreq = {};
  POSTS.forEach((p) => p.tags.forEach((t) => { tagFreq[t] = (tagFreq[t] || 0) + 1; }));
  const tags = Object.entries(tagFreq).sort((a, b) => b[1] - a[1]).map(([t]) => t);

  const filterProj = projectId ? projectById(projectId) : null;

  return (
    <div className="page" data-page="writing">
      <h1 className="page-title">{filterProj ? filterProj.name : 'Writing'}</h1>
      <p className="lede">
        {filterProj
          ? <>Posts that came out of this project. <a className="link-accent" href={`/experience/${filterProj.id}/`}>Open the project</a> or <a className="link-accent" href="/writing/">see all posts</a>.</>
          : <>Notes from things I’ve worked on, from GSoC in 2020 to flight hardware at ISRO.</>}
      </p>

      <div className="filters" role="group" aria-label="Filter by tag">
        <button className={'filter' + (tag === '' ? ' on' : '')} onClick={() => setTag('')}>All</button>
        {tags.map((t) => (
          <button key={t} className={'filter' + (tag === t ? ' on' : '')} onClick={() => setTag(t)}>
            {t}<span className="n">{tagFreq[t]}</span>
          </button>
        ))}
      </div>

      <div className="post-list">
        {filtered.length === 0 && (
          <p className="empty">No posts match. <button className="filter" onClick={() => setTag('')}>Show all</button></p>
        )}
        {filtered.map((p) => <WritingEntry key={p.id} p={p} />)}
      </div>
    </div>
  );
}

function WritingEntry({ p }) {
  const proj = projectById(p.project);
  return (
    <article className="post-item">
      <div className="post-meta">
        {p.date} · {p.minutes} min read
        {proj && <> · <a href={`/experience/${proj.id}/`}>{proj.name}</a></>}
      </div>
      <h2><a className="plain-link" href={`/writing/${p.id}/`}>{p.title}</a></h2>
      <p>{p.excerpt}</p>
    </article>
  );
}

Object.assign(window, { WritingPage });
