"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSectionHeight = exports.Section = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const style_1 = __importDefault(require("styled-jsx/style"));
const sdk_1 = require("@cntrl-site/sdk");
const useCntrlContext_1 = require("../provider/useCntrlContext");
const useSectionRegistry_1 = require("../utils/ArticleRectManager/useSectionRegistry");
const color_1 = require("@cntrl-site/color");
const DEFAULT_COLOR = 'rgba(0, 0, 0, 0)';
const Section = ({ section, data, children }) => {
    const id = (0, react_1.useId)();
    const sectionRef = (0, react_1.useRef)(null);
    const { layouts, customSections } = (0, useCntrlContext_1.useCntrlContext)();
    const layoutValues = [section.height, section.color];
    const SectionComponent = section.name ? customSections.getComponent(section.name) : undefined;
    (0, useSectionRegistry_1.useSectionRegistry)(section.id, sectionRef.current);
    const getSectionVisibilityStyles = () => {
        return layouts
            .sort((a, b) => a.startsWith - b.startsWith)
            .reduce((acc, layout) => {
            const isHidden = section.hidden[layout.id];
            return `
          ${acc}
          ${(0, sdk_1.getLayoutMediaQuery)(layout.id, layouts)} {
            .section-${section.id} {
              display: ${isHidden ? 'none' : 'block'};
            }
          }`;
        }, '');
    };
    if (SectionComponent)
        return (0, jsx_runtime_1.jsx)("div", { ref: sectionRef, children: (0, jsx_runtime_1.jsx)(SectionComponent, { data: data, children: children }) });
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("div", { className: `section-${section.id}`, id: section.name, ref: sectionRef, children: children }), (0, jsx_runtime_1.jsx)(style_1.default, { id: id, children: `
      ${(0, sdk_1.getLayoutStyles)(layouts, layoutValues, ([height, color]) => (`
         .section-${section.id} {
            height: ${getSectionHeight(height)};
            position: relative;
            background-color: ${color_1.CntrlColor.parse(color !== null && color !== void 0 ? color : DEFAULT_COLOR).fmt('rgba')};
         }`))}
      ${getSectionVisibilityStyles()}
    ` })] }));
};
exports.Section = Section;
function getSectionHeight(heightData) {
    const { units, vhUnits, mode } = heightData;
    if (mode === sdk_1.SectionHeightMode.ViewportHeightUnits)
        return `${vhUnits}vh`;
    if (mode === sdk_1.SectionHeightMode.ControlUnits)
        return `${units * 100}vw`;
    return '0';
}
exports.getSectionHeight = getSectionHeight;
