'use client';
import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
import { getTranslation } from '@payloadcms/translations';
import { getFieldPaths, toKebabCase } from 'payload/shared';
import React, { useCallback, useEffect, useState } from 'react';
import { useCollapsible } from '../../elements/Collapsible/provider.js';
import { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js';
import { useFormFields } from '../../forms/Form/index.js';
import { RenderFields } from '../../forms/RenderFields/index.js';
import { useField } from '../../forms/useField/index.js';
import { withCondition } from '../../forms/withCondition/index.js';
import { useDocumentInfo } from '../../providers/DocumentInfo/index.js';
import { usePreferences } from '../../providers/Preferences/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { FieldDescription } from '../FieldDescription/index.js';
import { fieldBaseClass } from '../shared/index.js';
import { TabsProvider } from './provider.js';
import { TabComponent } from './Tab/index.js';
import './index.scss';
const baseClass = 'tabs-field';
export { TabsProvider };
const TabsFieldComponent = (props)=>{
    const { field: { admin: { className } = {}, tabs = [] }, forceRender = false, indexPath = '', parentPath = '', parentSchemaPath = '', path = '', permissions, readOnly, schemaPath = '' } = props;
    const { getPreference, setPreference } = usePreferences();
    const { preferencesKey } = useDocumentInfo();
    const { i18n } = useTranslation();
    const { isWithinCollapsible } = useCollapsible();
    const tabStates = useFormFields(([fields])=>{
        return tabs.map((tab, index)=>{
            const id = tab?.id;
            return {
                index,
                passesCondition: fields?.[id]?.passesCondition ?? true,
                tab
            };
        });
    });
    const [activeTabIndex, setActiveTabIndex] = useState(()=>tabStates.filter(({ passesCondition })=>passesCondition)?.[0]?.index ?? 0);
    const tabsPrefKey = `tabs-${indexPath}`;
    const activeTabInfo = tabStates[activeTabIndex];
    const activeTabConfig = activeTabInfo?.tab;
    const activeTabDescription = activeTabConfig?.admin?.description ?? activeTabConfig?.description;
    const activeTabStaticDescription = typeof activeTabDescription === 'function' ? activeTabDescription({
        i18n,
        t: i18n.t
    }) : activeTabDescription;
    const hasVisibleTabs = tabStates.some(({ passesCondition })=>passesCondition);
    const handleTabChange = useCallback(async (incomingTabIndex)=>{
        setActiveTabIndex(incomingTabIndex);
        const existingPreferences = await getPreference(preferencesKey);
        if (preferencesKey) {
            void setPreference(preferencesKey, {
                ...existingPreferences,
                ...path ? {
                    fields: {
                        ...existingPreferences?.fields || {},
                        [path]: {
                            ...existingPreferences?.fields?.[path],
                            tabIndex: incomingTabIndex
                        }
                    }
                } : {
                    fields: {
                        ...existingPreferences?.fields,
                        [tabsPrefKey]: {
                            ...existingPreferences?.fields?.[tabsPrefKey],
                            tabIndex: incomingTabIndex
                        }
                    }
                }
            });
        }
    }, [
        getPreference,
        preferencesKey,
        setPreference,
        path,
        tabsPrefKey
    ]);
    useEffect(()=>{
        if (preferencesKey) {
            const getInitialPref = async ()=>{
                const existingPreferences = await getPreference(preferencesKey);
                const initialIndex = path ? existingPreferences?.fields?.[path]?.tabIndex : existingPreferences?.fields?.[tabsPrefKey]?.tabIndex;
                const newIndex = typeof initialIndex === 'number' && initialIndex < tabStates.length ? initialIndex : 0;
                setActiveTabIndex(newIndex);
            };
            void getInitialPref();
        }
    }, [
        path,
        getPreference,
        preferencesKey,
        tabsPrefKey,
        tabs,
        parentPath,
        parentSchemaPath
    ]);
    useEffect(()=>{
        if (activeTabInfo?.passesCondition === false) {
            const nextTab = tabStates.find(({ passesCondition })=>passesCondition);
            if (nextTab) {
                void handleTabChange(nextTab.index);
            }
        }
    }, [
        activeTabInfo,
        tabStates,
        handleTabChange
    ]);
    return /*#__PURE__*/ _jsxDEV("div", {
        className: [
            fieldBaseClass,
            className,
            baseClass,
            isWithinCollapsible && `${baseClass}--within-collapsible`,
            !hasVisibleTabs && `${baseClass}--hidden`
        ].filter(Boolean).join(' '),
        children: /*#__PURE__*/ _jsxDEV(TabsProvider, {
            children: [
                /*#__PURE__*/ _jsxDEV("div", {
                    className: `${baseClass}__tabs-wrap`,
                    children: /*#__PURE__*/ _jsxDEV("div", {
                        className: `${baseClass}__tabs`,
                        children: tabStates.map(({ index, passesCondition, tab })=>/*#__PURE__*/ _jsxDEV(TabComponent, {
                                hidden: !passesCondition,
                                isActive: activeTabIndex === index,
                                parentPath: path,
                                setIsActive: ()=>{
                                    void handleTabChange(index);
                                },
                                tab: tab
                            }, index, false, {
                                fileName: "src/fields/Tabs/index.tsx",
                                lineNumber: 155,
                                columnNumber: 15
                            }, this))
                    }, void 0, false, {
                        fileName: "src/fields/Tabs/index.tsx",
                        lineNumber: 153,
                        columnNumber: 11
                    }, this)
                }, void 0, false, {
                    fileName: "src/fields/Tabs/index.tsx",
                    lineNumber: 152,
                    columnNumber: 9
                }, this),
                /*#__PURE__*/ _jsxDEV("div", {
                    className: `${baseClass}__content-wrap`,
                    children: activeTabConfig && /*#__PURE__*/ _jsxDEV(TabContent, {
                        description: activeTabStaticDescription,
                        field: activeTabConfig,
                        forceRender: forceRender,
                        hidden: false,
                        parentIndexPath: indexPath,
                        parentPath: path,
                        parentSchemaPath: schemaPath,
                        path: path,
                        permissions: permissions && typeof permissions === 'object' && 'name' in activeTabConfig ? permissions[activeTabConfig.name] && typeof permissions[activeTabConfig.name] === 'object' && 'fields' in permissions[activeTabConfig.name] ? permissions[activeTabConfig.name].fields : permissions[activeTabConfig.name] : permissions,
                        readOnly: readOnly,
                        tabIndex: activeTabIndex
                    }, void 0, false, {
                        fileName: "src/fields/Tabs/index.tsx",
                        lineNumber: 170,
                        columnNumber: 13
                    }, this)
                }, void 0, false, {
                    fileName: "src/fields/Tabs/index.tsx",
                    lineNumber: 168,
                    columnNumber: 9
                }, this)
            ]
        }, void 0, true, {
            fileName: "src/fields/Tabs/index.tsx",
            lineNumber: 151,
            columnNumber: 7
        }, this)
    }, void 0, false, {
        fileName: "src/fields/Tabs/index.tsx",
        lineNumber: 140,
        columnNumber: 5
    }, this);
};
export const TabsField = withCondition(TabsFieldComponent);
function TabContent({ description, field, forceRender, hidden, label, parentIndexPath, parentPath, parentSchemaPath, permissions, readOnly, tabIndex }) {
    const { i18n } = useTranslation();
    const { customComponents: { AfterInput, BeforeInput, Description, Field } = {} } = useField();
    if (Field) {
        return Field;
    }
    const { indexPath, path, schemaPath } = getFieldPaths({
        field,
        index: tabIndex,
        parentIndexPath,
        parentPath,
        parentSchemaPath
    });
    return /*#__PURE__*/ _jsxDEV("div", {
        className: [
            hidden && `${baseClass}__tab--hidden`,
            `${baseClass}__tab`,
            label && `${baseClass}__tabConfigLabel-${toKebabCase(getTranslation(label, i18n))}`
        ].filter(Boolean).join(' '),
        children: [
            /*#__PURE__*/ _jsxDEV(RenderCustomComponent, {
                CustomComponent: Description,
                Fallback: /*#__PURE__*/ _jsxDEV(FieldDescription, {
                    description: description,
                    marginPlacement: "bottom",
                    path: parentPath
                }, void 0, false, {
                    fileName: "src/fields/Tabs/index.tsx",
                    lineNumber: 256,
                    columnNumber: 11
                }, void 0)
            }, void 0, false, {
                fileName: "src/fields/Tabs/index.tsx",
                lineNumber: 253,
                columnNumber: 7
            }, this),
            BeforeInput,
            /*#__PURE__*/ _jsxDEV(RenderFields, {
                fields: field.fields,
                forceRender: forceRender,
                parentIndexPath: indexPath,
                parentPath: path,
                parentSchemaPath: schemaPath,
                permissions: permissions,
                readOnly: readOnly
            }, void 0, false, {
                fileName: "src/fields/Tabs/index.tsx",
                lineNumber: 260,
                columnNumber: 7
            }, this),
            AfterInput
        ]
    }, void 0, true, {
        fileName: "src/fields/Tabs/index.tsx",
        lineNumber: 244,
        columnNumber: 5
    }, this);
}

//# sourceMappingURL=index.js.map