import { useEffect, useState } from 'react';
import { CopyStatus } from '../enums';
export const useLogic = ({ jsonData }) => {
    const [data, setData] = useState(null);
    const [expandedKeys, setExpandedKeys] = useState(new Set());
    const [copyStatus, setCopyStatus] = useState(CopyStatus.CanCopy);
    const collapseAll = () => {
        setExpandedKeys(new Set());
    };
    const checkExpanded = (key) => {
        return expandedKeys.has(key);
    };
    const expandAll = () => {
        const newExpandedKeys = new Set();
        const collectKeys = (obj, prefix = '') => {
            if (typeof obj === 'object' && obj !== null) {
                if (Array.isArray(obj)) {
                    obj.forEach((item, index) => {
                        const fullKey = prefix ? `${prefix}.${index}` : String(index);
                        newExpandedKeys.add(fullKey);
                        collectKeys(item, fullKey);
                    });
                }
                else {
                    Object.keys(obj).forEach((key) => {
                        const fullKey = prefix ? `${prefix}.${key}` : key;
                        newExpandedKeys.add(fullKey);
                        collectKeys(obj[key], fullKey);
                    });
                }
            }
        };
        collectKeys(data);
        setExpandedKeys(newExpandedKeys);
    };
    const copyAll = () => {
        navigator.clipboard
            .writeText(JSON.stringify(data))
            .then(() => {
            setCopyStatus(CopyStatus.Copied);
        })
            .catch(() => {
            setCopyStatus(CopyStatus.Error);
        });
        setTimeout(() => {
            setCopyStatus(CopyStatus.CanCopy);
        }, 2000);
    };
    const toggleExpanded = (key) => {
        const newExpandedKeys = new Set(expandedKeys);
        if (newExpandedKeys.has(key)) {
            newExpandedKeys.delete(key);
        }
        else {
            newExpandedKeys.add(key);
        }
        setExpandedKeys(newExpandedKeys);
    };
    useEffect(() => {
        try {
            setData(typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData);
        }
        catch (error) {
            throw new Error(`Error parsing JSON data: ${error}`);
        }
    }, [jsonData]);
    return {
        data,
        copyStatus,
        collapseAll,
        expandAll,
        copyAll,
        toggleExpanded,
        checkExpanded,
    };
};
