<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\ViewModel;

use WriteTextAI\WriteTextAI\Model\SettingManager;
use WriteTextAI\WriteTextAI\Helper\Data;
use WriteTextAI\WriteTextAI\ViewModel\Settings;

class Tooltip extends TooltipCategory
{
    public const FAQ_URL = 'https://writetext.ai/frequently-asked-questions#credit-cost';

    public const KEYWORDS_GUIDE_URL = 'https://writetext.ai/guide-mastering-keyword-optimization';

    /**
     * @var SettingManager
     */
    protected $settingManager;

    /**
     * @var Data
     */
    protected $helper;

    /**
     * @var Settings
     */
    protected $settings;

    /**
     * Constructor
     *
     * @param SettingManager $settingManager
     * @param Data $helper
     * @param Settings $settings
     */
    public function __construct(
        SettingManager $settingManager,
        Data $helper,
        Settings $settings
    ) {
        $this->settingManager = $settingManager;
        $this->helper = $helper;
        $this->settings = $settings;
        parent::__construct($settingManager, $helper, $settings);
    }

    /**
     * Get rules
     *
     * @return array
     */
    public function getRules()
    {
        return $this->settings->getSettings('rules');
    }

    /**
     * Get tooltip
     *
     * @param string $block
     * @param string $entityType
     *
     * @return string
     */
    public function getTooltip($block, $entityType = null)
    {
        $tooltip = '';
        switch ($block) {
            case 'wtai.reviewed':
                $tooltip = $this->getReviewedTooltip();
                break;
            case 'wtai.keywords':
                $tooltip = $this->getKeywordsTooltip();
                break;
            case 'wtai.attributes':
                if ($entityType === 'Category') {
                    $tooltip = $this->getRepresentativesTooltip();
                } else {
                    $tooltip = $this->getAttributesTooltip();
                }
                break;
            case 'wtai.tones.and.styles':
                $tooltip = $this->getTonesAndStylesTooltip();
                break;
            case 'wtai.audience':
                $tooltip = $this->getAudienceTooltip();
                break;
            case 'wtai.page.title':
                $tooltip = $this->getPageTitleTooltip();
                break;
            case 'wtai.product.description':
                $tooltip = $this->getProductDescriptionTooltip();
                break;
            case 'wtai.short.description':
                $tooltip = $this->getShortDescriptionTooltip();
                break;
            case 'wtai.open.graph':
                $tooltip = $this->getOpenGraphTooltip();
                break;
            case 'wtai.page.description':
                $tooltip = $this->getPageDescriptionTooltip();
                break;
            case 'wtai.generate.rewrite':
                $tooltip = $this->getGenerateRewriteTooltip();
                break;
            case 'wtai.transfer':
                $tooltip = $this->getTransferTooltip();
                break;
            case 'wtai.preview.changes':
                $tooltip = $this->getPreviewChangesTooltip();
                break;
            case 'wtai.alt.text':
                $tooltip = $this->getAltTextTooltip();
                break;
            case 'wtai.special.instructions':
                $tooltip = $this->getSpecialInstructionsTooltip();
                break;
            case 'wtai.trigger.action.none.selected':
                $tooltip = $this->getTriggerActionNoneSelectedTooltip();
                break;
            case 'wtai.intent':
                $tooltip = $this->getIntentTooltip();
                break;
            case 'wtai.pipeline.locked':
                $tooltip = $this->getPipelineLockedTooltip();
                break;
            case 'wtai.pipeline.unlocked':
                $tooltip = $this->getPipelineUnlockedTooltip();
                break;
            case 'wtai.add.keywords':
                $tooltip = $this->getAddKeywordsTooltip();
                break;
            case 'wtai.currently.optimizing.keywords':
                $tooltip = $this->getCurrentlyOptimizingKeywordsTooltip();
                break;
            case 'wtai.ai.model':
                $tooltip = $this->getAiModelTooltip();
                break;
            case 'wtai.no.ai.model':
                $tooltip = $this->getNoAiModelAssignedTooltip();
                break;
            case 'wtai.additional.prompt':
                $tooltip = $this->getAdditionalPromptTooltip();
                break;
        }

        if ($tooltip === '') {
            $tooltip = $this->getTooltipCategory($block);
        }

        return $tooltip;
    }

    /**
     * Get add keywords tooltip
     *
     * @return string
     */
    public function getAddKeywordsTooltip()
    {
        return sprintf('<p>%s</p>', __('(Optional) In the Starter plan, you can manually'
                . ' add target keywords to guide content generation.'))
            . sprintf('<p>%s</p>', __('In the Pro plan, this field is used to enter optional seed keywords that'
                . ' help kickstart AI-powered keyword analysis. These keywords serve as starting'
                . ' points for identifying high-potential terms, but may not always be included in the final pipeline.'
                . ' If you don’t enter any, WriteText.ai will automatically generate'
                . ' seed keywords based on your product name,'
                . ' online research, and image analysis. Pro users can also create custom pipelines after'
                . ' analysis to directly target specific keywords they want to optimize for.'));
    }

    /**
     * Get special instructions tooltip
     *
     * @return string
     */
    public function getSpecialInstructionsTooltip()
    {
        return __('Enter other details or instructions that you would like WriteText.ai'
            . ' to consider in generating text for the products you selected'
            . ' (e.g., add information on discounts, special sales, etc).'
            . ' This will not replace any details you may have added in the “Other product details”'
            . ' section in the individual product pages.'
            . ' Special instructions will be cleared at the end of a user session.');
    }

    /**
     * Get intent tooltip
     *
     * @return string
     */
    public function getIntentTooltip()
    {
        return __("Search intent refers to the purpose behind a user's search"
            . " query—what they’re looking to achieve. By default, transactional"
            . " intent is selected as recommended for product pages.");
    }

    /**
     * Get intent tooltip disabled
     *
     * @return string
     */
    public function getIntentTooltipDisabled()
    {
        return __("Search intent refers to the purpose behind a user's search"
            . " query—what they’re looking to achieve. By default, transactional"
            . " intent is selected as recommended for product pages.");
    }

    /**
     * Get reviewed tooltip
     *
     * @return string
     */
    public function getReviewedTooltip()
    {
        return sprintf('<p>%s</p>', __('Check this box to keep track of the products'
                . ' where you have reviewed the text. This is especially helpful if you'
                . ' have an internal workflow where text needs to go through a review'
                . ' process first before being published on the website. This checkbox'
                . ' does not affect the live content, it is only a classification.'))
            . sprintf('<p>%s</p>', __('You can filter reviewed products by'
                . ' clicking on the filter icon in the product list,'
                . ' clicking the WriteText.ai status dropdown and selecting “Reviewed”.'));
    }

    /**
     * Get keywords drawer tooltip
     *
     * @return string
     */
    public function keywordsDrawerTooltip()
    {
        return sprintf('<p><a href="%s" target="_blank">%s</a></p>', self::KEYWORDS_GUIDE_URL, __(
            'Read the complete guide here'
        ))
            . sprintf("<p>%s</p>", __("This pipeline visually maps out the journey of keywords through"
                . " different stages, helping you track progress and plan your next steps."))
            . sprintf("<p>%s</p>", __('Stars indicate that your page is currently ranking for a keyword.'
                . ' The "PRIMARY" badge marks the main keyword being targeted and prioritized for optimization.'))
            . sprintf("<p>%s</p>", __("Arrows show the progression path for each keyword."
                . " As your page meets the trigger criteria, it automatically moves up to the next keyword."
                . " You can set different triggers based on your SEO strategy:"))
            . sprintf("<p><ul><li class='wtai-list-disc'>%s</li>", __(
                "When your page is ranking within a specific position range in the SERP (recommended); or"
            ))
            . sprintf("<li class='wtai-list-disc'>%s</li></ul></p>", __("After a certain number of days"))
            . sprintf("<p>%s</p>", __("Use the Ranking History section to track progress over time."))
            . sprintf("<p>%s</p>", __("Select a specific date or refresh the view"
                . " to get the most up-to-date ranking information."))
            . sprintf("<p>%s</p>", __("Click on a specific keyword to view status,"
                . " position in the SERP, overview of the SERP, difficulty,"
                . " search volume, traffic potential, and intent."))
            . sprintf("<p>%s</p>", __("Cluster-based pipelines are automatically organized based on"
                . " the best possible keywords for each difficulty stage according to their search volume."
                . " Other keyword ideas that were not selected for the cluster-based pipelines are in"
                . " the keyword pool below. If you want to use these keywords, you can build a custom pipeline by"
                . " dragging keywords from the pool into an empty pipeline. You can also manually add target keywords"
                . " here and WriteText.ai will automatically retrieve search volume and"
                . " difficulty data if available."));
    }

    /**
     * Get keywords tooltip
     *
     * @return string
     */
    public function getKeywordsTooltip()
    {
        return sprintf("<p><strong>%s</strong></p>", __('Target keywords'))
            . sprintf("<p>%s</p>", __('Target keywords allow you to guide the AI toward optimizing'
                . ' your content for specific search terms. How you can use them depends on your plan.'))
            . sprintf("<p><strong>%s</strong></p>", __('Starter Plan'))
            . sprintf("<p>%s</p>", __('In the Starter plan, you can manually add target keywords'
                . ' before generating content. This is ideal if you already know which keywords you'
                . ' want to focus on. However, the full keyword optimization pipeline—including keyword analysis,'
                . ' ranking insights, clustering, and automation—is only available in the Pro plan.'))
            . sprintf("<p><strong>%s</strong></p>", __('Pro Plan'))
            . sprintf("<p>%s", __('Pro unlocks the full keyword optimization pipeline'))
            . sprintf(" (<a href='%s' target='_blank'>%s</a>): ", self::KEYWORDS_GUIDE_URL, __(
                'read the complete guide here'
            ))
            . sprintf("%s</p>", __('an AI-powered keyword analysis tool that uses the'
                . ' keyword ladder strategy to help you gradually improve your product page rankings.'))
            . sprintf("<p>%s</p>", __('Before starting, you can optionally add seed'
                . ' keywords—these help guide the AI during analysis, but aren’t guaranteed'
                . ' to be used if they don’t match the product context.'))
            . sprintf("<p>%s</p>", __('Once you click "Start AI-powered keyword analysis", the system will:'))
            . sprintf("<p><ul><li class='wtai-list-disc'>%s</li>", __(
                'Discover keywords your product pages already rank for'
            ))
            . sprintf("<li class='wtai-list-disc'>%s</li>", __(
                'Suggest new keyword ideas using product data, image analysis, and online research'
            ))
            . sprintf("<li class='wtai-list-disc'>%s</li>", __(
                'Automatically organize keyword suggestions into cluster-based pipelines,'
                    . ' starting with low-difficulty terms and progressing to higher-volume, more competitive ones'
            ))
            . sprintf("<li class='wtai-list-disc'>%s</li>", __(
                'Allow you to create your own custom pipelines to set specific keywords and stages for targeting'
            ))
            . sprintf("<li class='wtai-list-disc'>%s</li></ul></p>", __(
                'Provide keyword insights such as search volume, competition level, and search intent'
            ))
            . sprintf("<p>%s</p>", __('You can continue to manually add target keywords'
                . ' as needed to further refine the AI’s output.'))
            . sprintf("<p>%s</p>", __('Due to the complex nature of this process,'
                . ' starting AI-powered keyword analysis may take some time. You can click on'
                . ' "Automatically generate text when keyword analysis is done" or enable Full Automation'
                . ' in bulk to streamline the process. Make sure to select the text types'
                . ' you want to generate before starting AI-powered keyword analysis.'))
            . sprintf("<p><b>%s</b></p>", __('How the keyword optimization pipeline works'))
            . sprintf("<p>%s</p>", __('<em>Starting with low-difficulty keywords:</em><br>'
                . 'The pipeline identifies keywords with lower competition but good search potential.'))
            . sprintf("<p>%s</p>", __('<em>Progressive optimization:</em><br>'
                . 'As your product page starts to rank for low-difficulty keywords,'
                . ' the pipeline gradually recommends optimizing for higher-difficulty keywords.'))
            . sprintf("<p>%s</p>", __('<em>Automation and notifications:</em><br>'
                . 'WriteText.ai automates much of this process, analyzing keyword trends and'
                . ' notifying you when pages are ready for the next optimization step.'
                . ' Depending on your preferences, it can fully automate regenerating text with'
                . ' updated keywords and transferring to Magento, just regenerate and notify you for review,'
                . ' or prompt you to check and initiate regenerating text yourself.'))
            . sprintf("<p>%s</p>", __('<em>Iterative content refinement:</em><br>At every stage,'
                . ' the pipeline ensures your content is updated and optimized for current keyword trends,'
                . ' helping you maintain relevance and visibility.'));
    }

    /**
     * Get attributes tooltip
     *
     * @return string
     */
    public function getAttributesTooltip()
    {
        return  sprintf("<p>%s</p>", __("Product Data includes Attributes, your Thumbnail, and"
                . " optional Product Research."
                . " Select the data you want WriteText.ai to consider when generating text."))
            . sprintf("<p>%s</p>", __("Details help guide the AI,"
                . " but there’s no guarantee every item will appear in the final output."))
            . sprintf("<p>%s</p>", __("Each product can use up to 50 data fields (attributes) at no extra cost."
                . " If more apply, an additional 1 credit per product is charged for every 100 extra data fields."
                . " Fields without values aren’t counted or sent."));
    }

    /**
     * Get tones and styles tooltip
     *
     * @return string
     */
    public function getTonesAndStylesTooltip()
    {
        return __('<p>Select one or more tones to set the overall mood'
            . ' and attitude of the text, and then choose a style to'
            . ' set the voice and structure of the text.</p>');
    }

    /**
     * Get audience tooltip
     *
     * @return string
     */
    public function getAudienceTooltip()
    {
        return __(
            '<p>Select one or more tones to set the overall mood'
            . ' and attitude of the text, and then choose a style to'
            . ' set the voice and structure of the text.</p>'
            .'<p>Select the applicable audience for your product so WriteText.ai'
            . ' can generate text that will appeal to them. If you don’t select an audience, '
            . 'the generated text will default to a “neutral” audience. WriteText.ai also'
            . ' suggests more specific target markets based on your keywords. Click on the'
            . ' audience to select it or type in your own custom audience in the box.</p>'
            . '<p>If you want more precise control based on your own brand guidelines or existing content, '
            . 'you can build a brand voice instead.</p>'
        );
    }

    /**
     * Get meta title tooltip
     *
     * @return string
     */
    public function getPageTitleTooltip()
    {
        $pageTitleLength = $this->helper->getMaxLengthSettings('page_title');

        return sprintf(__('<p>WriteText.ai aims to generate a title with around'
            . ' %s characters, based on current SEO best practices. The current'
            . ' meta title saved for the product is displayed in the box on'
            . ' the right for your reference only.</p>'), $pageTitleLength)
            . sprintf("<p>%s</p>", __('To customize how titles are structured or written,'
            . ' you can set up a template for meta titles in the backend under Templates.'
            . ' If you have not set up or assigned any templates, WriteText.ai will'
            . ' generate a title based on its default approach using your product data.'));
    }

    /**
     * Get meta description tooltip
     *
     * @return string
     */
    public function getPageDescriptionTooltip()
    {
        $maxPageDescriptionLength = $this->helper->getMaxLengthSettings('page_description');

        return sprintf(__('<p>WriteText.ai aims to generate a description with'
            . ' around %s characters, based on current SEO best practices. The current'
            . ' meta description saved for the product is displayed in the box on'
            . ' the right for your reference only.</p>'), $maxPageDescriptionLength);
    }

    /**
     * Get description tooltip
     *
     * @return string
     */
    public function getProductDescriptionTooltip()
    {
        return  sprintf('<p>%s</p>', __('The current product description saved for the product is'
                . ' displayed in the box on the right for your reference only.'))
            . __('<p>Target length<br/>')
            . __('Indicate your target length by setting a minimum and maximum word count.'
                . ' WriteText.ai will aim to generate text within the number you set,'
                . ' but it may give you more or less words than expected from time to time.'
                . ' Note that your credit cost will depend on the target length you'
                . ' set so make sure to set a reasonable target range.'
                . " This target length is only considered when you don't have a template selected.</p>")
            . __('<p>Templates<br/>')
            . __('To better customize how descriptions are structured or written,'
                . ' you can set up a template for product descriptions in the backend under Templates.'
                . ' If you haven’t set or assigned a template, WriteText.ai will generate the text based on its'
                . ' default approach using your product data and the target length you define.'
                . ' When a template is used, the target length setting is ignored and'
                . ' content is generated based on the structure of the template.'
                . ' An estimated credit cost is shown in the preview panel based on the content'
                . ' sections included.</p>');
    }

    /**
     * Get short description tooltip
     *
     * @return string
     */
    public function getShortDescriptionTooltip()
    {
        return  sprintf('<p>%s</p>', __('The current short description saved for the product is'
                . ' displayed in the box on the right for your reference only.'))
            . __('<p>Target length<br/>')
            . __('Indicate your target length by setting a minimum and maximum word count.'
                . ' WriteText.ai will aim to generate text within the number you set,'
                . ' but it may give you more or less words than expected from time to time.'
                . ' Note that your credit cost will depend on the target length you'
                . ' set so make sure to set a reasonable target range. This target'
                . " length is only considered when you don't have a template selected.</p>")
            . __('<p>Templates<br/>')
            . __('To better customize how descriptions are structured or written,'
                . ' you can set up a template for short descriptions in the backend under Templates.'
                . ' If you haven’t set or assigned a template, WriteText.ai will generate the text'
                . ' based on its default approach using your product data and the target length'
                . ' you define. When a template is used, the target length setting is ignored'
                . ' and content is generated based on the structure of the template.'
                . ' An estimated credit cost is shown in the preview panel based on the'
                . ' content sections included.</p>');
    }

    /**
     * Get open graph tooltip
     *
     * @return string
     */
    public function getOpenGraphTooltip()
    {
        $maxOpenGraphLength = $this->helper->getMaxLengthSettings('open_graph');

        return sprintf(__('<p>This is the text that appears in the preview when you share'
            . ' the product page on social media sites like Facebook, Twitter, or LinkedIn.'
            . ' WriteText.ai aims to generate text with more or less %s characters,'
            . ' based on current best practices. The current Open Graph text saved for'
            . ' the product is displayed in the box on the right'
            . ' for your reference only.</p>'), $maxOpenGraphLength);
    }

    /**
     * Get transfer tooltip
     *
     * @return string
     */
    public function getTransferTooltip()
    {
        return sprintf("<p>%s</p>", __("When you're done generating and/or editing text,"
                . " you have the option to save the draft inside WriteText.ai or transfer"
                . " the text to Magento. Transferring your text to Magento will publish it"
                . " directly to the website. If the updates did not reflect in your page,"
                . " you may need to flush the cache or run reindexing. Please also make"
                . " sure that your product is enabled in the frontend."))
            . sprintf("<p>%s</p>", __("Note: Any media or directive you have inserted in"
                . " your current Magento text will be overwritten when you transfer from WriteText.ai."));
    }

    /**
     * Get generate rewrite tooltip
     *
     * @return string
     */
    public function getGenerateRewriteTooltip()
    {
        return sprintf('<p class="wtai-heading">%s</p>', __('Generate new text'))
            . sprintf('<p>%s</p>', __('Generate text for your selected text types based on'
                . ' the settings on this page.'));
    }

    /**
     * Get preview changes tooltip
     *
     * @return string
     */
    public function getPreviewChangesTooltip()
    {
        return __('Save your changes to preview how they will look on your website.');
    }

    /**
     * Get alt text tooltip
     *
     * @return string
     */
    public function getAltTextTooltip()
    {
        $altTextLength = $this->helper->getMaxLengthSettings('alt_text');

        return sprintf(__("Analyze your product image and automatically generate an alt image text"
            . " (incorporating your product name and keywords) to help improve your website's"
            . " accessibility and the way that search engines understand your content."
            . " WriteText.ai aims to generate an alt text with around %s characters based on current best practices."
            . " Note: We only allow up to 11 images here, including the thumbnail."
            . " If you have more than 11 images uploaded to your product,"
            . " only the first 11 images in your listing will be included."), $altTextLength);
    }

    /**
     * Get trigger action 'none' selected tooltip
     *
     * @return string
     */
    public function getTriggerActionNoneSelectedTooltip()
    {
        return __('This option is disabled when trigger action selected is "None".');
    }

    /**
     * Get trigger action 'none' selected tooltip
     *
     * @return string
     */
    public function getPipelineLockedTooltip()
    {
        return __("This pipeline is currently unlocked. Click to lock the entire pipeline to"
            . " preserve its current structure  and prevent changes, regardless of monthly search data updates.");
    }

    /**
     * Get trigger action 'none' selected tooltip
     *
     * @return string
     */
    public function getPipelineUnlockedTooltip()
    {
        return __("This pipeline is currently locked. Click to unlock the keyword pipeline to"
            . " allow updates and adjustments based on the latest search data trends.");
    }

    /**
     * Get currently optimizing keywords tooltip
     *
     * @return string
     */
    public function getCurrentlyOptimizingKeywordsTooltip()
    {
        return __('These are the keywords currently applied in the text,'
            . ' either used exactly as is or integrated in a semantically relevant way.');
    }

    /**
     * Get no AI model assigned tooltip
     *
     * @return string
     */
    public function getNoAiModelAssignedTooltip()
    {
        return sprintf(
            '<p>%s<br/>%s</p>'
            . '<p class="wtai-go-linked-webshops">'
            . '<a href="%s" target="_blank" class="action-primary primary">%s</a>'
            . '</p>',
            __('No brand voice is assigned to this webshop.'),
            __(
                'You can assign an existing brand voice or build a new one in the backend, '
                . 'then link it to this webshop to use it here.'
            ),
            'https://platform.writetext.ai/webshops',
            __('Assign brand voice in backend')
        );
    }

    /**
     * Get no AI model selected tooltip
     *
     * @return string
     */
    public function getAiModelTooltip()
    {
        
        return __(
            '<p><a target="_blank" href="https://platform.writetext.ai/brand-voices" >'
            . 'Build your own custom brand voice</a> in the backend and link it to your webshop '
            . 'to make it available here.</p>'
            . '<p>Upload PDFs or CSV files with brand guidelines or sample product text, '
            . 'or sync existing product content from your shop. '
            . 'WriteText.ai uses these samples to understand your brand’s tone and writing style.</p>'
            . '<p>Brand voice guides how text is written. Structure, sections, headings, '
            . 'and formatting are still controlled by your templates.</p>'
            . '<p>Tone, Style, and Audience use general writing presets, while brand voice follows '
            . 'your own content. You can only use one or the other.</p>'
        );
    }

    /**
     * Get additional prompt tooltip
     *
     * @return \Magento\Framework\Phrase
     */
    public function getAdditionalPromptTooltip()
    {
        return __(
            'Enter any additional instructions for the AI to follow when generating text. '
            . 'These instructions will be added to the prompt that the AI uses to generate text.'
        );
    }
}
