// Post page — /writing/[id]

marked.use(markedTypography);

const MD_CACHE = {};
const RELATED_POSTS = 3;

function PostBody({ post }) {
  const [state, setState] = React.useState(
    MD_CACHE[post.body] ? { status: 'done', html: MD_CACHE[post.body] } : { status: 'loading', html: null });

  React.useEffect(() => {
    if (MD_CACHE[post.body]) { setState({ status: 'done', html: MD_CACHE[post.body] }); return; }
    setState({ status: 'loading', html: null });

    fetch(`/portfolio/posts/${post.body}.md`)
      .then((r) => { if (!r.ok) throw r.status; return r.text(); })
      .then((raw) => {
        const md = raw
          .replace(/^---[\s\S]*?---\n/, '')
          .replace(/\{\{site\.baseurl\}\}/g, '')
          .replace(/\{:\s[^}]*\}/g, '');
        const html = marked.parse(md);
        MD_CACHE[post.body] = html;
        setState({ status: 'done', html });
      })
      .catch(() => setState({ status: 'error', html: null }));
  }, [post.body]);

  if (state.status === 'loading') return <p className="empty">Loading…</p>;
  if (state.status === 'error') return <p className="empty">This post didn&rsquo;t load. Try reloading the page.</p>;
  return <div dangerouslySetInnerHTML={{ __html: state.html }} />;
}

function PostPage({ route }) {
  const p = postById(route.segments[1]);

  if (!p) {
    return (
      <div className="page notfound">
        <h1 className="page-title">No post at this address.</h1>
        <p className="lede"><a className="link-accent" href="/writing/">See all writing</a></p>
      </div>
    );
  }

  const proj = projectById(p.project);

  return (
    <div data-page="post">
      <article className="article">
        <h1 className="article-title">{p.title}</h1>
        <p className="article-meta">
          Published <time dateTime={p.date}>{p.date}</time>
          {p.updated && <> · Updated <time dateTime={p.updated}>{p.updated}</time></>}
          {' '}· {p.minutes} min read
          {proj && <> · <a href={`/experience/${proj.id}/`}>{proj.name}</a></>}
        </p>
        <div className="prose">
          <PostBody post={p} />
        </div>

        <RelatedPosts post={p} />
      </article>
    </div>
  );
}

// Posts from the same project first, then ones sharing the most tags.
function RelatedPosts({ post }) {
  const scored = POSTS.filter((p) => p.id !== post.id).map((p) => {
    let s = 0;
    if (post.project && p.project === post.project) s += 3;
    s += p.tags.filter((t) => post.tags.includes(t)).length;
    return { p, s };
  }).filter((x) => x.s > 0).sort((a, b) => b.s - a.s).slice(0, RELATED_POSTS);

  if (scored.length === 0) return null;

  return (
    <section className="section">
      <h2 className="section-title">More writing</h2>
      <ul className="dated">
        {scored.map(({ p }) => (
          <li key={p.id}>
            <span className="date">{p.date}</span>
            <a className="plain-link" href={`/writing/${p.id}/`}>{p.title}</a>
          </li>
        ))}
      </ul>
    </section>
  );
}

Object.assign(window, { PostPage });
