import { useState, useEffect } from 'react';
import { PanelBody } from '@wordpress/components';

const SidebarSection = (props) => {
    const [opened, setOpened] = useState(true);

    const storageName = "seoaic_sidebar";
    const saveState = (id, showState) => {
        let storage = localStorage.getItem(storageName);
        if (!storage) {
            storage = {};
        } else {
            storage = JSON.parse(storage);
        }
        storage[id] = showState;

        localStorage.setItem(storageName, JSON.stringify(storage));
    };

    const loadState = (id) => {
        let storage = localStorage.getItem(storageName);
        storage = JSON.parse(storage);
        if (
            storage
            && "undefined" !== typeof storage[id]
            && 0 == storage[id]
        ) {
            setOpened(false);
        }
    };

    const onToggle = (showState) => {
        saveState(props.id, showState);
    };

    useEffect(() => {
        loadState(props.id);
    });

    return (
        <PanelBody
            title={ props.title }
            className={ props.className ? 'seoaic-sidebar ' + props.className : 'seoaic-sidebar' }
            initialOpen={ opened }
            onToggle={ onToggle }
        >
            <div className="seoaic-sc seoaic-sidebar-section">
                { props.children }
            </div>
        </PanelBody>
    );
};

export default SidebarSection;