import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Button, Input, Select, Toggle, Alert, Card } from '../../../components/ui';
import LoadingState from '../../../components/LoadingState';
import { useNotification } from '../../../contexts/NotificationContext';
import { ArrowTopRightOnSquareIcon, DocumentTextIcon, ClipboardDocumentIcon } from '@heroicons/react/24/outline';

const PodcastSeoSettings = ({ moduleSlug }) => {
  const [settings, setSettings] = useState({
    podcast_title: '',
    podcast_subtitle: '',
    podcast_description: '',
    podcast_author: '',
    podcast_email: '',
    podcast_category: '',
    podcast_subcategory: '',
    podcast_explicit: 'no',
    podcast_language: '',
    podcast_copyright: '',
    podcast_image: '',
    podcast_owner_name: '',
    podcast_owner_email: '',
    enable_podcast_feed: false,
    podcast_feed_limit: '',
    enable_itunes_tags: true,
    podcast_redirect_feed: '',
    enable_transcripts: false,
    funding_url: '',
    feed_url: '',
  });

  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState('settings');
  const [validating, setValidating] = useState(false);
  const [validationResult, setValidationResult] = useState(null);
  const { showNotification } = useNotification();

  // Podcast categories from Apple Podcasts
  const podcastCategories = [
    { value: '', label: __('-- Select Category --', 'prorank-seo') },
    { value: 'Arts', label: __('Arts', 'prorank-seo') },
    { value: 'Business', label: __('Business', 'prorank-seo') },
    { value: 'Comedy', label: __('Comedy', 'prorank-seo') },
    { value: 'Education', label: __('Education', 'prorank-seo') },
    { value: 'Fiction', label: __('Fiction', 'prorank-seo') },
    { value: 'Government', label: __('Government', 'prorank-seo') },
    { value: 'Health & Fitness', label: __('Health & Fitness', 'prorank-seo') },
    { value: 'History', label: __('History', 'prorank-seo') },
    { value: 'Kids & Family', label: __('Kids & Family', 'prorank-seo') },
    { value: 'Leisure', label: __('Leisure', 'prorank-seo') },
    { value: 'Music', label: __('Music', 'prorank-seo') },
    { value: 'News', label: __('News', 'prorank-seo') },
    { value: 'Religion & Spirituality', label: __('Religion & Spirituality', 'prorank-seo') },
    { value: 'Science', label: __('Science', 'prorank-seo') },
    { value: 'Society & Culture', label: __('Society & Culture', 'prorank-seo') },
    { value: 'Sports', label: __('Sports', 'prorank-seo') },
    { value: 'Technology', label: __('Technology', 'prorank-seo') },
    { value: 'True Crime', label: __('True Crime', 'prorank-seo') },
    { value: 'TV & Film', label: __('TV & Film', 'prorank-seo') },
  ];

  useEffect(() => {
    fetchSettings();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const fetchSettings = async () => {
    setLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/podcast/settings',
      });
      if (response && response.success && response.data) {
        // Merge fetched settings with defaults, preserving any saved values
        setSettings((prevSettings) => ({
          ...prevSettings,
          ...response.data,
        }));
      } else {
        // If no settings exist, keep the default empty state
        // No podcast settings found, using defaults
      }
    } catch (error) {
      // Error loading podcast settings
      // Don't show error notification for expected 404s when settings don't exist yet
      if (error.code !== 'rest_no_route') {
        showNotification(__('Failed to load podcast settings', 'prorank-seo'), 'error');
      }
    } finally {
      setLoading(false);
    }
  };

  const saveSettings = async () => {
    setSaving(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/podcast/settings',
        method: 'POST',
        data: { settings },
      });
      
      if (response && response.success) {
        showNotification(__('Podcast settings saved successfully!', 'prorank-seo'), 'success');
        
        // Reload settings to confirm they were saved
        await fetchSettings();
      } else {
        throw new Error(response?.message || 'Unknown error');
      }
    } catch (error) {
      // Error saving podcast settings
      showNotification(
        error.message || __('Failed to save podcast settings', 'prorank-seo'), 
        'error'
      );
    } finally {
      setSaving(false);
    }
  };

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

  const handleDescriptionChange = (value) => {
    setSettings((prev) => ({
      ...prev,
      podcast_subtitle: value,
      podcast_description: value,
    }));
  };

  const validateFeed = async () => {
    setValidating(true);
    setValidationResult(null);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/podcast/validate-feed',
      });
      setValidationResult(response);
      if (response?.feed_url) {
        setSettings((prev) => ({
          ...prev,
          feed_url: response.feed_url,
        }));
      }
      if (response.valid) {
        showNotification(__('Feed validation passed!', 'prorank-seo'), 'success');
      } else if (response.errors?.length > 0) {
        showNotification(__('Feed has issues that need attention.', 'prorank-seo'), 'warning');
      }
    } catch (error) {
      showNotification(__('Failed to validate feed', 'prorank-seo'), 'error');
    } finally {
      setValidating(false);
    }
  };

  const handleImageSelect = () => {
    if (typeof window.wp !== 'undefined' && window.wp.media) {
      const frame = window.wp.media({
        title: __('Select Podcast Artwork', 'prorank-seo'),
        button: {
          text: __('Use this image', 'prorank-seo'),
        },
        multiple: false,
        library: {
          type: 'image',
        },
      });

      frame.on('select', () => {
        const attachment = frame.state().get('selection').first().toJSON();
        handleSettingChange('podcast_image', attachment.url);
      });

      frame.open();
    } else {
      showNotification(__('Media library is not available', 'prorank-seo'), 'error');
    }
  };

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

  const feedUrl = settings.feed_url || (window.prorankSeo?.siteUrl
    ? `${window.prorankSeo.siteUrl}/feed/podcast/`
    : '/feed/podcast/');
  const podcastDescription = settings.podcast_subtitle || settings.podcast_description || '';

  const tabs = [
    { id: 'settings', label: __('Podcast Settings', 'prorank-seo') },
    { id: 'validation', label: __('Feed Validation', 'prorank-seo') },
  ];

  return (
    <div className="pr:max-w-7xl pr:mx-auto pr:p-8">
      {/* Tab Navigation */}
      <div className="pr:border-b pr:border-gray-200 pr:mb-8">
        <nav className="pr:-mb-px pr:flex pr:space-x-8">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`pr:whitespace-nowrap pr:py-4 pr:px-1 pr:border-b-2 pr:font-medium pr:text-sm pr:transition-colors ${
                activeTab === tab.id
                  ? 'pr:border-primary-500 pr:text-primary-600'
                  : 'pr:border-transparent pr:text-gray-500 pr:hover:text-gray-700 pr:hover:border-gray-300'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab Content */}
      <div>
        {activeTab === 'settings' && (
          <div className="pr:space-y-6">
            {!settings.podcast_title && !settings.podcast_author && (
              <Alert variant="warning">
                <p>
                  <strong>{__('Welcome to Podcast SEO!', 'prorank-seo')}</strong> {__(
                    'Start by configuring your podcast details below. All fields start empty - fill them with your actual podcast information.',
                    'prorank-seo'
                  )}
                </p>
              </Alert>
            )}

            <Alert variant="info">
              <p className="pr:mb-2">
                {__(
                  'Configure your podcast settings to optimize your podcast for search engines and podcast directories.',
                  'prorank-seo'
                )}
              </p>
              {settings.enable_podcast_feed && (
                <div className="pr:flex pr:items-center pr:gap-2 pr:mt-3 pr:p-3 pr:bg-white pr:rounded-md pr:border pr:border-info-200">
                  <strong className="pr:text-sm pr:text-gray-900">{__('Your podcast RSS feed URL:', 'prorank-seo')}</strong>
                  <code className="pr:flex-1 pr:text-sm pr:text-gray-700 pr:bg-gray-50 pr:px-2 pr:py-1 pr:rounded-xs">{feedUrl}</code>
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(feedUrl);
                      showNotification(__('Feed URL copied to clipboard', 'prorank-seo'), 'success');
                    }}
                    className="pr:inline-flex pr:items-center pr:gap-1 pr:px-3 pr:py-1.5 pr:text-sm pr:text-primary-600 pr:hover:text-primary-700 pr:transition-colors"
                  >
                    <ClipboardDocumentIcon className="pr:w-4 pr:h-4" />
                    {__('Copy', 'prorank-seo')}
                  </button>
                </div>
              )}
              <div className="pr:flex pr:gap-3 pr:mt-3">
                <a
                  href="edit.php?post_type=prorank_podcast"
                  className="pr:inline-flex pr:items-center pr:px-4 pr:py-2 pr:bg-white pr:text-gray-700 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:font-medium pr:hover:bg-gray-50 pr:transition-colors"
                >
                  {__('Manage Podcast Episodes', 'prorank-seo')}
                </a>
                <a
                  href="post-new.php?post_type=prorank_podcast"
                  className="pr:inline-flex pr:items-center pr:px-4 pr:py-2 pr:text-primary-600 pr:hover:text-primary-700 pr:text-sm pr:font-medium pr:hover:underline pr:transition-colors"
                >
                  {__('Add New Episode', 'prorank-seo')}
                </a>
              </div>
            </Alert>

            <div className="pr:grid pr:grid-cols-1 pr:lg:grid-cols-2 pr:gap-6">
              <Card
                header={
                  <h4 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                    {__('Basic Information', 'prorank-seo')}
                  </h4>
                }
              >
                <div className="pr:space-y-4">
                  <Input
                    label={__('Podcast Title', 'prorank-seo')}
                    helperText={__(
                      'The name of your podcast as it will appear in podcast directories',
                      'prorank-seo'
                    )}
                    value={settings.podcast_title}
                    onChange={(value) => handleSettingChange('podcast_title', value)}
                    placeholder="My Amazing Podcast"
                  />
                  <div className="pr:space-y-2">
                    <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                      {__('Podcast 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={4}
                      value={podcastDescription}
                      onChange={(e) => handleDescriptionChange(e.target.value)}
                    />
                    <p className="pr:text-xs pr:text-gray-500">
                      {__('A brief description of your podcast (max 4000 characters)', 'prorank-seo')}
                    </p>
                  </div>
                  <Input
                    label={__('Podcast Author', 'prorank-seo')}
                    helperText={__('The author or host of the podcast', 'prorank-seo')}
                    value={settings.podcast_author}
                    onChange={(value) => handleSettingChange('podcast_author', value)}
                  />
                  <Input
                    label={__('Podcast Email', 'prorank-seo')}
                    helperText={__('Contact email for the podcast', 'prorank-seo')}
                    type="email"
                    value={settings.podcast_email}
                    onChange={(value) => handleSettingChange('podcast_email', value)}
                  />
                  <Input
                    label={__('Copyright Notice', 'prorank-seo')}
                    helperText={__('Copyright information for your podcast', 'prorank-seo')}
                    value={settings.podcast_copyright}
                    onChange={(value) => handleSettingChange('podcast_copyright', value)}
                    placeholder="© 2025 My Company. All rights reserved."
                  />
                  <div className="pr:pt-4 pr:border-t pr:border-gray-200">
                    <h5 className="pr:text-sm pr:font-semibold pr:text-gray-700 pr:mb-3">
                      {__('Apple Podcasts Owner Information', 'prorank-seo')}
                    </h5>
                    <div className="pr:space-y-4">
                      <Input
                        label={__('Owner Name', 'prorank-seo')}
                        helperText={__('Required by Apple Podcasts - the entity responsible for the podcast', 'prorank-seo')}
                        value={settings.podcast_owner_name}
                        onChange={(value) => handleSettingChange('podcast_owner_name', value)}
                        placeholder="Your Name or Company"
                      />
                      <Input
                        label={__('Owner Email', 'prorank-seo')}
                        helperText={__('Required by Apple Podcasts - not displayed publicly, used for account verification', 'prorank-seo')}
                        type="email"
                        value={settings.podcast_owner_email}
                        onChange={(value) => handleSettingChange('podcast_owner_email', value)}
                        placeholder="owner@example.com"
                      />
                    </div>
                  </div>
                </div>
              </Card>

              <Card
                header={
                  <h4 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                    {__('Podcast Details', 'prorank-seo')}
                  </h4>
                }
              >
                <div className="pr:space-y-4">
                  <div className="pr:space-y-2">
                    <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                      {__('Podcast Artwork', 'prorank-seo')}
                    </label>
                    {settings.podcast_image && (
                      <div className="pr:w-32 pr:h-32 pr:rounded-md pr:overflow-hidden pr:border pr:border-gray-300 pr:mb-3">
                        <img
                          src={settings.podcast_image}
                          alt={__('Podcast artwork', 'prorank-seo')}
                          className="pr:w-full pr:h-full pr:object-cover"
                        />
                      </div>
                    )}
                    <div className="pr:flex pr:gap-2">
                      <Button variant="primary" size="sm" onClick={handleImageSelect}>
                        {settings.podcast_image
                          ? __('Change Artwork', 'prorank-seo')
                          : __('Select Artwork', 'prorank-seo')}
                      </Button>
                      {settings.podcast_image && (
                        <Button
                          variant="danger"
                          size="sm"
                          onClick={() => handleSettingChange('podcast_image', '')}
                        >
                          {__('Remove', 'prorank-seo')}
                        </Button>
                      )}
                    </div>
                    <p className="pr:text-xs pr:text-gray-500">
                      {__('Recommended size: 3000x3000px, JPG or PNG, RGB color space', 'prorank-seo')}
                    </p>
                  </div>
                  <Select
                    label={__('Primary Category', 'prorank-seo')}
                    value={settings.podcast_category}
                    options={podcastCategories}
                    onChange={(value) => handleSettingChange('podcast_category', value)}
                  />
                  <Input
                    label={__('Subcategory', 'prorank-seo')}
                    helperText={__('Optional subcategory within your primary category', 'prorank-seo')}
                    value={settings.podcast_subcategory}
                    onChange={(value) => handleSettingChange('podcast_subcategory', value)}
                  />
                  <Select
                    label={__('Explicit Content', 'prorank-seo')}
                    value={settings.podcast_explicit}
                    options={[
                      { value: 'no', label: __('No', 'prorank-seo') },
                      { value: 'yes', label: __('Yes', 'prorank-seo') },
                    ]}
                    onChange={(value) => handleSettingChange('podcast_explicit', value)}
                  />
                  <Input
                    label={__('Language', 'prorank-seo')}
                    helperText={__('Language code (e.g., en-US, es-ES)', 'prorank-seo')}
                    value={settings.podcast_language}
                    onChange={(value) => handleSettingChange('podcast_language', value)}
                    placeholder="en-US"
                  />
                </div>
              </Card>

              <Card
                header={
                  <h4 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                    {__('RSS Feed Configuration', 'prorank-seo')}
                  </h4>
                }
              >
                <div className="pr:space-y-4">
                  <Toggle
                    label={__('Enable Podcast Feed', 'prorank-seo')}
                    description={__('Generate an RSS feed for your podcast episodes', 'prorank-seo')}
                    checked={settings.enable_podcast_feed}
                    onChange={(value) => handleSettingChange('enable_podcast_feed', value)}
                  />
                  <Input
                    label={__('Feed Limit', 'prorank-seo')}
                    helperText={__('Number of episodes to include in the feed (leave empty for default)', 'prorank-seo')}
                    type="number"
                    value={settings.podcast_feed_limit}
                    onChange={(value) =>
                      handleSettingChange('podcast_feed_limit', value ? parseInt(value) : '')
                    }
                    placeholder="50"
                  />
                  <Toggle
                    label={__('Include iTunes Tags', 'prorank-seo')}
                    description={__('Add Apple Podcasts/iTunes specific tags to your feed', 'prorank-seo')}
                    checked={settings.enable_itunes_tags}
                    onChange={(value) => handleSettingChange('enable_itunes_tags', value)}
                  />
                  <Input
                    label={__('Redirect Feed URL', 'prorank-seo')}
                    helperText={__("If you're moving your podcast, enter the new feed URL here", 'prorank-seo')}
                    type="url"
                    value={settings.podcast_redirect_feed}
                    onChange={(value) => handleSettingChange('podcast_redirect_feed', value)}
                  />
                </div>
              </Card>

              <Card
                header={
                  <h4 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                    {__('Podcast 2.0 Features', 'prorank-seo')}
                  </h4>
                }
              >
                <div className="pr:space-y-4">
                  <Toggle
                    label={__('Enable Transcripts', 'prorank-seo')}
                    description={__('Add transcript support for accessibility and SEO', 'prorank-seo')}
                    checked={settings.enable_transcripts}
                    onChange={(value) => handleSettingChange('enable_transcripts', value)}
                  />
                  {settings.enable_transcripts && (
                    <div className="pr:ml-4 pr:p-3 pr:bg-info-50 pr:rounded-md pr:border pr:border-info-200">
                      <p className="pr:text-sm pr:text-info-700">
                        {__(
                          'Upload transcripts for each episode in the Episode Editor. Supported formats: VTT, SRT, TXT. Transcripts improve accessibility and SEO visibility.',
                          'prorank-seo'
                        )}
                      </p>
                      <a
                        href="post-new.php?post_type=prorank_podcast"
                        className="pr:inline-flex pr:items-center pr:mt-2 pr:text-sm pr:text-info-600 pr:hover:text-info-700 pr:hover:underline"
                      >
                        {__('Add Episode with Transcript', 'prorank-seo')} →
                      </a>
                    </div>
                  )}
                  <Input
                    label={__('Funding URL', 'prorank-seo')}
                    helperText={__('Link to your donation/support page', 'prorank-seo')}
                    type="url"
                    value={settings.funding_url}
                    onChange={(value) => handleSettingChange('funding_url', value)}
                    placeholder="https://www.patreon.com/yourpodcast"
                  />
                </div>
              </Card>

              <Card
                header={
                  <h4 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                    {__('Podcast Directories', 'prorank-seo')}
                  </h4>
                }
              >
                <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
                  {__('Submit your podcast feed to these directories:', 'prorank-seo')}
                </p>
                <ul className="pr:space-y-3">
                  <li>
                    <a
                      href="https://podcasters.apple.com/"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="pr:inline-flex pr:items-center pr:gap-2 pr:text-sm pr:text-primary-600 pr:hover:text-primary-700 pr:hover:underline pr:transition-colors"
                    >
                      {__('Apple Podcasts', 'prorank-seo')}
                      <ArrowTopRightOnSquareIcon className="pr:w-4 pr:h-4" />
                    </a>
                  </li>
                  <li>
                    <a
                      href="https://podcasters.spotify.com/"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="pr:inline-flex pr:items-center pr:gap-2 pr:text-sm pr:text-primary-600 pr:hover:text-primary-700 pr:hover:underline pr:transition-colors"
                    >
                      {__('Spotify for Podcasters', 'prorank-seo')}
                      <ArrowTopRightOnSquareIcon className="pr:w-4 pr:h-4" />
                    </a>
                  </li>
                  <li>
                    <a
                      href="https://music.youtube.com/podcasts"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="pr:inline-flex pr:items-center pr:gap-2 pr:text-sm pr:text-primary-600 pr:hover:text-primary-700 pr:hover:underline pr:transition-colors"
                    >
                      {__('YouTube Music', 'prorank-seo')}
                      <ArrowTopRightOnSquareIcon className="pr:w-4 pr:h-4" />
                    </a>
                  </li>
                  <li>
                    <a
                      href="https://www.amazon.com/music/podcasts"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="pr:inline-flex pr:items-center pr:gap-2 pr:text-sm pr:text-primary-600 pr:hover:text-primary-700 pr:hover:underline pr:transition-colors"
                    >
                      {__('Amazon Music & Audible', 'prorank-seo')}
                      <ArrowTopRightOnSquareIcon className="pr:w-4 pr:h-4" />
                    </a>
                  </li>
                  <li>
                    <a
                      href="https://www.iheart.com/podcast/"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="pr:inline-flex pr:items-center pr:gap-2 pr:text-sm pr:text-primary-600 pr:hover:text-primary-700 pr:hover:underline pr:transition-colors"
                    >
                      {__('iHeartRadio', 'prorank-seo')}
                      <ArrowTopRightOnSquareIcon className="pr:w-4 pr:h-4" />
                    </a>
                  </li>
                  <li>
                    <a
                      href="https://www.pandora.com/podcast-submission"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="pr:inline-flex pr:items-center pr:gap-2 pr:text-sm pr:text-primary-600 pr:hover:text-primary-700 pr:hover:underline pr:transition-colors"
                    >
                      {__('Pandora', 'prorank-seo')}
                      <ArrowTopRightOnSquareIcon className="pr:w-4 pr:h-4" />
                    </a>
                  </li>
                </ul>
              </Card>
            </div>

            <div className="pr:flex pr:items-center pr:gap-3 pr:mt-8 pr:pt-6 pr:border-t pr:border-gray-200">
              <Button variant="primary" onClick={saveSettings} loading={saving} disabled={saving}>
                {saving ? __('Saving…', 'prorank-seo') : __('Save Settings', 'prorank-seo')}
              </Button>
              <a
                href={`${window.prorankSeo?.adminUrl || '/wp-admin/'}edit.php?post_type=prorank_podcast`}
                className="pr:inline-flex pr:items-center pr:px-4 pr:py-2 pr:bg-white pr:text-gray-700 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:font-medium pr:hover:bg-gray-50 pr:transition-colors"
              >
                {__('Manage Episodes', 'prorank-seo')}
              </a>
              <a
                href={`${window.prorankSeo?.adminUrl || '/wp-admin/'}post-new.php?post_type=prorank_podcast`}
                className="pr:inline-flex pr:items-center pr:px-4 pr:py-2 pr:text-primary-600 pr:hover:text-primary-700 pr:text-sm pr:font-medium pr:hover:underline pr:transition-colors"
              >
                {__('Add New Episode', 'prorank-seo')}
              </a>
            </div>
          </div>
        )}
        {activeTab === 'validation' && (
          <div className="pr:space-y-6">
            <Card
              header={
                <h4 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                  {__('Feed Configuration Status', 'prorank-seo')}
                </h4>
              }
            >
              <div className="pr:space-y-6">
                {settings.enable_podcast_feed ? (
                  <div className="pr:space-y-4">
                    <h5 className="pr:text-base pr:font-semibold pr:text-gray-900">
                      {__('RSS Feed', 'prorank-seo')}
                    </h5>
                    <div className="pr:flex pr:items-center pr:gap-2 pr:p-3 pr:bg-gray-50 pr:rounded-md pr:border pr:border-gray-200">
                      <DocumentTextIcon className="pr:w-5 pr:h-5 pr:text-gray-500" />
                      <span className="pr:text-sm pr:font-medium pr:text-gray-700">
                        {__('Your podcast RSS feed URL:', 'prorank-seo')}
                      </span>
                      <code className="pr:flex-1 pr:text-sm pr:text-gray-900 pr:bg-white pr:px-2 pr:py-1 pr:rounded-xs">
                        {feedUrl}
                      </code>
                    </div>
                    <div className="pr:flex pr:flex-wrap pr:gap-3">
                      <Button
                        variant="primary"
                        size="sm"
                        onClick={validateFeed}
                        loading={validating}
                        disabled={validating}
                      >
                        {validating ? __('Validating…', 'prorank-seo') : __('Validate Feed Now', 'prorank-seo')}
                      </Button>
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => window.open(feedUrl, '_blank')}
                      >
                        {__('View Feed', 'prorank-seo')}
                      </Button>
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => window.open(`https://podba.se/validate/?url=${encodeURIComponent(feedUrl)}`, '_blank')}
                      >
                        {__('Validate with Podbase', 'prorank-seo')}
                      </Button>
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => window.open(`https://castfeedvalidator.com/?url=${encodeURIComponent(feedUrl)}`, '_blank')}
                      >
                        {__('Validate with Cast Feed Validator', 'prorank-seo')}
                      </Button>
                    </div>

                    {/* Validation Results */}
                    {validationResult && (
                      <div className="pr:space-y-4 pr:mt-6 pr:pt-6 pr:border-t pr:border-gray-200">
                        <h5 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:flex pr:items-center pr:gap-2">
                          {validationResult.valid ? (
                            <>
                              <span className="pr:text-success-500">✓</span>
                              {__('Feed Validation Passed', 'prorank-seo')}
                            </>
                          ) : (
                            <>
                              <span className="pr:text-danger-500">✕</span>
                              {__('Feed Has Issues', 'prorank-seo')}
                            </>
                          )}
                        </h5>

                        {/* Errors */}
                        {validationResult.errors?.length > 0 && (
                          <div className="pr:p-4 pr:bg-danger-50 pr:rounded-lg pr:border pr:border-danger-200">
                            <h6 className="pr:text-sm pr:font-semibold pr:text-danger-800 pr:mb-2">
                              {__('Errors (must fix)', 'prorank-seo')}
                            </h6>
                            <ul className="pr:space-y-1">
                              {validationResult.errors.map((error, index) => (
                                <li key={index} className="pr:text-sm pr:text-danger-700 pr:flex pr:items-start pr:gap-2">
                                  <span className="pr:text-danger-400 pr:mt-0.5">✕</span>
                                  {error.message}
                                </li>
                              ))}
                            </ul>
                          </div>
                        )}

                        {/* Warnings */}
                        {validationResult.warnings?.length > 0 && (
                          <div className="pr:p-4 pr:bg-warning-50 pr:rounded-lg pr:border pr:border-warning-200">
                            <h6 className="pr:text-sm pr:font-semibold pr:text-warning-800 pr:mb-2">
                              {__('Warnings (recommended fixes)', 'prorank-seo')}
                            </h6>
                            <ul className="pr:space-y-1">
                              {validationResult.warnings.map((warning, index) => (
                                <li key={index} className="pr:text-sm pr:text-warning-700 pr:flex pr:items-start pr:gap-2">
                                  <span className="pr:text-warning-400 pr:mt-0.5">⚠</span>
                                  {warning.message}
                                </li>
                              ))}
                            </ul>
                          </div>
                        )}

                        {/* Info */}
                        {validationResult.info?.length > 0 && (
                          <div className="pr:p-4 pr:bg-info-50 pr:rounded-lg pr:border pr:border-info-200">
                            <h6 className="pr:text-sm pr:font-semibold pr:text-info-800 pr:mb-2">
                              {__('Recommendations', 'prorank-seo')}
                            </h6>
                            <ul className="pr:space-y-1">
                              {validationResult.info
                                .filter((item) => item.code !== 'feed_url')
                                .map((item, index) => (
                                  <li key={index} className="pr:text-sm pr:text-info-700 pr:flex pr:items-start pr:gap-2">
                                    <span className="pr:text-info-400 pr:mt-0.5">ℹ</span>
                                    {item.message}
                                  </li>
                                ))}
                            </ul>
                          </div>
                        )}

                        {/* Episode count */}
                        {validationResult.episode_count !== undefined && (
                          <p className="pr:text-sm pr:text-gray-600">
                            {__('Episodes in feed:', 'prorank-seo')} <strong>{validationResult.episode_count}</strong>
                          </p>
                        )}
                      </div>
                    )}
                  </div>
                ) : (
                  <Alert variant="warning">
                    {__('Podcast feed is currently disabled. Enable it in the settings tab to generate your RSS feed.', 'prorank-seo')}
                  </Alert>
                )}

                <div className="pr:space-y-4">
                  <h5 className="pr:text-base pr:font-semibold pr:text-gray-900">
                    {__('Configuration Status', 'prorank-seo')}
                  </h5>
                  <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-3 pr:gap-4">
                    <div className={`pr:p-4 pr:rounded-lg pr:border-2 ${
                      settings.enable_podcast_feed
                        ? 'pr:bg-success-50 pr:border-success-200'
                        : 'pr:bg-gray-50 pr:border-gray-200'
                    }`}>
                      <div className="pr:text-2xl pr:font-bold pr:text-gray-900">
                        {settings.enable_podcast_feed ? __('Active', 'prorank-seo') : __('Inactive', 'prorank-seo')}
                      </div>
                      <div className="pr:text-sm pr:text-gray-600 pr:mt-1">
                        {__('Feed Status', 'prorank-seo')}
                      </div>
                    </div>
                    <div className="pr:p-4 pr:bg-gray-50 pr:rounded-lg pr:border-2 pr:border-gray-200">
                      <div className="pr:text-2xl pr:font-bold pr:text-gray-900">
                        {settings.podcast_feed_limit || __('Not Set', 'prorank-seo')}
                      </div>
                      <div className="pr:text-sm pr:text-gray-600 pr:mt-1">
                        {__('Max Episodes in Feed', 'prorank-seo')}
                      </div>
                    </div>
                    <div className={`pr:p-4 pr:rounded-lg pr:border-2 ${
                      settings.enable_transcripts
                        ? 'pr:bg-success-50 pr:border-success-200'
                        : 'pr:bg-gray-50 pr:border-gray-200'
                    }`}>
                      <div className="pr:text-2xl pr:font-bold pr:text-gray-900">
                        {settings.enable_transcripts ? __('Enabled', 'prorank-seo') : __('Disabled', 'prorank-seo')}
                      </div>
                      <div className="pr:text-sm pr:text-gray-600 pr:mt-1">
                        {__('Transcripts', 'prorank-seo')}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="pr:space-y-4">
                  <h5 className="pr:text-base pr:font-semibold pr:text-gray-900">
                    {__('Setup Checklist', 'prorank-seo')}
                  </h5>
                  <ul className="pr:space-y-2">
                    {[
                      { key: 'podcast_title', label: __('Podcast title', 'prorank-seo'), value: settings.podcast_title },
                      { key: 'podcast_subtitle', label: __('Podcast description', 'prorank-seo'), value: podcastDescription },
                      { key: 'podcast_image', label: __('Podcast artwork', 'prorank-seo'), value: settings.podcast_image },
                      { key: 'podcast_author', label: __('Author/Host name', 'prorank-seo'), value: settings.podcast_author },
                      { key: 'podcast_email', label: __('Contact email', 'prorank-seo'), value: settings.podcast_email },
                      { key: 'podcast_category', label: __('Podcast category', 'prorank-seo'), value: settings.podcast_category },
                      { key: 'podcast_owner_name', label: __('Owner name (Apple)', 'prorank-seo'), value: settings.podcast_owner_name },
                      { key: 'podcast_owner_email', label: __('Owner email (Apple)', 'prorank-seo'), value: settings.podcast_owner_email },
                    ].map(({ key, label, value }) => (
                      <li key={key} className="pr:flex pr:items-center pr:gap-3 pr:p-3 pr:bg-gray-50 pr:rounded-md">
                        <span className="pr:text-2xl">
                          {value && value.trim() ? '✅' : '⚠️'}
                        </span>
                        <span className="pr:flex-1 pr:text-sm pr:text-gray-700">
                          {label}
                          {value && value.trim() && key !== 'podcast_image' && (
                            <span className="pr:ml-2 pr:text-gray-500">({value})</span>
                          )}
                        </span>
                      </li>
                    ))}
                  </ul>

                  {(!settings.podcast_title || !podcastDescription || !settings.podcast_image ||
                    !settings.podcast_author || !settings.podcast_email) && (
                    <div className="pr:mt-4">
                      <Button variant="primary" onClick={() => setActiveTab('settings')}>
                        {__('Complete Setup', 'prorank-seo')}
                      </Button>
                    </div>
                  )}
                </div>

                <div className="pr:space-y-4">
                  <h5 className="pr:text-base pr:font-semibold pr:text-gray-900">
                    {__('Optimization Recommendations', 'prorank-seo')}
                  </h5>
                  <ul className="pr:space-y-2">
                    {!settings.enable_transcripts && (
                      <li className="pr:flex pr:items-start pr:gap-2 pr:text-sm pr:text-gray-700">
                        <span className="pr:text-primary-500 pr:mt-0.5">•</span>
                        {__('Enable transcripts to improve accessibility and SEO visibility', 'prorank-seo')}
                      </li>
                    )}
                    {!settings.funding_url && (
                      <li className="pr:flex pr:items-start pr:gap-2 pr:text-sm pr:text-gray-700">
                        <span className="pr:text-primary-500 pr:mt-0.5">•</span>
                        {__('Add a funding URL to enable listener support', 'prorank-seo')}
                      </li>
                    )}
                    <li className="pr:flex pr:items-start pr:gap-2 pr:text-sm pr:text-gray-700">
                      <span className="pr:text-primary-500 pr:mt-0.5">•</span>
                      {__('Submit your feed to all major podcast platforms', 'prorank-seo')}
                    </li>
                    <li className="pr:flex pr:items-start pr:gap-2 pr:text-sm pr:text-gray-700">
                      <span className="pr:text-primary-500 pr:mt-0.5">•</span>
                      {__('Use detailed show notes with timestamps and links', 'prorank-seo')}
                    </li>
                  </ul>
                </div>
              </div>
            </Card>
          </div>
        )}
      </div>
    </div>
  );
};

export default PodcastSeoSettings;
