/**
 * Schema Targeting - Step 2 of Schema Wizard
 * Configure where the schema should be applied
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import {
  LightBulbIcon,
  GlobeAltIcon,
  DocumentTextIcon
} from '@heroicons/react/24/outline';
import { Button, Input, Select, Checkbox, Alert, Card } from '../../../../components/ui';
import LoadingState from '../../../../components/LoadingState';

const SchemaTargeting = ({ targeting, onUpdateTargeting, schemaType }) => {
  const [postTypes, setPostTypes] = useState([]);
  const [categories, setCategories] = useState([]);
  const [tags, setTags] = useState([]);
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [targetingMode, setTargetingMode] = useState(targeting.mode || 'auto');
  const [customRule, setCustomRule] = useState({ field: '', operator: 'equals', value: '' });
  const [excludeRule, setExcludeRule] = useState({ field: '', operator: 'equals', value: '' });

  // Load WordPress data
  useEffect(() => {
    loadWordPressData();
  }, []);

  const loadWordPressData = async () => {
    try {
      // Load post types
      const typesResponse = await apiFetch({ path: '/wp/v2/types' });
      const types = Object.keys(typesResponse).map(key => ({
        label: typesResponse[key].name,
        value: key,
        public: typesResponse[key].public
      })).filter(type => type.public);
      setPostTypes(types);

      // Load categories
      try {
        const categoriesResponse = await apiFetch({ path: '/wp/v2/categories?per_page=100' });
        setCategories(categoriesResponse.map(cat => ({
          label: cat.name,
          value: cat.id,
          slug: cat.slug
        })));
      } catch (e) {
        // Categories not available
      }

      // Load tags
      try {
        const tagsResponse = await apiFetch({ path: '/wp/v2/tags?per_page=100' });
        setTags(tagsResponse.map(tag => ({
          label: tag.name,
          value: tag.id,
          slug: tag.slug
        })));
      } catch (e) {
        // Tags not available
      }

      // Load user roles
      try {
        const rolesResponse = await apiFetch({ path: '/prorank-seo/v1/schema/user-roles' });
        if (Array.isArray(rolesResponse)) {
          setRoles(rolesResponse);
        }
      } catch (e) {
        // Roles not available
      }
    } catch (error) {
      // Failed to load WordPress data
    } finally {
      setLoading(false);
    }
  };

  const updateTargeting = (field, value) => {
    const newTargeting = { ...targeting, [field]: value };
    onUpdateTargeting(newTargeting);
  };

  const togglePostType = (postType) => {
    const current = targeting.postTypes || [];
    const updated = current.includes(postType)
      ? current.filter(pt => pt !== postType)
      : [...current, postType];
    updateTargeting('postTypes', updated);
  };

  const updateExclude = (field, value) => {
    const currentExclude = targeting.exclude || {};
    updateTargeting('exclude', { ...currentExclude, [field]: value });
  };

  const toggleExcludePostType = (postType) => {
    const current = (targeting.exclude?.postTypes) || [];
    const updated = current.includes(postType)
      ? current.filter(pt => pt !== postType)
      : [...current, postType];
    updateExclude('postTypes', updated);
  };

  const toggleExcludeCategory = (categoryId) => {
    const current = (targeting.exclude?.categories) || [];
    const updated = current.includes(categoryId)
      ? current.filter(cat => cat !== categoryId)
      : [...current, categoryId];
    updateExclude('categories', updated);
  };

  const toggleExcludeTag = (tagId) => {
    const current = (targeting.exclude?.tags) || [];
    const updated = current.includes(tagId)
      ? current.filter(tag => tag !== tagId)
      : [...current, tagId];
    updateExclude('tags', updated);
  };

  const toggleUserRole = (roleKey) => {
    const current = targeting.userRoles || [];
    const updated = current.includes(roleKey)
      ? current.filter(role => role !== roleKey)
      : [...current, roleKey];
    updateTargeting('userRoles', updated);
  };

  const toggleCategory = (categoryId) => {
    const current = targeting.categories || [];
    const updated = current.includes(categoryId)
      ? current.filter(cat => cat !== categoryId)
      : [...current, categoryId];
    updateTargeting('categories', updated);
  };

  const toggleTag = (tagId) => {
    const current = targeting.tags || [];
    const updated = current.includes(tagId)
      ? current.filter(tag => tag !== tagId)
      : [...current, tagId];
    updateTargeting('tags', updated);
  };

  const addCustomRule = () => {
    if (customRule.field && customRule.value) {
      const rules = targeting.rules || [];
      updateTargeting('rules', [...rules, { ...customRule, id: Date.now() }]);
      setCustomRule({ field: '', operator: 'equals', value: '' });
    }
  };

  const addExcludeRule = () => {
    if (excludeRule.field && excludeRule.value) {
      const rules = targeting.exclude?.rules || [];
      updateExclude('rules', [...rules, { ...excludeRule, id: Date.now() }]);
      setExcludeRule({ field: '', operator: 'equals', value: '' });
    }
  };

  const removeExcludeRule = (ruleId) => {
    const rules = targeting.exclude?.rules || [];
    updateExclude('rules', rules.filter(rule => rule.id !== ruleId));
  };

  const removeCustomRule = (ruleId) => {
    const rules = targeting.rules || [];
    updateTargeting('rules', rules.filter(rule => rule.id !== ruleId));
  };

  // Get smart targeting suggestions based on schema type
  const getSmartSuggestions = () => {
    const suggestions = {
      Product: {
        postTypes: ['product'],
        message: __('Recommended: Apply to all WooCommerce products', 'prorank-seo')
      },
      Article: {
        postTypes: ['post'],
        message: __('Recommended: Apply to all blog posts', 'prorank-seo')
      },
      BlogPosting: {
        postTypes: ['post'],
        message: __('Recommended: Apply to all blog posts', 'prorank-seo')
      },
      Event: {
        postTypes: ['event', 'tribe_events'],
        message: __('Recommended: Apply to event post types', 'prorank-seo')
      },
      Recipe: {
        postTypes: ['recipe', 'post'],
        categories: ['recipes'],
        message: __('Recommended: Apply to recipe posts or posts in recipe category', 'prorank-seo')
      },
      JobPosting: {
        postTypes: ['job_listing', 'job'],
        message: __('Recommended: Apply to job listing post types', 'prorank-seo')
      },
      LocalBusiness: {
        postTypes: ['page'],
        message: __('Recommended: Apply to location or contact pages', 'prorank-seo')
      },
      FAQPage: {
        postTypes: ['page'],
        message: __('Recommended: Apply to FAQ pages', 'prorank-seo')
      },
      Service: {
        postTypes: ['service', 'page'],
        message: __('Recommended: Apply to service pages', 'prorank-seo')
      }
    };

    return suggestions[schemaType] || null;
  };

  const applySuggestion = (suggestion) => {
    if (suggestion.postTypes) {
      updateTargeting('postTypes', suggestion.postTypes);
    }
    if (suggestion.categories) {
      // Find category IDs from suggested category slugs
      const categoryIds = categories
        .filter(cat => suggestion.categories.includes(cat.slug))
        .map(cat => cat.value);
      updateTargeting('categories', categoryIds);
    }
  };

  const suggestion = getSmartSuggestions();

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

  return (
    <div className="pr:space-y-6">
      {/* Header */}
      <div>
        <h3 className="pr:text-xl pr:font-semibold pr:text-gray-900 pr:mb-2">
          {__('Step 2: Choose Where to Apply This Schema', 'prorank-seo')}
        </h3>
        <p className="pr:text-sm pr:text-gray-600">
          {__('Configure where this schema markup should be applied on your website. You can target specific post types, categories, tags, or create custom rules.', 'prorank-seo')}
        </p>
      </div>

      {/* Smart Suggestion */}
      {suggestion && (
        <Alert variant="info" icon={LightBulbIcon}>
          <div className="pr:flex pr:items-center pr:justify-between pr:gap-4">
            <p className="pr:flex-1">{suggestion.message}</p>
            <Button
              variant="link"
              size="sm"
              onClick={() => applySuggestion(suggestion)}
            >
              {__('Apply Recommendation', 'prorank-seo')}
            </Button>
          </div>
        </Alert>
      )}

      {/* Targeting Mode Selection */}
      <Card>
        <div className="pr:space-y-4">
          <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
            {__('Targeting Mode', 'prorank-seo')}
          </h4>
          <div className="pr:space-y-3">
            <label className="pr:flex pr:items-start pr:gap-3 pr:cursor-pointer pr:p-4 pr:border pr:border-gray-200 pr:rounded-lg pr:hover:bg-gray-50 pr:transition-colors">
              <input
                type="radio"
                name="targetingMode"
                value="auto"
                checked={targetingMode === 'auto'}
                onChange={(e) => {
                  setTargetingMode(e.target.value);
                  updateTargeting('mode', e.target.value);
                }}
                className="pr:mt-1 pr:w-4 pr:h-4 pr:text-primary-500 pr:border-gray-300 pr:focus:ring-2 pr:focus:ring-primary-500"
              />
              <div className="pr:flex-1">
                <div className="pr:text-sm pr:font-medium pr:text-gray-900">
                  {__('Automatic (Smart Detection)', 'prorank-seo')}
                </div>
                <div className="pr:text-xs pr:text-gray-500 pr:mt-1">
                  {__('ProRank will automatically detect and apply schema to appropriate content', 'prorank-seo')}
                </div>
              </div>
            </label>

            <label className="pr:flex pr:items-start pr:gap-3 pr:cursor-pointer pr:p-4 pr:border pr:border-gray-200 pr:rounded-lg pr:hover:bg-gray-50 pr:transition-colors">
              <input
                type="radio"
                name="targetingMode"
                value="manual"
                checked={targetingMode === 'manual'}
                onChange={(e) => {
                  setTargetingMode(e.target.value);
                  updateTargeting('mode', e.target.value);
                }}
                className="pr:mt-1 pr:w-4 pr:h-4 pr:text-primary-500 pr:border-gray-300 pr:focus:ring-2 pr:focus:ring-primary-500"
              />
              <div className="pr:flex-1">
                <div className="pr:text-sm pr:font-medium pr:text-gray-900">
                  {__('Manual Selection', 'prorank-seo')}
                </div>
                <div className="pr:text-xs pr:text-gray-500 pr:mt-1">
                  {__('Choose specific post types, categories, and tags', 'prorank-seo')}
                </div>
              </div>
            </label>

            <label className="pr:flex pr:items-start pr:gap-3 pr:cursor-pointer pr:p-4 pr:border pr:border-gray-200 pr:rounded-lg pr:hover:bg-gray-50 pr:transition-colors">
              <input
                type="radio"
                name="targetingMode"
                value="advanced"
                checked={targetingMode === 'advanced'}
                onChange={(e) => {
                  setTargetingMode(e.target.value);
                  updateTargeting('mode', e.target.value);
                }}
                className="pr:mt-1 pr:w-4 pr:h-4 pr:text-primary-500 pr:border-gray-300 pr:focus:ring-2 pr:focus:ring-primary-500"
              />
              <div className="pr:flex-1">
                <div className="pr:text-sm pr:font-medium pr:text-gray-900">
                  {__('Advanced Rules', 'prorank-seo')}
                </div>
                <div className="pr:text-xs pr:text-gray-500 pr:mt-1">
                  {__('Create custom targeting rules based on conditions', 'prorank-seo')}
                </div>
              </div>
            </label>
          </div>
        </div>
      </Card>

      {/* User Role Targeting */}
      {roles.length > 0 && (
        <Card>
          <div className="pr:space-y-4">
            <div>
              <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                {__('User Role Targeting', 'prorank-seo')}
              </h4>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Limit schema output to visitors with specific roles (optional).', 'prorank-seo')}
              </p>
            </div>
            <div className="pr:space-y-3">
              {roles.map(role => (
                <Checkbox
                  key={role.key}
                  label={role.label}
                  checked={(targeting.userRoles || []).includes(role.key)}
                  onChange={() => toggleUserRole(role.key)}
                />
              ))}
            </div>
          </div>
        </Card>
      )}

      {/* Automatic Targeting Info */}
      {targetingMode === 'auto' && (
        <Alert variant="info" icon={LightBulbIcon}>
          <div>
            <h4 className="pr:font-medium pr:mb-1">
              {__('Automatic Targeting Enabled', 'prorank-seo')}
            </h4>
            <p>
              {__('ProRank SEO will automatically detect and apply this schema to appropriate content based on your schema type and content analysis.', 'prorank-seo')}
            </p>
          </div>
        </Alert>
      )}

      {/* Manual Targeting */}
      {targetingMode === 'manual' && (
        <div className="pr:space-y-6">
          {/* Post Types */}
          <Card>
            <div className="pr:space-y-4">
              <div>
                <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                  {__('Post Types', 'prorank-seo')}
                </h4>
                <p className="pr:text-sm pr:text-gray-600">
                  {__('Select which post types should use this schema.', 'prorank-seo')}
                </p>
              </div>
              <div className="pr:space-y-3">
                {postTypes.map(postType => (
                  <Checkbox
                    key={postType.value}
                    label={postType.label}
                    checked={(targeting.postTypes || []).includes(postType.value)}
                    onChange={() => togglePostType(postType.value)}
                  />
                ))}
              </div>
            </div>
          </Card>

          {/* Categories */}
          {categories.length > 0 && (
            <Card>
              <div className="pr:space-y-4">
                <div>
                  <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                    {__('Categories', 'prorank-seo')}
                  </h4>
                  <p className="pr:text-sm pr:text-gray-600">
                    {__('Apply schema to posts in these categories.', 'prorank-seo')}
                  </p>
                </div>
                <div className="pr:space-y-3 pr:max-h-64 pr:overflow-y-auto pr:pr-2">
                  {categories.map(category => (
                    <Checkbox
                      key={category.value}
                      label={category.label}
                      checked={(targeting.categories || []).includes(category.value)}
                      onChange={() => toggleCategory(category.value)}
                    />
                  ))}
                </div>
              </div>
            </Card>
          )}

          {/* Tags */}
          {tags.length > 0 && (
            <Card>
              <div className="pr:space-y-4">
                <div>
                  <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                    {__('Tags', 'prorank-seo')}
                  </h4>
                  <p className="pr:text-sm pr:text-gray-600">
                    {__('Apply schema to posts with these tags.', 'prorank-seo')}
                  </p>
                </div>
                <div className="pr:space-y-3 pr:max-h-64 pr:overflow-y-auto pr:pr-2">
                  {tags.map(tag => (
                    <Checkbox
                      key={tag.value}
                      label={tag.label}
                      checked={(targeting.tags || []).includes(tag.value)}
                      onChange={() => toggleTag(tag.value)}
                    />
                  ))}
                </div>
              </div>
            </Card>
          )}

          {/* Specific Pages */}
          <Card>
            <div className="pr:space-y-4">
              <div>
                <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                  {__('Specific Pages/Posts', 'prorank-seo')}
                </h4>
                <p className="pr:text-sm pr:text-gray-600">
                  {__('Enter post/page IDs separated by commas.', 'prorank-seo')}
                </p>
              </div>
              <Input
                value={(targeting.specific || []).join(', ')}
                onChange={(value) => {
                  const ids = value.split(',').map(id => id.trim()).filter(id => id);
                  updateTargeting('specific', ids);
                }}
                placeholder={__('e.g., 123, 456, 789', 'prorank-seo')}
              />
            </div>
          </Card>

          {/* Exclusions */}
          <Card>
            <div className="pr:space-y-4">
              <div>
                <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                  {__('Exclusions', 'prorank-seo')}
                </h4>
                <p className="pr:text-sm pr:text-gray-600">
                  {__('Do not apply schema on these content types or specific IDs.', 'prorank-seo')}
                </p>
              </div>

              <div className="pr:space-y-3">
                <p className="pr:text-sm pr:font-medium pr:text-gray-700">
                  {__('Exclude Post Types', 'prorank-seo')}
                </p>
                {postTypes.map(postType => (
                  <Checkbox
                    key={`exclude-${postType.value}`}
                    label={postType.label}
                    checked={(targeting.exclude?.postTypes || []).includes(postType.value)}
                    onChange={() => toggleExcludePostType(postType.value)}
                  />
                ))}
              </div>

              {categories.length > 0 && (
                <div className="pr:space-y-3">
                  <p className="pr:text-sm pr:font-medium pr:text-gray-700">
                    {__('Exclude Categories', 'prorank-seo')}
                  </p>
                  <div className="pr:space-y-2 pr:max-h-48 pr:overflow-y-auto pr:pr-2">
                    {categories.map(category => (
                      <Checkbox
                        key={`exclude-cat-${category.value}`}
                        label={category.label}
                        checked={(targeting.exclude?.categories || []).includes(category.value)}
                        onChange={() => toggleExcludeCategory(category.value)}
                      />
                    ))}
                  </div>
                </div>
              )}

              {tags.length > 0 && (
                <div className="pr:space-y-3">
                  <p className="pr:text-sm pr:font-medium pr:text-gray-700">
                    {__('Exclude Tags', 'prorank-seo')}
                  </p>
                  <div className="pr:space-y-2 pr:max-h-48 pr:overflow-y-auto pr:pr-2">
                    {tags.map(tag => (
                      <Checkbox
                        key={`exclude-tag-${tag.value}`}
                        label={tag.label}
                        checked={(targeting.exclude?.tags || []).includes(tag.value)}
                        onChange={() => toggleExcludeTag(tag.value)}
                      />
                    ))}
                  </div>
                </div>
              )}

              <div className="pr:space-y-2">
                <p className="pr:text-sm pr:font-medium pr:text-gray-700">
                  {__('Exclude Specific IDs', 'prorank-seo')}
                </p>
                <Input
                  value={(targeting.exclude?.specific || []).join(', ')}
                  onChange={(value) => {
                    const ids = value.split(',').map(id => id.trim()).filter(id => id);
                    updateExclude('specific', ids);
                  }}
                  placeholder={__('e.g., 123, 456', 'prorank-seo')}
                />
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* Advanced Targeting */}
      {targetingMode === 'advanced' && (
        <Card>
          <div className="pr:space-y-4">
            <div>
              <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                {__('Custom Rules', 'prorank-seo')}
              </h4>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Create advanced targeting rules based on custom conditions.', 'prorank-seo')}
              </p>
            </div>

            {/* Rule Builder */}
            <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-12 pr:gap-4 pr:p-4 pr:bg-gray-50 pr:rounded-lg">
              <div className="pr:md:col-span-4">
                <Select
                  label={__('Field', 'prorank-seo')}
                  value={customRule.field}
                  onChange={(value) => setCustomRule({ ...customRule, field: value })}
                  options={[
                    { label: __('Select field...', 'prorank-seo'), value: '' },
                    { label: __('Post Title', 'prorank-seo'), value: 'post_title' },
                    { label: __('Post URL', 'prorank-seo'), value: 'post_url' },
                    { label: __('Post Author', 'prorank-seo'), value: 'post_author' },
                    { label: __('Custom Field', 'prorank-seo'), value: 'custom_field' },
                    { label: __('Post Template', 'prorank-seo'), value: 'template' },
                    { label: __('Post Status', 'prorank-seo'), value: 'post_status' },
                    { label: __('Post Type', 'prorank-seo'), value: 'post_type' }
                  ]}
                />
              </div>
              <div className="pr:md:col-span-3">
                <Select
                  label={__('Operator', 'prorank-seo')}
                  value={customRule.operator}
                  onChange={(value) => setCustomRule({ ...customRule, operator: value })}
                  options={[
                    { label: __('Equals', 'prorank-seo'), value: 'equals' },
                    { label: __('Contains', 'prorank-seo'), value: 'contains' },
                    { label: __('Starts with', 'prorank-seo'), value: 'starts_with' },
                    { label: __('Ends with', 'prorank-seo'), value: 'ends_with' },
                    { label: __('Does not equal', 'prorank-seo'), value: 'not_equals' }
                  ]}
                />
              </div>
              <div className="pr:md:col-span-3">
                <Input
                  label={__('Value', 'prorank-seo')}
                  value={customRule.value}
                  onChange={(value) => setCustomRule({ ...customRule, value })}
                  placeholder={__('Enter value...', 'prorank-seo')}
                />
              </div>
              <div className="pr:md:col-span-2 pr:flex pr:items-end">
                <Button
                  variant="secondary"
                  onClick={addCustomRule}
                  disabled={!customRule.field || !customRule.value}
                  fullWidth
                >
                  {__('Add', 'prorank-seo')}
                </Button>
              </div>
            </div>

            {/* Active Rules */}
            {(targeting.rules || []).length > 0 && (
              <div className="pr:space-y-2">
                <h5 className="pr:text-sm pr:font-medium pr:text-gray-900">
                  {__('Active Rules:', 'prorank-seo')}
                </h5>
                {targeting.rules.map(rule => (
                  <div
                    key={rule.id}
                    className="pr:flex pr:items-center pr:justify-between pr:p-3 pr:bg-gray-50 pr:rounded-lg pr:border pr:border-gray-200"
                  >
                    <span className="pr:text-sm pr:text-gray-700">
                      <span className="pr:font-medium">{rule.field}</span> {rule.operator} "{rule.value}"
                    </span>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => removeCustomRule(rule.id)}
                    >
                      {__('Remove', 'prorank-seo')}
                    </Button>
                  </div>
                ))}
              </div>
            )}

            {/* Exclusion Rules */}
            <div className="pr:pt-4 pr:border-t pr:border-gray-200">
              <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-2">
                {__('Exclude When', 'prorank-seo')}
              </h4>
              <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
                {__('If any exclusion rule matches, schema will not be output.', 'prorank-seo')}
              </p>

              <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-12 pr:gap-4 pr:p-4 pr:bg-gray-50 pr:rounded-lg">
                <div className="pr:md:col-span-4">
                  <Select
                    label={__('Field', 'prorank-seo')}
                    value={excludeRule.field}
                    onChange={(value) => setExcludeRule({ ...excludeRule, field: value })}
                    options={[
                      { label: __('Select field...', 'prorank-seo'), value: '' },
                      { label: __('Post Title', 'prorank-seo'), value: 'post_title' },
                      { label: __('Post URL', 'prorank-seo'), value: 'post_url' },
                      { label: __('Post Author', 'prorank-seo'), value: 'post_author' },
                      { label: __('Custom Field', 'prorank-seo'), value: 'custom_field' },
                      { label: __('Post Template', 'prorank-seo'), value: 'template' },
                      { label: __('Post Status', 'prorank-seo'), value: 'post_status' },
                      { label: __('Post Type', 'prorank-seo'), value: 'post_type' }
                    ]}
                  />
                </div>
                <div className="pr:md:col-span-3">
                  <Select
                    label={__('Operator', 'prorank-seo')}
                    value={excludeRule.operator}
                    onChange={(value) => setExcludeRule({ ...excludeRule, operator: value })}
                    options={[
                      { label: __('Equals', 'prorank-seo'), value: 'equals' },
                      { label: __('Contains', 'prorank-seo'), value: 'contains' },
                      { label: __('Starts with', 'prorank-seo'), value: 'starts_with' },
                      { label: __('Ends with', 'prorank-seo'), value: 'ends_with' },
                      { label: __('Does not equal', 'prorank-seo'), value: 'not_equals' }
                    ]}
                  />
                </div>
                <div className="pr:md:col-span-3">
                  <Input
                    label={__('Value', 'prorank-seo')}
                    value={excludeRule.value}
                    onChange={(value) => setExcludeRule({ ...excludeRule, value })}
                    placeholder={__('Enter value...', 'prorank-seo')}
                  />
                </div>
                <div className="pr:md:col-span-2 pr:flex pr:items-end">
                  <Button
                    variant="secondary"
                    onClick={addExcludeRule}
                    disabled={!excludeRule.field || !excludeRule.value}
                    fullWidth
                  >
                    {__('Add', 'prorank-seo')}
                  </Button>
                </div>
              </div>

              {(targeting.exclude?.rules || []).length > 0 && (
                <div className="pr:space-y-2 pr:mt-4">
                  <h5 className="pr:text-sm pr:font-medium pr:text-gray-900">
                    {__('Active Exclusions:', 'prorank-seo')}
                  </h5>
                  {(targeting.exclude?.rules || []).map(rule => (
                    <div
                      key={`exclude-${rule.id}`}
                      className="pr:flex pr:items-center pr:justify-between pr:p-3 pr:bg-gray-50 pr:rounded-lg pr:border pr:border-gray-200"
                    >
                      <span className="pr:text-sm pr:text-gray-700">
                        <span className="pr:font-medium">{rule.field}</span> {rule.operator} "{rule.value}"
                      </span>
                      <Button
                        variant="danger"
                        size="sm"
                        onClick={() => removeExcludeRule(rule.id)}
                      >
                        {__('Remove', 'prorank-seo')}
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </Card>
      )}

      {/* Targeting Summary */}
      <Card variant="elevated" className="pr:bg-primary-50 pr:border-primary-200">
        <div className="pr:space-y-3">
          <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
            {__('Targeting Summary', 'prorank-seo')}
          </h4>
          <div className="pr:space-y-2">
            {targetingMode === 'auto' && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <GlobeAltIcon className="pr:w-4 pr:h-4 pr:text-success-500" />
                <span>{__('Automatic targeting enabled - ProRank will handle everything', 'prorank-seo')}</span>
              </div>
            )}
            {(targeting.postTypes || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-primary-500" />
                <span>{__('Post Types:', 'prorank-seo')} {targeting.postTypes.join(', ')}</span>
              </div>
            )}
            {(targeting.categories || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-primary-500" />
                <span>{__('Categories:', 'prorank-seo')} {targeting.categories.length} {__('selected', 'prorank-seo')}</span>
              </div>
            )}
            {(targeting.tags || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-primary-500" />
                <span>{__('Tags:', 'prorank-seo')} {targeting.tags.length} {__('selected', 'prorank-seo')}</span>
              </div>
            )}
            {(targeting.specific || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-primary-500" />
                <span>{__('Specific IDs:', 'prorank-seo')} {targeting.specific.join(', ')}</span>
              </div>
            )}
            {(targeting.rules || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-primary-500" />
                <span>{__('Custom Rules:', 'prorank-seo')} {targeting.rules.length} {__('rules', 'prorank-seo')}</span>
              </div>
            )}
            {(targeting.userRoles || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-primary-500" />
                <span>{__('User Roles:', 'prorank-seo')} {targeting.userRoles.join(', ')}</span>
              </div>
            )}
            {(targeting.exclude?.postTypes || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-red-500" />
                <span>{__('Excluded Post Types:', 'prorank-seo')} {targeting.exclude.postTypes.join(', ')}</span>
              </div>
            )}
            {(targeting.exclude?.categories || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-red-500" />
                <span>{__('Excluded Categories:', 'prorank-seo')} {targeting.exclude.categories.length} {__('selected', 'prorank-seo')}</span>
              </div>
            )}
            {(targeting.exclude?.tags || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-red-500" />
                <span>{__('Excluded Tags:', 'prorank-seo')} {targeting.exclude.tags.length} {__('selected', 'prorank-seo')}</span>
              </div>
            )}
            {(targeting.exclude?.specific || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-red-500" />
                <span>{__('Excluded IDs:', 'prorank-seo')} {targeting.exclude.specific.join(', ')}</span>
              </div>
            )}
            {(targeting.exclude?.rules || []).length > 0 && (
              <div className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-gray-700">
                <DocumentTextIcon className="pr:w-4 pr:h-4 pr:text-red-500" />
                <span>{__('Exclusion Rules:', 'prorank-seo')} {targeting.exclude.rules.length} {__('rules', 'prorank-seo')}</span>
              </div>
            )}
          </div>
        </div>
      </Card>
    </div>
  );
};

export default SchemaTargeting;
