/**
 * Demonstrates a client component loading once from a custom
 * express route, then not re-loading the page upon subsequent
 * route changes.
 *
 * See:
 *
 *    https://spectrum.chat/thread/78340a39-6562-41bd-8b48-bf763578a416
 *    https://github.com/zeit/next.js/issues/2833#issuecomment-414919347
 *
 * With <Link>
 *    href === the nextjs page route
 *    as   === the browser URL.
 *
 */
// import Router from 'next/router'
import Link from 'next/link';
import { React, css, log } from '../common';

import { NextDocumentContext } from 'next/document';

export interface IPageProps {
  id: string;
  path: string;
  q: string;
}

export default class Page extends React.PureComponent<IPageProps> {
  public static getInitialProps(ctx: NextDocumentContext) {
    const { asPath: path, query } = ctx;
    log.group('getInitialProps');
    log.info('ctx.asPath', ctx.asPath);
    log.info('query', query);
    log.groupEnd();

    return { path, id: query.id, q: query.q };
  }

  public componentDidMount() {
    log.info('Mounted:', this.props);
  }

  public render() {
    log.info('Render:', this.props);
    const styles = {
      base: css({}),
      hr: css({ MarginY: 30 }),
    };
    return (
      <div {...styles.base}>
        <h1>range.tsx</h1>
        <ul>
          <li>
            props:
            <ul>
              <li>
                path: <code>{this.props.path}</code>
              </li>
              <li>
                id: <code>{this.props.id}</code>
              </li>
              <li>
                q: <code>{this.props.q}</code>
              </li>
            </ul>
          </li>
        </ul>
        <hr {...styles.hr} />
        <ul>
          <LinkItem href={'/range?id=foo&q=123'} as={'/range/foo?q=123'} />
          <LinkItem href={'/range?id=bar'} as={'/range/bar'} />
          <LinkItem href={'/range?id=baz&q=456'} as={'/range/baz?q=456'} />
        </ul>
        <hr {...styles.hr} />
        <a href={'/'}>Home</a>
      </div>
    );
  }
}

const LinkItem = (props: { href: string; as?: string; q?: string }) => {
  const href = props.href;
  const asRef = props.as || href;
  return (
    <li>
      <Link href={href} as={asRef}>
        <a>
          Link:{' '}
          <code>
            href="
            {href}
            ", as="
            {asRef}"
          </code>
        </a>
      </Link>
    </li>
  );
};
