import React from "react";
import { graphql } from "gatsby";
import Page from "../templates/page";

export default function Archive({ data }) {
	const siteMetadata = data.site.siteMetadata;
	const yearGroups = data.allMarkdownRemark.yearGroup;

	const yearGroupsHtml = yearGroups.map(yg => {
		const postListItems = yg.edges.map(({node}) => {
			return (
				<li>
					<a href={node.fields.slug}>{node.frontmatter.title}</a>
				</li>
			);
		});
		return (
			<div>
				<h2>{yg.year}</h2>
				<ul>
					{postListItems}
				</ul>
			</div>
		);
	});

	return (
		<Page headerInfo={siteMetadata} pageTitle="Posts Archive">
			<p>Browse all posts by month and year.</p>
			{yearGroupsHtml}
		</Page>
	);
}

export const query = graphql`
  query {
	allMarkdownRemark {
		yearGroup: group(field: fields___year) {
			year: fieldValue
			edges {
				node {
					fields {
						slug
					}
					frontmatter {
						title
					}
				}
			}
		}
	}	
    site {
		...HeaderInfo
    }
  }
`