import React from 'react';
import styled from 'styled-components';

import { breakpoints } from '@redocly/theme/core';

export type CodeWalkthroughLayoutProps = React.PropsWithChildren<{
  className?: string;
}>;

export function CodeWalkthroughLayout({
  className,
  children,
}: CodeWalkthroughLayoutProps): JSX.Element {
  return (
    <LayoutWrapper data-component-name="Layout/CodeWalkthroughLayout" className={className}>
      <ContentWrapper>{children}</ContentWrapper>
    </LayoutWrapper>
  );
}

const LayoutWrapper = styled.div.attrs(({ className }) => ({
  className,
}))`
  display: flex;
  flex: 1;
  width: 100%;
`;

const ContentWrapper = styled.section`
  width: 100%;
  --md-content-font-size: var(--font-size-lg);
  --md-content-line-height: var(--line-height-lg);
  --md-table-font-size: var(--md-content-font-size);
  --md-table-line-height: var(--md-content-line-height);
  --md-tabs-content-font-size: var(--md-content-font-size);
  --md-tabs-content-line-height: var(--md-content-line-height);

  article {
    padding: var(--spacing-xl) 0;

    /* Spacing for elements preceding a code walkthrough */
    > :not(.code-walkthrough):has(+ .code-walkthrough) {
      margin-bottom: var(--spacing-xl);
    }

    /* Spacing for code walkthroughs not at the end */
    > .code-walkthrough:not(:last-child) {
      margin-bottom: var(--spacing-xl);
    }

    /* Layout constraints for direct children except .code-walkthrough */
    > :not(.code-walkthrough) {
      max-width: var(--md-content-max-width);
      padding-left: 0;
      padding-right: 0;
      margin-left: auto !important;
      margin-right: auto !important;
    }

    /* Adjust padding for edge cases with .code-walkthrough */
    &:has(.code-walkthrough:first-child) {
      padding-top: 0;
    }

    &:has(.code-walkthrough:last-child) {
      padding-bottom: 0;
    }

    /* Full-width styling for all .code-walkthroughs */
    .code-walkthrough {
      width: 100%;
      max-width: ${breakpoints.max};
      margin-left: auto;
      margin-right: auto;
    }

    &:first-child > h1:first-child {
      // disable margin top for h1 on the title heading
      margin-top: 0;
    }
  }
`;
