import React, { useEffect } from 'react'
import Helmet from 'react-helmet'
import styled, { createGlobalStyle } from 'styled-components'

import Header from '../Header'
import Footer from '../Footer';
import useStore from '../../store';
import Will from '../../images/will.png';
import './Layout.css';

export const themes = {
  light: {
    name: '☀️ Light Theme',
    background: 'white',
    text: 'black',
    links: '#01BAEF',
    activeLinks: 'rgb(50,50,50)',
  },
  dark: {
    name: '🌒 Dark Theme',
    background: '#0f0e17',
    text: '#a7a9be',
    headers: '#fffffe',
    links: '#ff8906',
    activeLinks: 'rgb(200,200,200)',
  }
}

const GlobalStyle = createGlobalStyle`
  body{
    background-color: ${({ theme }) => theme.background};
    color: ${({ theme }) => theme.text};
    transition: background-color 0.25s, color 0.25s;
  }
  h1,h2,h3,h4 {
    color: ${({ theme }) => theme.headers};
  }
  a {
    color: ${({ theme }) => theme.links};
    &.active-link {
      color: ${({ theme }) => theme.activeLinks};
    }
  }
`;

const StyledMain = styled.div`
  margin: 0px auto;
  max-width: 960px;
  padding: 0px 1.1rem 1.45rem;
`;

const TemplateWrapper = ({ children }) => {
  const theme = useStore(s => s.theme);
  const setTheme = useStore(s => s.setTheme);
  
  useEffect(() => {
    const rememberedTheme = localStorage.getItem('theme');
    if (rememberedTheme && themes[rememberedTheme]) {
      setTheme(rememberedTheme);
    } else {
      const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
      if (isDarkMode) setTheme('dark');
    }
  }, [setTheme]);
  
  return (
    <div>
      <GlobalStyle theme={themes[theme]} />
      <Helmet titleTemplate="%s | Will Webberley" defaultTitle="Will Webberley">
        <link rel="icon" type="image/png" href={Will} />
      </Helmet>
      <Header />
      <StyledMain>{children}</StyledMain>
      <Footer />
    </div>
  );
}

export default TemplateWrapper
