/**
 * Title & Meta Settings Component
 *
 * Comprehensive settings for titles, meta descriptions, and robots meta across
 * all post types, taxonomies, and special pages.
 *
 * @package ProRank\SEO
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Button, Input, Select, Checkbox, Toggle, Card, Alert } from '../../../components/ui';
import LoadingState from '../../../components/LoadingState';

const SEO_PRIMARY_POST_TYPE_ORDER = ['post', 'page', 'attachment', 'product', 'sc_product', 'prorank_podcast'];

// Hide builder/system CPTs so Titles & Meta stays focused on search-facing content.
const HIDDEN_POST_TYPE_TABS = new Set([
  'e-floating-buttons',
  'elementor_library',
  'elementor-hf',
  'wpcode',
  'acf-post-type',
  'acf-field-group',
  'acf-field',
  'acf-taxonomy',
  'bp-email',
  'shop_order_placehold',
  'monsterinsights_note',
  'wpforms',
  'wpforms-template',
  'sc_upsell',
]);

const shouldShowPostTypeTab = (type) => {
  if (!type?.viewable || !type?.slug) {
    return false;
  }

  if (HIDDEN_POST_TYPE_TABS.has(type.slug)) {
    return false;
  }

  return true;
};

const hasCustomRobotsOverrides = (prefix, settings) => {
  const followKey = `${prefix}_robots_follow`;
  const archiveKey = `${prefix}_robots_archive`;
  const imageIndexKey = `${prefix}_robots_imageindex`;
  const snippetKey = `${prefix}_robots_snippet`;
  const maxSnippetKey = `${prefix}_max_snippet`;
  const maxVideoKey = `${prefix}_max_video_preview`;
  const maxImageKey = `${prefix}_max_image_preview`;

  return (
    settings[followKey] === false ||
    settings[archiveKey] === false ||
    settings[imageIndexKey] === false ||
    settings[snippetKey] === false ||
    (settings[maxSnippetKey] !== undefined && String(settings[maxSnippetKey]) !== '' && String(settings[maxSnippetKey]) !== '-1') ||
    (settings[maxVideoKey] !== undefined && String(settings[maxVideoKey]) !== '' && String(settings[maxVideoKey]) !== '-1') ||
    (settings[maxImageKey] !== undefined && String(settings[maxImageKey]) !== '' && String(settings[maxImageKey]).toLowerCase() !== 'large')
  );
};

const getRobotsIndexingMode = (prefix, settings) => {
  const robotsMeta = settings[`${prefix}_robots_meta`];
  const indexSetting = settings[`${prefix}_robots_index`];

  if (robotsMeta !== 'custom') {
    return 'default';
  }

  if (hasCustomRobotsOverrides(prefix, settings)) {
    return 'custom';
  }

  if (indexSetting === false) {
    return 'noindex';
  }

  if (indexSetting === true || indexSetting === undefined) {
    return 'index';
  }

  return 'custom';
};

const normalizeLoadedSettings = (incoming = {}, separators = []) => {
  const next = { ...incoming };
  const separator = typeof next.title_separator === 'string' ? next.title_separator : '';
  const isCustomSeparator = separator !== '' && !separators.includes(separator);

  if (isCustomSeparator) {
    next.use_custom_separator = true;
    next.custom_separator = separator;
  } else if (!next.custom_separator && separator !== '') {
    next.custom_separator = separator;
  }

  return next;
};

const applyRobotsIndexingMode = (settings, prefix, mode) => {
  const nextSettings = { ...settings };
  const metaKey = `${prefix}_robots_meta`;
  const indexKey = `${prefix}_robots_index`;

  if (mode === 'default') {
    nextSettings[metaKey] = 'default';
    return nextSettings;
  }

  nextSettings[metaKey] = 'custom';

  if (mode === 'index') {
    nextSettings[indexKey] = true;
  } else if (mode === 'noindex') {
    nextSettings[indexKey] = false;
  }

  return nextSettings;
};

const TitleMetaSettings = () => {
  const [settings, setSettings] = useState({});
  const [siteInfo, setSiteInfo] = useState({
    show_on_front: window.prorankSeo?.siteSettings?.show_on_front || 'posts',
    page_on_front: window.prorankSeo?.siteSettings?.page_on_front || 0,
  });
  const [postTypes, setPostTypes] = useState([]);
  const [taxonomies, setTaxonomies] = useState([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState(null);
  const [activeTab, setActiveTab] = useState('global-meta');

  // Template variables organized by category
  const templateVariables = {
    basic: [
      '%sep%', '%sitename%', '%tagline%', '%page%', '%currentyear%', '%currentmonth%', '%currentday%'
    ],
    post: [
      '%title%', '%excerpt%', '%author%', '%date%', '%modified%', '%category%', '%tag%', '%focus_keyword%'
    ],
    archive: [
      '%term%', '%term_description%', '%name%', '%search_query%', '%count%'
    ],
    woocommerce: [
      '%price%', '%sku%', '%brand%', '%stock_status%'
    ]
  };

  // Title separators
  const separators = ['-', '–', '—', '|', '•', '»', '/', '~', ':', '·'];

  useEffect(() => {
    loadSettings();
    loadPostTypes();
    loadTaxonomies();
    loadSiteInfo();
  }, []);

  const loadSettings = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/titles-meta',
      });
      setSettings(normalizeLoadedSettings(response?.settings || response || {}, separators));
    } catch (error) {
      // Failed to load settings, use defaults
      setNotice({ type: 'error', message: __('Failed to load settings', 'prorank-seo') });
    } finally {
      setLoading(false);
    }
  };

  const loadPostTypes = async () => {
    try {
      const response = await apiFetch({
        path: '/wp/v2/types?context=edit',
      });
      const types = Object.values(response).filter(shouldShowPostTypeTab);
      setPostTypes(types);
    } catch (error) {
      // Failed to load post types
    }
  };

  const loadTaxonomies = async () => {
    try {
      const response = await apiFetch({
        path: '/wp/v2/taxonomies?context=edit',
      });
      const taxs = Object.values(response).filter(tax => tax.visibility?.public !== false);
      setTaxonomies(taxs);
    } catch (error) {
      // Failed to load taxonomies
    }
  };

  const loadSiteInfo = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/site_info',
      });

      if (response?.success && response?.data) {
        setSiteInfo((prev) => ({ ...prev, ...response.data }));
      }
    } catch (error) {
      // Keep localized defaults when endpoint is unavailable.
    }
  };

  const saveSettings = async () => {
    setSaving(true);
    setNotice(null);

    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/titles-meta',
        method: 'POST',
        data: settings,
      });
      setSettings((prev) => normalizeLoadedSettings(prev, separators));
      setNotice({ type: 'success', message: __('Settings saved successfully', 'prorank-seo') });
    } catch (error) {
      // Failed to save settings
      setNotice({ type: 'error', message: __('Failed to save settings', 'prorank-seo') });
    } finally {
      setSaving(false);
    }
  };

  const updateSetting = (key, value) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  const resetSettings = async () => {
    if (!confirm(__('Are you sure you want to reset all Titles & Meta settings to defaults?', 'prorank-seo'))) {
      return;
    }

    setSaving(true);
    setNotice(null);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/titles-meta',
        method: 'POST',
        data: { __reset_defaults: true },
      });

      setSettings(normalizeLoadedSettings(response?.settings || {}, separators));
      setNotice({ type: 'success', message: __('Settings reset to defaults', 'prorank-seo') });
    } catch (error) {
      setNotice({ type: 'error', message: __('Failed to reset settings', 'prorank-seo') });
    } finally {
      setSaving(false);
    }
  };

  const renderVariableReference = () => (
    <Card>
      <div className="pr:p-6">
        <h4 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-4">
          {__('Available Variables', 'prorank-seo')}
        </h4>
        <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-3 pr:gap-6">
          <div>
            <strong className="pr:text-sm pr:font-medium pr:text-gray-900 pr:block pr:mb-2">
              {__('Basic', 'prorank-seo')}
            </strong>
            <ul className="pr:space-y-1">
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%sep%</code> - {__('Separator', 'prorank-seo')}
              </li>
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%sitename%</code> - {__('Site Name', 'prorank-seo')}
              </li>
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%tagline%</code> - {__('Site Tagline', 'prorank-seo')}
              </li>
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%page%</code> - {__('Page Number', 'prorank-seo')}
              </li>
            </ul>
          </div>
          <div>
            <strong className="pr:text-sm pr:font-medium pr:text-gray-900 pr:block pr:mb-2">
              {__('Post/Page', 'prorank-seo')}
            </strong>
            <ul className="pr:space-y-1">
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%title%</code> - {__('Title', 'prorank-seo')}
              </li>
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%excerpt%</code> - {__('Excerpt', 'prorank-seo')}
              </li>
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%author%</code> - {__('Author', 'prorank-seo')}
              </li>
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%date%</code> - {__('Date', 'prorank-seo')}
              </li>
            </ul>
          </div>
          <div>
            <strong className="pr:text-sm pr:font-medium pr:text-gray-900 pr:block pr:mb-2">
              {__('Archive', 'prorank-seo')}
            </strong>
            <ul className="pr:space-y-1">
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%term%</code> - {__('Term Name', 'prorank-seo')}
              </li>
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%term_description%</code> - {__('Term Description', 'prorank-seo')}
              </li>
              <li className="pr:text-xs pr:text-gray-600">
                <code className="pr:px-1.5 pr:py-0.5 pr:bg-gray-100 pr:rounded-xs pr:text-xs pr:font-mono">%search_query%</code> - {__('Search Query', 'prorank-seo')}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </Card>
  );

  const renderGlobalMeta = () => (
    <div className="pr:space-y-6">
      {/* Robots Meta */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Robots Meta', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
            {__('Default values for meta robots. These can be overridden for individual posts/pages.', 'prorank-seo')}
          </p>
          <div className="pr:space-y-4">
            <Checkbox
              label={__('Index', 'prorank-seo')}
              help={__('Allow search engines to index pages', 'prorank-seo')}
              checked={settings.robots_default_index !== false}
              onChange={(value) => updateSetting('robots_default_index', value)}
            />
            <Checkbox
              label={__('Follow', 'prorank-seo')}
              help={__('Allow search engines to follow links', 'prorank-seo')}
              checked={settings.robots_default_follow !== false}
              onChange={(value) => updateSetting('robots_default_follow', value)}
            />
            <Checkbox
              label={__('Archive', 'prorank-seo')}
              help={__('Allow search engines to show cached versions', 'prorank-seo')}
              checked={settings.robots_default_archive !== false}
              onChange={(value) => updateSetting('robots_default_archive', value)}
            />
            <Checkbox
              label={__('Image Index', 'prorank-seo')}
              help={__('Allow images to be indexed', 'prorank-seo')}
              checked={settings.robots_default_imageindex !== false}
              onChange={(value) => updateSetting('robots_default_imageindex', value)}
            />
            <Checkbox
              label={__('Snippet', 'prorank-seo')}
              help={__('Allow snippet in search results', 'prorank-seo')}
              checked={settings.robots_default_snippet !== false}
              onChange={(value) => updateSetting('robots_default_snippet', value)}
            />
          </div>
        </div>
      </Card>

      {/* Advanced Robots Meta */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Advanced Robots Meta', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <div className="pr:space-y-4">
            <Input
              label={__('Max Snippet Length', 'prorank-seo')}
              help={__('Maximum text length for snippet in characters (-1 for no limit)', 'prorank-seo')}
              type="number"
              value={settings.robots_max_snippet || '-1'}
              onChange={(value) => updateSetting('robots_max_snippet', value)}
            />
            <Input
              label={__('Max Video Preview', 'prorank-seo')}
              help={__('Maximum video preview in seconds (-1 for no limit)', 'prorank-seo')}
              type="number"
              value={settings.robots_max_video_preview || '-1'}
              onChange={(value) => updateSetting('robots_max_video_preview', value)}
            />
            <Select
              label={__('Max Image Preview', 'prorank-seo')}
              value={settings.robots_max_image_preview || 'large'}
              options={[
                { label: __('None', 'prorank-seo'), value: 'none' },
                { label: __('Standard', 'prorank-seo'), value: 'standard' },
                { label: __('Large', 'prorank-seo'), value: 'large' },
              ]}
              onChange={(value) => updateSetting('robots_max_image_preview', value)}
            />
          </div>
        </div>
      </Card>

      {/* General Settings */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('General Settings', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <div className="pr:space-y-6">
            <div>
              <p className="pr:text-sm pr:font-medium pr:text-gray-900 pr:mb-2">
                {__('Separator Character', 'prorank-seo')}
              </p>
              <p className="pr:text-xs pr:text-gray-500 pr:mb-3">
                {__('Choose the character to separate your title elements', 'prorank-seo')}
              </p>
              <div className="pr:grid pr:grid-cols-11 pr:gap-2">
                {separators.map(sep => (
                  <button
                    key={sep}
                    type="button"
                    className={`
                      pr:flex pr:items-center pr:justify-center pr:h-10 pr:px-3 pr:border pr:rounded-md pr:text-sm pr:font-medium pr:transition-colors
                      ${settings.title_separator === sep && !settings.use_custom_separator
                        ? 'pr:bg-primary-50 pr:border-primary-500 pr:text-primary-600'
                        : 'pr:bg-white pr:border-gray-300 pr:text-gray-700 pr:hover:bg-gray-50'
                      }
                    `}
                    onClick={() => {
                      updateSetting('title_separator', sep);
                      updateSetting('use_custom_separator', false);
                    }}
                  >
                    {sep}
                  </button>
                ))}
                <button
                  type="button"
                  className={`
                    pr:flex pr:items-center pr:justify-center pr:h-10 pr:px-3 pr:border pr:rounded-md pr:text-sm pr:font-medium pr:transition-colors
                    ${settings.use_custom_separator
                      ? 'pr:bg-primary-50 pr:border-primary-500 pr:text-primary-600'
                      : 'pr:bg-white pr:border-gray-300 pr:text-gray-700 pr:hover:bg-gray-50'
                    }
                  `}
                  onClick={() => {
                    updateSetting('use_custom_separator', true);
                    if (!settings.custom_separator) {
                      updateSetting('custom_separator', '»');
                    }
                    updateSetting('title_separator', settings.custom_separator || '»');
                  }}
                >
                  {__('Custom', 'prorank-seo')}
                </button>
              </div>
              {settings.use_custom_separator && (
                <div className="pr:mt-3">
                  <Input
                    label={__('Custom Separator', 'prorank-seo')}
                    value={settings.custom_separator || ''}
                    onChange={(value) => {
                      updateSetting('custom_separator', value);
                      updateSetting('title_separator', value);
                    }}
                    placeholder={__('Enter custom separator', 'prorank-seo')}
                    help={__('Enter any character or text to use as separator', 'prorank-seo')}
                  />
                </div>
              )}
            </div>

            <Toggle
              label={__('Capitalize Titles', 'prorank-seo')}
              help={__('Automatically capitalize first letter of each word in titles', 'prorank-seo')}
              checked={settings.capitalize_titles === true}
              onChange={(value) => updateSetting('capitalize_titles', value)}
            />

            <Toggle
              label={__('Noindex Empty Archives', 'prorank-seo')}
              help={__('Prevent empty archive pages from being indexed', 'prorank-seo')}
              checked={settings.noindex_empty_archives === true}
              onChange={(value) => updateSetting('noindex_empty_archives', value)}
            />
          </div>
        </div>
      </Card>
    </div>
  );

  const renderHomepage = () => {
    const { show_on_front, page_on_front } = siteInfo;
    const isStaticHomepage = show_on_front === 'page' && page_on_front;

    return (
      <div className="pr:space-y-6">
        <Card>
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Homepage Settings', 'prorank-seo')}
            </h3>
          </div>
          <div className="pr:p-6">
            {isStaticHomepage ? (
              <Alert variant="info">
                <p className="pr:mb-3">
                  {__('A static page is set as your homepage. SEO settings should be configured on that page directly.', 'prorank-seo')}
                </p>
                <Button
                  variant="primary"
                  onClick={() => window.location.href = `${window.prorankSeo?.adminUrl || '/wp-admin/'}post.php?post=${page_on_front}&action=edit`}
                >
                  {__('Edit Homepage', 'prorank-seo')}
                </Button>
              </Alert>
            ) : (
              <div className="pr:space-y-4">
                <Input
                  label={__('Homepage Title', 'prorank-seo')}
                  value={settings.homepage_title || '%sitename% %sep% %tagline%'}
                  onChange={(value) => updateSetting('homepage_title', value)}
                  help={__('Use variables like %sitename%, %tagline%, %sep%', 'prorank-seo')}
                />
                <div className="pr:space-y-2">
                  <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                    {__('Homepage Meta Description', 'prorank-seo')}
                  </label>
                  <textarea
                    className="pr:block pr:w-full pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:focus:outline-hidden pr:focus:ring-2 pr:focus:ring-primary-500 pr:focus:border-transparent"
                    rows={3}
                    value={settings.homepage_description || ''}
                    onChange={(e) => updateSetting('homepage_description', e.target.value)}
                  />
                  <p className="pr:text-xs pr:text-gray-500">
                    {__('Recommended: 150-160 characters', 'prorank-seo')}
                  </p>
                </div>
                <Select
                  label={__('Homepage Robots Meta', 'prorank-seo')}
                  value={settings.homepage_robots || 'index,follow'}
                  options={[
                    { label: __('Index, Follow', 'prorank-seo'), value: 'index,follow' },
                    { label: __('Index, Nofollow', 'prorank-seo'), value: 'index,nofollow' },
                    { label: __('Noindex, Follow', 'prorank-seo'), value: 'noindex,follow' },
                    { label: __('Noindex, Nofollow', 'prorank-seo'), value: 'noindex,nofollow' },
                  ]}
                  onChange={(value) => updateSetting('homepage_robots', value)}
                />
              </div>
            )}
          </div>
        </Card>
        {renderVariableReference()}
      </div>
    );
  };

  const renderAuthors = () => (
    <div className="pr:space-y-6">
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Author Archives', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <div className="pr:space-y-6">
            <Toggle
              label={__('Enable Author Archives', 'prorank-seo')}
              help={__('If disabled, author archives will be redirected to homepage. Enable to avoid duplicate content issues with proper noindex.', 'prorank-seo')}
              checked={settings.disable_author_archives !== true}
              onChange={(value) => updateSetting('disable_author_archives', !value)}
            />

            {!settings.disable_author_archives && (
              <>
                <Input
                  label={__('Author Base', 'prorank-seo')}
                  value={settings.author_base || 'author'}
                  onChange={(value) => updateSetting('author_base', value)}
                  help={__('Change the /author/ part in author archive URLs', 'prorank-seo')}
                />

                <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                  <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-4">
                    {__('Author Indexing & Robots', 'prorank-seo')}
                  </h4>
                  <Select
                    label={__('Author Indexing', 'prorank-seo')}
                    value={getRobotsIndexingMode('author', settings)}
                    options={[
                      { label: __('Use Global Default', 'prorank-seo'), value: 'default' },
                      { label: __('Index Author Archives', 'prorank-seo'), value: 'index' },
                      { label: __('Noindex Author Archives', 'prorank-seo'), value: 'noindex' },
                      { label: __('Custom', 'prorank-seo'), value: 'custom' },
                    ]}
                    onChange={(value) => setSettings((prev) => applyRobotsIndexingMode(prev, 'author', value))}
                    help={__('Choose whether author archive pages should be indexed. Use Custom only when you need manual robots control.', 'prorank-seo')}
                  />

                  {getRobotsIndexingMode('author', settings) === 'custom' && (
                    <div className="pr:mt-4 pr:space-y-3">
                      <Checkbox
                        label={__('Index', 'prorank-seo')}
                        checked={settings.author_robots_index !== false}
                        onChange={(value) => updateSetting('author_robots_index', value)}
                      />
                      <Checkbox
                        label={__('Follow', 'prorank-seo')}
                        checked={settings.author_robots_follow !== false}
                        onChange={(value) => updateSetting('author_robots_follow', value)}
                      />
                      <Checkbox
                        label={__('Archive', 'prorank-seo')}
                        checked={settings.author_robots_archive !== false}
                        onChange={(value) => updateSetting('author_robots_archive', value)}
                      />
                      <Checkbox
                        label={__('Image Index', 'prorank-seo')}
                        checked={settings.author_robots_imageindex !== false}
                        onChange={(value) => updateSetting('author_robots_imageindex', value)}
                      />
                      <Checkbox
                        label={__('Snippet', 'prorank-seo')}
                        checked={settings.author_robots_snippet !== false}
                        onChange={(value) => updateSetting('author_robots_snippet', value)}
                      />
                    </div>
                  )}
                </div>

                <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                  <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-4">
                    {__('Author Advanced Robots', 'prorank-seo')}
                  </h4>
                  <div className="pr:space-y-4">
                    <Input
                      label={__('Max Snippet', 'prorank-seo')}
                      type="number"
                      value={settings.author_max_snippet || '-1'}
                      onChange={(value) => updateSetting('author_max_snippet', value)}
                      help={__('Maximum text length in characters (-1 for no limit)', 'prorank-seo')}
                    />
                    <Input
                      label={__('Max Video Preview', 'prorank-seo')}
                      type="number"
                      value={settings.author_max_video_preview || '-1'}
                      onChange={(value) => updateSetting('author_max_video_preview', value)}
                      help={__('Maximum video preview in seconds (-1 for no limit)', 'prorank-seo')}
                    />
                    <Select
                      label={__('Max Image Preview', 'prorank-seo')}
                      value={settings.author_max_image_preview || 'large'}
                      options={[
                        { label: __('None', 'prorank-seo'), value: 'none' },
                        { label: __('Standard', 'prorank-seo'), value: 'standard' },
                        { label: __('Large', 'prorank-seo'), value: 'large' },
                      ]}
                      onChange={(value) => updateSetting('author_max_image_preview', value)}
                    />
                  </div>
                </div>

                <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                  <div className="pr:space-y-4">
                    <Input
                      label={__('Author Archive Title', 'prorank-seo')}
                      value={settings.author_archive_title || '%name% %sep% %sitename% %page%'}
                      onChange={(value) => updateSetting('author_archive_title', value)}
                      help={__('Title tag on author archives. Use %name%, %sep%, %sitename%, %page%', 'prorank-seo')}
                    />
                    <div className="pr:space-y-2">
                      <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                        {__('Author Archive Description', 'prorank-seo')}
                      </label>
                      <textarea
                        className="pr:block pr:w-full pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:focus:outline-hidden pr:focus:ring-2 pr:focus:ring-primary-500 pr:focus:border-transparent"
                        rows={2}
                        value={settings.author_archive_description || ''}
                        onChange={(e) => updateSetting('author_archive_description', e.target.value)}
                      />
                      <p className="pr:text-xs pr:text-gray-500">
                        {__('Meta description for author archive pages', 'prorank-seo')}
                      </p>
                    </div>
                  </div>
                </div>

                <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                  <div className="pr:space-y-4">
                    <Toggle
                      label={__('Slack Enhanced Sharing', 'prorank-seo')}
                      help={__('Show additional info (name & post count) when shared on Slack', 'prorank-seo')}
                      checked={settings.author_slack_enhanced === true}
                      onChange={(value) => updateSetting('author_slack_enhanced', value)}
                    />

                    <Toggle
                      label={__('Add SEO Controls to User Profiles', 'prorank-seo')}
                      help={__('Add SEO meta box to user profile pages', 'prorank-seo')}
                      checked={settings.author_seo_meta_box === true}
                      onChange={(value) => updateSetting('author_seo_meta_box', value)}
                    />
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      </Card>
      {renderVariableReference()}
    </div>
  );

  const renderMiscPages = () => (
    <div className="pr:space-y-6">
      {/* Date Archives */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Date Archives', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <div className="pr:space-y-4">
            <Toggle
              label={__('Enable Date Archives', 'prorank-seo')}
              help={__('Enable or disable date archives (e.g: domain.com/2019/06/). If disabled, they will be redirected to homepage.', 'prorank-seo')}
              checked={settings.disable_date_archives !== true}
              onChange={(value) => updateSetting('disable_date_archives', !value)}
            />
            {!settings.disable_date_archives && (
              <>
                <Input
                  label={__('Date Archive Title', 'prorank-seo')}
                  value={settings.date_archive_title || '%date% %sep% %sitename%'}
                  onChange={(value) => updateSetting('date_archive_title', value)}
                  help={__('Title tag for date archive pages', 'prorank-seo')}
                />
                <Checkbox
                  label={__('Noindex Date Archives', 'prorank-seo')}
                  checked={settings.noindex_date_archives === true}
                  onChange={(value) => updateSetting('noindex_date_archives', value)}
                  help={__('Prevent date archives from being indexed', 'prorank-seo')}
                />
              </>
            )}
          </div>
        </div>
      </Card>

      {/* 404 Page */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('404 Error Page', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <Input
            label={__('404 Title', 'prorank-seo')}
            value={settings.error_404_title || 'Page Not Found %sep% %sitename%'}
            onChange={(value) => updateSetting('error_404_title', value)}
            help={__('Title tag on 404 Not Found error page', 'prorank-seo')}
          />
        </div>
      </Card>

      {/* Search Results */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Search Results Page', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <div className="pr:space-y-4">
            <Input
              label={__('Search Results Title', 'prorank-seo')}
              value={settings.search_title || '%search_query% %page% %sep% %sitename%'}
              onChange={(value) => updateSetting('search_title', value)}
              help={__('Title tag on search results page. Use %search_query%, %page%, %sep%, %sitename%', 'prorank-seo')}
            />
            <Checkbox
              label={__('Noindex Search Results', 'prorank-seo')}
              help={__('Prevent search results pages from being indexed. They could be considered thin content prone to duplicate issues.', 'prorank-seo')}
              checked={settings.noindex_search === true}
              onChange={(value) => updateSetting('noindex_search', value)}
            />
          </div>
        </div>
      </Card>

      {/* Pagination & Special Pages */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Pagination & Special Pages', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <div className="pr:space-y-4">
            <Checkbox
              label={__('Noindex Subpages', 'prorank-seo')}
              help={__('Prevent all paginated pages from getting indexed by search engines', 'prorank-seo')}
              checked={settings.noindex_subpages === true}
              onChange={(value) => updateSetting('noindex_subpages', value)}
            />
            <Checkbox
              label={__('Noindex Paginated Single Pages', 'prorank-seo')}
              help={__('Prevent paginated pages of single posts/pages from showing in search results. Also applies to Blog page.', 'prorank-seo')}
              checked={settings.noindex_paginated_singles === true}
              onChange={(value) => updateSetting('noindex_paginated_singles', value)}
            />
            <Checkbox
              label={__('Noindex Password Protected Pages', 'prorank-seo')}
              help={__('Prevent password protected pages & posts from getting indexed by search engines', 'prorank-seo')}
              checked={settings.noindex_password_protected === true}
              onChange={(value) => updateSetting('noindex_password_protected', value)}
            />
          </div>
        </div>
      </Card>

      {renderVariableReference()}
    </div>
  );

  const renderPostTypeSettings = (postType) => {
    const key = `post_type_${postType.slug}`;
    const typeSettings = settings[key] || {};

    return (
      <div className="pr:space-y-6">
        <Card>
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {postType.labels.name} {__('Settings', 'prorank-seo')}
            </h3>
          </div>
          <div className="pr:p-6">
            <div className="pr:space-y-6">
              <Input
                label={__('Single Title Template', 'prorank-seo')}
                value={typeSettings.single_title || '%title% %sep% %sitename%'}
                onChange={(value) => updateSetting(key, { ...typeSettings, single_title: value })}
                help={__('Title template for individual posts', 'prorank-seo')}
              />

              <div className="pr:space-y-2">
                <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                  {__('Single Description Template', 'prorank-seo')}
                </label>
                <textarea
                  className="pr:block pr:w-full pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:focus:outline-hidden pr:focus:ring-2 pr:focus:ring-primary-500 pr:focus:border-transparent"
                  rows={2}
                  value={typeSettings.single_description || '%excerpt%'}
                  onChange={(e) => updateSetting(key, { ...typeSettings, single_description: e.target.value })}
                />
                <p className="pr:text-xs pr:text-gray-500">
                  {__('Description template for individual posts', 'prorank-seo')}
                </p>
              </div>

              {postType.has_archive && (
                <>
                  <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                    <Input
                      label={__('Archive Title Template', 'prorank-seo')}
                      value={typeSettings.archive_title || `${postType.labels.name} %sep% %sitename%`}
                      onChange={(value) => updateSetting(key, { ...typeSettings, archive_title: value })}
                    />
                  </div>
                  <div className="pr:space-y-2">
                    <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                      {__('Archive Description', 'prorank-seo')}
                    </label>
                    <textarea
                      className="pr:block pr:w-full pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:focus:outline-hidden pr:focus:ring-2 pr:focus:ring-primary-500 pr:focus:border-transparent"
                      rows={2}
                      value={typeSettings.archive_description || ''}
                      onChange={(e) => updateSetting(key, { ...typeSettings, archive_description: e.target.value })}
                    />
                  </div>
                </>
              )}

              <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                <Select
                  label={__('Schema Type', 'prorank-seo')}
                  value={typeSettings.schema_type || 'Article'}
                  options={[
                    { label: __('None', 'prorank-seo'), value: '' },
                    { label: __('Article', 'prorank-seo'), value: 'Article' },
                    { label: __('BlogPosting', 'prorank-seo'), value: 'BlogPosting' },
                    { label: __('NewsArticle', 'prorank-seo'), value: 'NewsArticle' },
                    { label: __('Product', 'prorank-seo'), value: 'Product' },
                    { label: __('Event', 'prorank-seo'), value: 'Event' },
                    { label: __('Course', 'prorank-seo'), value: 'Course' },
                    { label: __('JobPosting', 'prorank-seo'), value: 'JobPosting' },
                    { label: __('Recipe', 'prorank-seo'), value: 'Recipe' },
                    { label: __('FAQPage', 'prorank-seo'), value: 'FAQPage' },
                    { label: __('HowTo', 'prorank-seo'), value: 'HowTo' },
                    { label: __('Video', 'prorank-seo'), value: 'VideoObject' },
                  ]}
                  onChange={(value) => updateSetting(key, { ...typeSettings, schema_type: value })}
                />
              </div>

              {typeSettings.schema_type === 'Article' && (
                <Select
                  label={__('Article Type', 'prorank-seo')}
                  value={typeSettings.article_type || 'Article'}
                  options={[
                    { label: __('Article', 'prorank-seo'), value: 'Article' },
                    { label: __('Blog Post', 'prorank-seo'), value: 'BlogPosting' },
                    { label: __('News Article', 'prorank-seo'), value: 'NewsArticle' },
                  ]}
                  onChange={(value) => updateSetting(key, { ...typeSettings, article_type: value })}
                />
              )}

              <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-4">
                  {__('Robots Meta', 'prorank-seo')}
                </h4>
                <Select
                  label={__('Robots Meta', 'prorank-seo')}
                  value={typeSettings.robots || 'default'}
                  options={[
                    { label: __('Use Default', 'prorank-seo'), value: 'default' },
                    { label: __('Custom', 'prorank-seo'), value: 'custom' },
                  ]}
                  onChange={(value) => updateSetting(key, { ...typeSettings, robots: value })}
                />

                {typeSettings.robots === 'custom' && (
                  <div className="pr:mt-4 pr:space-y-3">
                    <Checkbox
                      label={__('Noindex', 'prorank-seo')}
                      checked={typeSettings.noindex === true}
                      onChange={(value) => updateSetting(key, { ...typeSettings, noindex: value })}
                    />
                    <Checkbox
                      label={__('Nofollow', 'prorank-seo')}
                      checked={typeSettings.nofollow === true}
                      onChange={(value) => updateSetting(key, { ...typeSettings, nofollow: value })}
                    />
                    <Checkbox
                      label={__('Noarchive', 'prorank-seo')}
                      checked={typeSettings.noarchive === true}
                      onChange={(value) => updateSetting(key, { ...typeSettings, noarchive: value })}
                    />
                    <Checkbox
                      label={__('Noimageindex', 'prorank-seo')}
                      checked={typeSettings.noimageindex === true}
                      onChange={(value) => updateSetting(key, { ...typeSettings, noimageindex: value })}
                    />
                    <Checkbox
                      label={__('Nosnippet', 'prorank-seo')}
                      checked={typeSettings.nosnippet === true}
                      onChange={(value) => updateSetting(key, { ...typeSettings, nosnippet: value })}
                    />
                  </div>
                )}
              </div>

              <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                <div className="pr:space-y-4">
                  <Toggle
                    label={__('Show SEO Meta Box', 'prorank-seo')}
                    help={__('Display SEO controls in the editor for this post type', 'prorank-seo')}
                    checked={typeSettings.show_meta_box !== false}
                    onChange={(value) => updateSetting(key, { ...typeSettings, show_meta_box: value })}
                  />

                  <Toggle
                    label={__('Enable Bulk Editing', 'prorank-seo')}
                    help={__('Allow bulk editing of SEO data in list view', 'prorank-seo')}
                    checked={typeSettings.bulk_editing === true}
                    onChange={(value) => updateSetting(key, { ...typeSettings, bulk_editing: value })}
                  />
                </div>
              </div>
            </div>
          </div>
        </Card>
        {renderVariableReference()}
      </div>
    );
  };

  const renderTaxonomySettings = (taxonomy) => {
    const key = `taxonomy_${taxonomy.slug}`;
    const taxSettings = settings[key] || {};

    return (
      <div className="pr:space-y-6">
        <Card>
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {taxonomy.labels.name} {__('Settings', 'prorank-seo')}
            </h3>
          </div>
          <div className="pr:p-6">
            <div className="pr:space-y-6">
              <Input
                label={__('Archive Title Template', 'prorank-seo')}
                value={taxSettings.archive_title || '%term% %sep% %sitename%'}
                onChange={(value) => updateSetting(key, { ...taxSettings, archive_title: value })}
              />

              <div className="pr:space-y-2">
                <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                  {__('Archive Description Template', 'prorank-seo')}
                </label>
                <textarea
                  className="pr:block pr:w-full pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:focus:outline-hidden pr:focus:ring-2 pr:focus:ring-primary-500 pr:focus:border-transparent"
                  rows={2}
                  value={taxSettings.archive_description || '%term_description%'}
                  onChange={(e) => updateSetting(key, { ...taxSettings, archive_description: e.target.value })}
                />
              </div>

              <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-4">
                  {__('Robots Meta', 'prorank-seo')}
                </h4>
                <Select
                  label={__('Robots Meta', 'prorank-seo')}
                  value={taxSettings.robots || 'default'}
                  options={[
                    { label: __('Use Global Default', 'prorank-seo'), value: 'default' },
                    { label: __('Custom', 'prorank-seo'), value: 'custom' },
                  ]}
                  onChange={(value) => updateSetting(key, { ...taxSettings, robots: value })}
                />

                {taxSettings.robots === 'custom' && (
                  <div className="pr:mt-4 pr:space-y-3">
                    <Checkbox
                      label={__('Noindex', 'prorank-seo')}
                      checked={taxSettings.noindex === true}
                      onChange={(value) => updateSetting(key, { ...taxSettings, noindex: value })}
                    />
                    <Checkbox
                      label={__('Nofollow', 'prorank-seo')}
                      checked={taxSettings.nofollow === true}
                      onChange={(value) => updateSetting(key, { ...taxSettings, nofollow: value })}
                    />
                  </div>
                )}
              </div>

              <div className="pr:border-t pr:border-gray-200 pr:pt-6">
                <div className="pr:space-y-4">
                  <Toggle
                    label={__('Show SEO Controls', 'prorank-seo')}
                    help={__('Add SEO fields to term edit pages', 'prorank-seo')}
                    checked={taxSettings.show_seo_controls !== false}
                    onChange={(value) => updateSetting(key, { ...taxSettings, show_seo_controls: value })}
                  />
                </div>
              </div>
            </div>
          </div>
        </Card>
        {renderVariableReference()}
      </div>
    );
  };

  if (loading) {
    return <LoadingState message={__('Loading settings...', 'prorank-seo')} />;
  }

  // Build tabs - Fixed order with specific post types and taxonomies
  const tabs = [
    { name: 'global-meta', title: __('Global Meta', 'prorank-seo') },
    { name: 'homepage', title: __('Homepage', 'prorank-seo') },
    { name: 'authors', title: __('Authors', 'prorank-seo') },
    { name: 'misc-pages', title: __('Misc Pages', 'prorank-seo') },
  ];

  // Add specific post types in order
  const postTypeOrder = SEO_PRIMARY_POST_TYPE_ORDER;
  const postTypeLabels = {
    'post': __('Posts', 'prorank-seo'),
    'page': __('Pages', 'prorank-seo'),
    'attachment': __('Media', 'prorank-seo'),
    'product': __('Products', 'prorank-seo'),
    'sc_product': __('SureCart Product', 'prorank-seo'),
    'prorank_podcast': __('Podcast Episodes', 'prorank-seo'),
  };

  postTypeOrder.forEach(slug => {
    const postType = postTypes.find(pt => pt.slug === slug);
    if (postType) {
      tabs.push({
        name: `post-type-${slug}`,
        title: postTypeLabels[slug] || postType.labels.name,
      });
    }
  });

  // Add any other post types not in the order list
  postTypes.forEach(postType => {
    if (!postTypeOrder.includes(postType.slug)) {
      tabs.push({
        name: `post-type-${postType.slug}`,
        title: postType.labels.name,
      });
    }
  });

  // Add taxonomy tabs
  taxonomies.forEach(taxonomy => {
    tabs.push({
      name: `taxonomy-${taxonomy.slug}`,
      title: taxonomy.labels.name,
    });
  });

  const renderTabContent = () => {
    if (activeTab === 'global-meta') return renderGlobalMeta();
    if (activeTab === 'homepage') return renderHomepage();
    if (activeTab === 'authors') return renderAuthors();
    if (activeTab === 'misc-pages') return renderMiscPages();

    if (activeTab.startsWith('post-type-')) {
      const slug = activeTab.replace('post-type-', '');
      const postType = postTypes.find(pt => pt.slug === slug);
      return postType ? renderPostTypeSettings(postType) : null;
    }

    if (activeTab.startsWith('taxonomy-')) {
      const slug = activeTab.replace('taxonomy-', '');
      const taxonomy = taxonomies.find(tx => tx.slug === slug);
      return taxonomy ? renderTaxonomySettings(taxonomy) : null;
    }

    return null;
  };

  return (
    <div className="pr:space-y-6">
      {notice && (
        <Alert
          variant={notice.type}
          onDismiss={() => setNotice(null)}
        >
          {notice.message}
        </Alert>
      )}

      {/* Tab Navigation */}
      <div className="pr:bg-white pr:rounded-lg pr:shadow-card pr:overflow-hidden">
        <div className="pr:border-b pr:border-gray-200 pr:overflow-x-auto">
          <nav className="pr:flex pr:gap-0 pr:min-w-max" aria-label="Tabs">
            {tabs.map((tab) => (
              <button
                key={tab.name}
                onClick={() => {
                  setActiveTab(tab.name);
                  window.scrollTo(0, 0);
                }}
                className={`
                  pr:px-6 pr:py-4 pr:text-sm pr:font-medium pr:whitespace-nowrap pr:border-b-2 pr:transition-colors
                  ${
                    activeTab === tab.name
                      ? 'pr:border-primary-500 pr:text-primary-600 pr:bg-primary-50'
                      : 'pr:border-transparent pr:text-gray-600 pr:hover:text-gray-900 pr:hover:border-gray-300'
                  }
                `}
                aria-current={activeTab === tab.name ? 'page' : undefined}
              >
                {tab.title}
              </button>
            ))}
          </nav>
        </div>

        {/* Tab Content */}
        <div className="pr:p-6">
          {renderTabContent()}
        </div>
      </div>

      {/* Action Buttons */}
      <div className="pr:flex pr:items-center pr:justify-between pr:p-6 pr:bg-white pr:rounded-lg pr:shadow-card pr:sticky pr:bottom-6">
        <Button
          variant="link"
          onClick={resetSettings}
          className="pr:text-error-500 pr:hover:text-error-600"
        >
          {__('Reset to Defaults', 'prorank-seo')}
        </Button>
        <Button
          variant="primary"
          onClick={saveSettings}
          loading={saving}
        >
          {saving ? __('Saving...', 'prorank-seo') : __('Save Changes', 'prorank-seo')}
        </Button>
      </div>
    </div>
  );
};

export default TitleMetaSettings;
