/**
 * @license MIT
 * author: Cube Dev Team
 * @cube-dev/ui-kit v0.0.0-canary-2305ece
 * Released under the MIT license.
 */

import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import copy from 'clipboard-copy';
import { useCallback, useMemo } from 'react';
import { Button } from '../../components/actions/Button/index.js';
import { Layout } from '../../components/content/Layout/index.js';
import { PrismCode } from '../../components/content/PrismCode/PrismCode.js';
import { useToast } from '../../components/overlays/Toast/index.js';
import { CopyIcon } from '../../icons/index.js';
import { tasty } from '../../tasty/index.js';
import { renderStyles } from '../../tasty/pipeline/index.js';
const OutputContent = tasty({
    styles: {
        display: 'block',
        flex: 1,
        overflow: 'auto',
        padding: '2x',
        margin: 0,
        fill: '#dark-bg',
    },
});
function formatStyleResults(results) {
    if (results.length === 0) {
        return '/* No styles generated */';
    }
    // Group rules by selector + atRules combination
    const groupedRules = new Map();
    for (const result of results) {
        const { selector, declarations, atRules } = result;
        // Create a unique key for grouping: selector + atRules
        const atRulesKey = atRules?.join('|') ?? '';
        const groupKey = `${selector}|||${atRulesKey}`;
        const declList = declarations.split(';').filter(Boolean);
        if (!groupedRules.has(groupKey)) {
            groupedRules.set(groupKey, []);
        }
        groupedRules.get(groupKey).push(...declList);
    }
    const lines = [];
    for (const [groupKey, declList] of groupedRules) {
        const [selector, atRulesKey] = groupKey.split('|||');
        const atRules = atRulesKey ? atRulesKey.split('|') : [];
        // Build the rule with merged declarations
        const rule = `${selector} {\n  ${declList.join(';\n  ')};\n}`;
        if (atRules.length > 0) {
            // Wrap in at-rules (nested)
            let wrapped = rule;
            for (let i = atRules.length - 1; i >= 0; i--) {
                const indent = '  '.repeat(atRules.length - i);
                const innerIndent = '  '.repeat(atRules.length - i + 1);
                wrapped = `${atRules[i]} {\n${wrapped
                    .split('\n')
                    .map((line) => innerIndent + line)
                    .join('\n')}\n${indent.slice(2)}}`;
            }
            lines.push(wrapped);
        }
        else {
            lines.push(rule);
        }
    }
    return lines.join('\n\n');
}
export function PlaygroundOutput({ styles }) {
    const toast = useToast();
    const cssOutput = useMemo(() => {
        if (!styles || Object.keys(styles).length === 0) {
            return '/* Enter styles in the editor to see generated CSS */';
        }
        try {
            // Use a demo selector for display purposes
            const results = renderStyles(styles, '.demo');
            return formatStyleResults(results);
        }
        catch (e) {
            return `/* Error generating CSS: ${e.message} */`;
        }
    }, [styles]);
    const handleCopy = useCallback(async () => {
        await copy(cssOutput);
        toast.success('CSS copied to clipboard');
    }, [cssOutput, toast]);
    return (_jsxs(Layout, { height: "100%", children: [_jsxs(Layout.Toolbar, { children: [_jsx("span", { children: "Generated CSS" }), _jsx(Button, { size: "small", type: "clear", icon: _jsx(CopyIcon, {}), "aria-label": "Copy CSS", onPress: handleCopy })] }), _jsx(Layout.Content, { padding: 0, children: _jsx(OutputContent, { children: _jsx(PrismCode, { code: cssOutput, language: "css" }) }) })] }));
}

        