import { __ } from '@wordpress/i18n';
import Prompt from './prompt.js';

const PromptsHistory = (props) => {
    const storageKey = 'editorImprovePromptsHistory';
    let lastPrompts = localStorage.getItem(storageKey);
    lastPrompts = null === lastPrompts ? {} : JSON.parse(lastPrompts);

    if (Array.isArray(lastPrompts)) { // migrate old format (array) to new one (object)
        const promptsArr = lastPrompts;
        lastPrompts = {
            all: promptsArr
        };
        localStorage.setItem(storageKey, JSON.stringify(lastPrompts));
    }

    const multisiteDomain = new URL(document.location).pathname.split('/')[1];
    const isMultisite = "wp-admin" != multisiteDomain;
    const key = isMultisite ? multisiteDomain : 'all';
    let domainLastPrompts = "undefined" !== typeof lastPrompts[key] ? lastPrompts[key] : [];

    return (
        0 !== domainLastPrompts.length
        && <div className="seoaic-prompts-history-section">
            <div className="seoaic-prompts-title">{ __("Last Used Prompts:", "seoaic") }</div>
            <div className="seoaic-prompts-history">
            { domainLastPrompts.map((prompt, index) => {
                return (
                    <Prompt
                        value={ prompt }
                        onClick={ () => {
                            props.setPromptField(prompt);
                        } }
                    />
                );
            }) }
            </div>
        </div>
    );
};

export default PromptsHistory;