/**
 * Dynamic Variables Component
 *
 * UI helper component for inserting dynamic variables into text fields.
 *
 * @package
 * @since   1.0.0
 */

import { __ } from '@wordpress/i18n';
import { Button, Popover, MenuGroup, MenuItem } from '@wordpress/components';
import { useState, useRef } from '@wordpress/element';
import { plus } from '@wordpress/icons';
import './dynamic-variables.css';

const DynamicVariables = ({ onInsert, context = 'post', disabled = false }) => {
  const [isOpen, setIsOpen] = useState(false);
  const buttonRef = useRef();

  // Define available variables based on context
  const getVariables = () => {
    const commonVars = [
      {
        value: '%%sitename%%',
        label: __('Site Name', 'prorank-seo'),
        description: __('The name of your website', 'prorank-seo'),
      },
      {
        value: '%%tagline%%',
        label: __('Site Tagline', 'prorank-seo'),
        description: __("Your site's tagline", 'prorank-seo'),
      },
      {
        value: '%%sep%%',
        label: __('Separator', 'prorank-seo'),
        description: __('The separator character', 'prorank-seo'),
      },
      {
        value: '%%currentyear%%',
        label: __('Current Year', 'prorank-seo'),
        description: __('The current year', 'prorank-seo'),
      },
      {
        value: '%%currentmonth%%',
        label: __('Current Month', 'prorank-seo'),
        description: __('The current month', 'prorank-seo'),
      },
      {
        value: '%%currentday%%',
        label: __('Current Day', 'prorank-seo'),
        description: __('The current day', 'prorank-seo'),
      },
    ];

    const postVars = [
      {
        value: '%%title%%',
        label: __('Post Title', 'prorank-seo'),
        description: __('The title of the post/page', 'prorank-seo'),
      },
      {
        value: '%%excerpt%%',
        label: __('Excerpt', 'prorank-seo'),
        description: __('The post excerpt', 'prorank-seo'),
      },
      {
        value: '%%category%%',
        label: __('Category', 'prorank-seo'),
        description: __('The primary category', 'prorank-seo'),
      },
      {
        value: '%%focuskeyword%%',
        label: __('Focus Keyword', 'prorank-seo'),
        description: __('The focus keyword', 'prorank-seo'),
      },
      {
        value: '%%author%%',
        label: __('Author Name', 'prorank-seo'),
        description: __("The post author's name", 'prorank-seo'),
      },
      {
        value: '%%date%%',
        label: __('Publish Date', 'prorank-seo'),
        description: __('The publish date', 'prorank-seo'),
      },
      {
        value: '%%modified%%',
        label: __('Modified Date', 'prorank-seo'),
        description: __('The last modified date', 'prorank-seo'),
      },
      {
        value: '%%id%%',
        label: __('Post ID', 'prorank-seo'),
        description: __('The post ID', 'prorank-seo'),
      },
    ];

    const termVars = [
      {
        value: '%%term_title%%',
        label: __('Term Title', 'prorank-seo'),
        description: __('The term name', 'prorank-seo'),
      },
      {
        value: '%%term_description%%',
        label: __('Term Description', 'prorank-seo'),
        description: __('The term description', 'prorank-seo'),
      },
      {
        value: '%%term_hierarchy%%',
        label: __('Term Hierarchy', 'prorank-seo'),
        description: __('The full term hierarchy', 'prorank-seo'),
      },
    ];

    const archiveVars = [
      {
        value: '%%archive_title%%',
        label: __('Archive Title', 'prorank-seo'),
        description: __('The archive title', 'prorank-seo'),
      },
      {
        value: '%%pagenumber%%',
        label: __('Page Number', 'prorank-seo'),
        description: __('The current page number', 'prorank-seo'),
      },
      {
        value: '%%pagetotal%%',
        label: __('Total Pages', 'prorank-seo'),
        description: __('The total number of pages', 'prorank-seo'),
      },
    ];

    const authorVars = [
      {
        value: '%%author%%',
        label: __('Author Name', 'prorank-seo'),
        description: __('The author archive display name', 'prorank-seo'),
      },
      {
        value: '%%name%%',
        label: __('Author Name', 'prorank-seo'),
        description: __('The author archive display name', 'prorank-seo'),
      },
    ];

    const productVars = [
      {
        value: '%%product_name%%',
        label: __('Product Name', 'prorank-seo'),
        description: __('The product name', 'prorank-seo'),
      },
      {
        value: '%%product_short_description%%',
        label: __('Short Description', 'prorank-seo'),
        description: __('Product short description', 'prorank-seo'),
      },
      {
        value: '%%product_price%%',
        label: __('Product Price', 'prorank-seo'),
        description: __('The product price', 'prorank-seo'),
      },
      {
        value: '%%product_sku%%',
        label: __('Product SKU', 'prorank-seo'),
        description: __('The product SKU', 'prorank-seo'),
      },
    ];

    let variables = [...commonVars];

    switch (context) {
      case 'post':
      case 'page':
        variables = [...variables, ...postVars];
        break;
      case 'term':
      case 'category':
      case 'tag':
        variables = [...variables, ...termVars];
        break;
      case 'archive':
        variables = [...variables, ...archiveVars];
        break;
      case 'author':
        variables = [...variables, ...authorVars];
        break;
      case 'product':
        variables = [...variables, ...postVars, ...productVars];
        break;
      case 'all':
        variables = [...variables, ...postVars, ...termVars, ...archiveVars, ...authorVars, ...productVars];
        break;
    }

    return variables;
  };

  const handleInsert = (variable) => {
    onInsert(variable);
    setIsOpen(false);
  };

  const variables = getVariables();

  return (
    <div className="prorank-dynamic-variables">
      <Button
        ref={buttonRef}
        icon={plus}
        variant="tertiary"
        size="small"
        onClick={() => setIsOpen(!isOpen)}
        disabled={disabled}
        label={__('Insert Variable', 'prorank-seo')}
        className="prorank-dynamic-variables__trigger"
      />

      {isOpen && (
        <Popover
          anchor={buttonRef.current}
          onClose={() => setIsOpen(false)}
          placement="bottom-start"
          className="prorank-dynamic-variables__popover"
        >
          <div className="prorank-dynamic-variables__header">
            <h3>{__('Dynamic Variables', 'prorank-seo')}</h3>
            <p className="description">
              {__('Click a variable to insert it at the cursor position.', 'prorank-seo')}
            </p>
          </div>

          <div className="prorank-dynamic-variables__list">
            <MenuGroup>
              {variables.map((variable) => (
                <MenuItem
                  key={variable.value}
                  onClick={() => handleInsert(variable.value)}
                  className="prorank-dynamic-variables__item"
                >
                  <div className="prorank-dynamic-variables__item-content">
                    <code className="prorank-dynamic-variables__code">{variable.value}</code>
                    <span className="prorank-dynamic-variables__label">{variable.label}</span>
                    {variable.description && (
                      <span className="prorank-dynamic-variables__description">
                        {variable.description}
                      </span>
                    )}
                  </div>
                </MenuItem>
              ))}
            </MenuGroup>
          </div>
        </Popover>
      )}
    </div>
  );
};

export default DynamicVariables;
