import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { forwardRef, useContext, useEffect, useMemo, useRef, useState } from 'react';
import styled, { css } from 'styled-components';
import { useBreakpoint, useConfiguration, useConsolidatedRef, useElement, useI18n, useScrollStick } from '../../hooks';
import { calculateForegroundColor, readableColor } from '../../styles';
import { defaultThemeProp } from '../../theme';
import { focusHeadingOrContainer, tryCatch } from '../../utils';
import AppShellContext from '../AppShell/AppShellContext';
import { StyledBanner } from '../Banner/Banner';
import Breadcrumbs, { StyledBreadcrumbs } from '../Breadcrumbs';
import Flex from '../Flex';
import Grid from '../Grid';
import Icon from '../Icon';
import SummaryItem from '../SummaryItem';
import Tabs, { TabPanel } from '../Tabs';
import { StyledTabPanel } from '../Tabs/TabPanel';
import { StyledAllTabsWrapper, StyledTabs, StylesAllTabsButtonWrapper } from '../Tabs/Tabs.styles';
import Text from '../Text';
import { StyledMenuButton } from '../MenuButton/MenuButton';
export const StyledPageIcon = styled(Flex)(({ theme }) => {
    const bgColor = theme.base.palette['brand-primary'];
    const color = tryCatch(() => readableColor(bgColor));
    return css `
    height: calc(4 * ${theme.base.spacing});
    width: calc(4 * ${theme.base.spacing});
    background: ${bgColor};
    color: ${color};
    border-radius: calc(0.5 * ${theme.base['border-radius']});
  `;
});
StyledPageIcon.defaultProps = defaultThemeProp;
export const StyledPageHeader = styled.header(({ theme }) => {
    const appBg = theme.base.palette['app-background'];
    const appFg = theme.base.palette['app-foreground'];
    const tabsDetached = theme.components.tabs.detached;
    const color = calculateForegroundColor(appBg, appFg);
    return css `
    h1 {
      color: ${color};
    }

    h1:focus-visible {
      outline: transparent;
      box-shadow: ${theme.base.shadow.focus};
    }

    ${StyledBreadcrumbs} {
      margin-block-end: ${theme.base.spacing};
    }

    ${StyledBanner}, ${StyledTabs}, ${StylesAllTabsButtonWrapper} {
      margin-block-start: calc(2 * ${theme.base.spacing});
    }

    ${tabsDetached &&
        css `
      ${StyledAllTabsWrapper} {
        margin-block-start: calc(2 * ${theme.base.spacing});
        border-radius: var(--border-radius, ${theme.base['border-radius']});
        border-end-start-radius: 0;

        ${StyledTabs} {
          border-radius: unset;
          border-start-end-radius: inherit;
          margin-block-start: 0;
        }

        ${StylesAllTabsButtonWrapper} {
          margin-block-start: 0;

          ${StyledMenuButton} {
            border-start-start-radius: var(--border-radius, ${theme.base['border-radius']});
          }
        }
      }
    `}
  `;
});
StyledPageHeader.defaultProps = defaultThemeProp;
export const StyledRegion = styled.div(({ renderSingleRegion }) => {
    if (renderSingleRegion) {
        return css `
        height: 100%;
      `;
    }
});
StyledRegion.defaultProps = defaultThemeProp;
export const StyledRegions = styled.div(({ pad, theme }) => {
    const spacing = theme.base.spacing;
    return css `
    flex-grow: 1;
    max-width: 100%;

    ${pad &&
        css `
      padding: 0 calc(2 * ${spacing}) calc(2 * ${spacing});
    `}
    [role='tabpanel'] & {
      padding: 0;
    }
  `;
});
StyledRegions.defaultProps = defaultThemeProp;
export const StyledContent = styled.div ``;
StyledContent.defaultProps = defaultThemeProp;
export const StyledScrollableTabPanel = styled(TabPanel)(() => {
    return css `
    height: 100%;
    overflow: auto;
  `;
});
StyledScrollableTabPanel.defaultProps = defaultThemeProp;
export const StyledPageLayout = styled.div(({ theme: { base: { palette: { 'app-background': appBackground } } }, scrollContent, minContentHeight }) => {
    const emptyContentHeight = minContentHeight ? `${minContentHeight}px` : undefined;
    return css `
      --content-height-in-view: ${emptyContentHeight};
      position: relative;
      min-height: inherit;
      background: ${appBackground};

      ${scrollContent &&
        css `
        ${StyledContent} {
          position: relative;
        }

        ${StyledRegions} {
          position: absolute;
          height: 100%;
          width: 100%;
          overflow: auto;
        }
      `}
    `;
});
StyledPageLayout.defaultProps = defaultThemeProp;
const StyledPageLayoutWrapper = styled.div `
  height: 100%;
`;
const StylePageTabContent = styled.div `
  ${StyledRegions} {
    padding: 0;
  }
`;
const PageLayout = forwardRef(function PageLayout({ regions, cols = `repeat(${regions.length}, minmax(0, 1fr))`, title, icon, path, actions, banners, tabs, utilities, as, header, regionsRef, scrollContent = false, padContent = true, ...restProps }, ref) {
    const t = useI18n();
    const [contentEl, setContentEl] = useElement();
    const isMediumOrAbove = useBreakpoint('md');
    const hasSideBySideColumns = regions.length > 1 && isMediumOrAbove;
    const { headerEl } = useContext(AppShellContext);
    const { loadedRef } = useConfiguration();
    const [panel, setPanel] = useState('content');
    const pageRef = useConsolidatedRef(ref);
    const pageTabsRef = useRef(null);
    const consolidatedRegionRef = useConsolidatedRef(regionsRef);
    const scrollStickOptions = useRef({
        elements: []
    });
    scrollStickOptions.current.scrollContainer = scrollContent && contentEl ? contentEl : undefined;
    scrollStickOptions.current.offset = (headerEl?.offsetHeight ?? 0) + 16;
    useScrollStick(hasSideBySideColumns ? scrollStickOptions.current : undefined);
    const renderSingleRegion = regions?.length === 1;
    const [minContentHeight, setMinContentHeight] = useState();
    useEffect(() => {
        if (!pageRef.current)
            return;
        if (loadedRef.current) {
            focusHeadingOrContainer(pageRef.current, title);
        }
        else {
            loadedRef.current = true;
        }
    }, [title]);
    useEffect(() => {
        if (consolidatedRegionRef.current) {
            const refElement = consolidatedRegionRef.current;
            const regionsPaddingBottomPixels = Number.parseInt(window.getComputedStyle(refElement).getPropertyValue('padding-bottom'), 10);
            const resizeObserver = new ResizeObserver(() => {
                const headerOffset = headerEl?.offsetHeight ?? 0;
                const emptyHeight = document.documentElement.offsetHeight -
                    (headerOffset + refElement.offsetTop) -
                    regionsPaddingBottomPixels;
                setMinContentHeight(emptyHeight);
            });
            resizeObserver.observe(refElement);
            return () => {
                resizeObserver.disconnect();
            };
        }
    }, [consolidatedRegionRef, headerEl]);
    const pageContent = (_jsxs(Flex, { container: true, item: { grow: 1 }, as: StyledContent, ref: scrollContent ? setContentEl : undefined, children: [renderSingleRegion && (_jsx(StyledRegions, { ref: consolidatedRegionRef, pad: padContent, children: _jsx(Flex, { container: {
                        direction: 'column',
                        gap: 2
                    }, as: StyledRegion, ref: (el) => {
                        if (el) {
                            scrollStickOptions.current.elements[0] = el;
                        }
                    }, renderSingleRegion: true, children: regions[0] }) })), !renderSingleRegion && (_jsx(Grid, { container: {
                    cols: 'minmax(0, 1fr)',
                    alignItems: 'start',
                    gap: 2,
                    pad: [0, 2, 2]
                }, md: { container: { cols } }, as: StyledRegions, ref: consolidatedRegionRef, children: regions.map((colItems, i) => {
                    return (_jsx(Flex, { container: {
                            direction: 'column',
                            gap: 2
                        }, as: StyledRegion, ref: (el) => {
                            if (el) {
                                scrollStickOptions.current.elements[i] = el;
                            }
                        }, children: colItems }, i));
                }) }))] }));
    const pageTabs = [
        { name: t('content'), id: 'content', content: pageContent },
        {
            name: t('chat_with_ai'),
            id: 'chat_with_ai',
            content: utilities
        }
    ];
    const pageHeader = !!path || !!icon || !!actions || !!title || !!banners || !!tabs || !!header ? (_jsxs(Flex, { container: { direction: 'column', pad: [2, 2, 0] }, item: { grow: 0, shrink: 0 }, as: StyledPageHeader, children: [path && path.length > 0 && _jsx(Breadcrumbs, { path: path }), header || (_jsx(SummaryItem, { visual: icon && (_jsx(StyledPageIcon, { container: { alignItems: 'center', justify: 'center' }, children: _jsx(Icon, { name: icon }) })), primary: _jsx(Text, { variant: 'h1', children: title }), actions: actions })), banners, tabs] })) : null;
    const handleTabChange = (id) => {
        setPanel(id);
    };
    if (utilities) {
        if (isMediumOrAbove || tabs) {
            return (_jsxs(Flex, { container: { gap: 2 }, as: StyledPageLayoutWrapper, children: [_jsxs(Flex, { ...restProps, container: {
                            direction: 'column',
                            alignItems: 'stretch',
                            gap: 2
                        }, item: { grow: 1 }, scrollContent: scrollContent, as: StyledPageLayout, forwardedAs: as, ref: pageRef, minContentHeight: minContentHeight, children: [pageHeader, pageContent] }), (isMediumOrAbove || !tabs) && _jsx("div", { children: utilities })] }));
        }
        return (_jsxs(Flex, { ...restProps, as: StyledPageLayout, forwardedAs: as, ref: pageRef, container: { direction: 'column' }, children: [pageHeader, _jsxs(Flex, { container: { direction: 'column', pad: [2, 2, 0], gap: 2 }, children: [_jsx(Tabs, { tabs: pageTabs, onTabClick: handleTabChange, currentTabId: panel, ref: pageTabsRef }), pageTabs.map(tab => (_jsx(TabPanel, { tabId: tab.id, currentTabId: panel, tablistRef: pageTabsRef, children: _jsx(StylePageTabContent, { children: tab.content }) }, tab.id)))] })] }));
    }
    return (_jsxs(Flex, { ...restProps, container: {
            direction: 'column',
            alignItems: 'stretch',
            gap: 2
        }, item: { grow: 1 }, scrollContent: scrollContent, as: StyledPageLayout, forwardedAs: as, ref: pageRef, minContentHeight: minContentHeight, children: [pageHeader, pageContent] }));
});
const StyledTabbedPage = styled(PageLayout)(({ $layout = 'standard', theme: { base: { palette: { 'border-line': borderLine } }, components: { tabs: { detached: tabsDetached } } } }) => {
    return css `
    gap: 0;

    ${tabsDetached &&
        css `
      ${StyledTabPanel} {
        border-block-end: none;
        box-shadow: 0 0.0625rem 0 ${borderLine};
      }
    `}

    ${$layout === 'full-size' &&
        css `
      ${StyledRegions} {
        padding: 0;

        ${StyledTabPanel} {
          padding-block-start: 0;
        }
      }
    `}
  `;
});
StyledTabbedPage.defaultProps = defaultThemeProp;
export const TabbedPage = forwardRef(function TabbedPage({ tabs: tabsProps, utilities, as, ...restProps }, ref) {
    const isMediumOrAbove = useBreakpoint('md');
    const t = useI18n();
    const tabs = useMemo(() => {
        if (utilities && !isMediumOrAbove) {
            return {
                ...tabsProps,
                tabs: [
                    ...tabsProps.tabs,
                    { id: 'chat_with_ai', name: t('chat_with_ai'), content: utilities }
                ]
            };
        }
        return tabsProps;
    }, [tabsProps, utilities, isMediumOrAbove]);
    const [tabId, setTabId] = useState(tabs.defaultTabId || tabs.tabs[0]?.id);
    useEffect(() => {
        const currentTabId = tabs.defaultTabId || tabs.tabs[0]?.id;
        if (currentTabId && tabId === 'agent')
            setTabId(currentTabId);
    }, [tabsProps, isMediumOrAbove]);
    const tabPanels = tabs.tabs.map(tab => {
        return (_jsx(Flex, { container: { direction: 'column', gap: 2 }, as: TabPanel, tabId: tab.id, currentTabId: tabId, children: tab.content }, tab.id));
    });
    return (_jsx(StyledTabbedPage, { ...restProps, utilities: utilities, tabs: _jsx(Tabs, { ...tabs, onTabClick: (id, e) => {
                setTabId(id);
                tabs.onTabClick?.(id, e);
            }, currentTabId: tabId }), regions: [_jsx(_Fragment, { children: tabPanels })], "$layout": tabs.tabs.find(({ id }) => id === tabId)?.layout, forwardedAs: as, ref: ref }));
});
export const DynamicLayoutPage = forwardRef(function DynamicLayoutPage({ a, ...restProps }, ref) {
    return _jsx(PageLayout, { regions: [a], ref: ref, ...restProps, padContent: false });
});
export const OneColumnPage = forwardRef(function OneColumnPage({ a, ...restProps }, ref) {
    return _jsx(PageLayout, { regions: [a], ref: ref, ...restProps, cols: 'minmax(0, 1fr)' });
});
export const TwoColumnPage = forwardRef(function TwoColumnPage({ a, b, ...restProps }, ref) {
    return (_jsx(PageLayout, { regions: [a, b], ref: ref, ...restProps, cols: 'repeat(2, minmax(0, 1fr))' }));
});
export const ThreeColumnPage = forwardRef(function ThreeColumnPage({ a, b, c, ...restProps }, ref) {
    return (_jsx(PageLayout, { regions: [a, b, c], ref: ref, ...restProps, cols: 'repeat(3, minmax(0, 1fr))' }));
});
export const FourColumnPage = forwardRef(function FourColumnPage({ a, b, c, d, ...restProps }, ref) {
    return (_jsx(PageLayout, { regions: [a, b, c, d], ref: ref, ...restProps, cols: 'repeat(4, minmax(0, 1fr))' }));
});
export const WideNarrowPage = forwardRef(function WideNarrowPage({ a, b, ...restProps }, ref) {
    return (_jsx(PageLayout, { regions: [a, b], ref: ref, ...restProps, cols: 'minmax(0, 2fr) minmax(0, 1fr)' }));
});
export const NarrowWidePage = forwardRef(function NarrowWidePage({ a, b, ...restProps }, ref) {
    return (_jsx(PageLayout, { regions: [a, b], ref: ref, ...restProps, cols: 'minmax(0, 1fr) minmax(0, 2fr)' }));
});
export const WideWideNarrowPage = forwardRef(function WideWideNarrowPage({ a, b, c, ...restProps }, ref) {
    return (_jsx(PageLayout, { regions: [a, b, c], ref: ref, ...restProps, cols: 'repeat(2, minmax(0, 2fr)) minmax(0, 1fr)' }));
});
export const NarrowWideWidePage = forwardRef(function NarrowWideWidePage({ a, b, c, ...restProps }, ref) {
    return (_jsx(PageLayout, { regions: [a, b, c], ref: ref, ...restProps, cols: 'minmax(0, 1fr) repeat(2, minmax(0, 2fr))' }));
});
export const NarrowWideNarrowPage = forwardRef(function NarrowWideNarrowPage({ a, b, c, ...restProps }, ref) {
    return (_jsx(PageLayout, { regions: [a, b, c], ref: ref, ...restProps, cols: 'minmax(0, 1fr) minmax(0, 3fr) minmax(0, 1fr)' }));
});
//# sourceMappingURL=PageTemplates.js.map