/**
 * InstaRank Gutenberg SEO Panel
 *
 * Adds a sidebar panel to the Gutenberg editor with all SEO controls
 *
 * @package InstaRank
 * @since 1.4.0
 */

import { registerPlugin } from '@wordpress/plugins';
import { PluginSidebar, PluginSidebarMoreMenuItem } from '@wordpress/edit-post';
import { PanelBody, TextControl, TextareaControl, ToggleControl, ExternalLink, Notice, Button, TabPanel } from '@wordpress/components';
import { useSelect, useDispatch } from '@wordpress/data';
import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
// SCSS imported via PHP wp_enqueue_style
// import './style.scss';

/**
 * Character counter component
 */
const CharacterCounter = ({ current, max, optimal }) => {
    const percentage = (current / max) * 100;
    let status = 'good';

    if (current === 0) {
        status = 'empty';
    } else if (current > max) {
        status = 'too-long';
    } else if (current < optimal) {
        status = 'short';
    }

    return (
        <div className={`instarank-char-counter status-${status}`}>
            <span className="count">{current} / {max}</span>
            <div className="bar">
                <div className="fill" style={{ width: `${Math.min(percentage, 100)}%` }} />
            </div>
            {status === 'too-long' && (
                <span className="warning">{__('Too long - will be truncated', 'instarank')}</span>
            )}
            {status === 'short' && (
                <span className="hint">{__(`Optimal: ${optimal} characters`, 'instarank')}</span>
            )}
        </div>
    );
};

/**
 * SERP Preview component
 */
const SerpPreview = ({ title, description, url }) => {
    const displayTitle = title || __('Post Title', 'instarank');
    const displayUrl = url || 'https://example.com/post-url';
    const displayDescription = description || __('Meta description will appear here...', 'instarank');

    return (
        <div className="instarank-serp-preview">
            <div className="serp-container">
                <div className="serp-url">{displayUrl}</div>
                <div className="serp-title">{displayTitle}</div>
                <div className="serp-description">{displayDescription}</div>
            </div>
        </div>
    );
};

/**
 * Focus Keyword Analysis component
 */
const FocusKeywordAnalysis = ({ keyword, title, description, content, url }) => {
    if (!keyword) {
        return null;
    }

    const checks = {
        inTitle: title.toLowerCase().includes(keyword.toLowerCase()),
        inDescription: description.toLowerCase().includes(keyword.toLowerCase()),
        inUrl: url.toLowerCase().includes(keyword.toLowerCase()),
        inContent: content.toLowerCase().includes(keyword.toLowerCase()),
    };

    const score = Object.values(checks).filter(Boolean).length;
    const percentage = (score / 4) * 100;

    return (
        <div className="instarank-keyword-analysis">
            <div className={`score-badge score-${Math.round(percentage / 25)}`}>
                {score}/4
            </div>
            <ul className="checks-list">
                <li className={checks.inTitle ? 'check-pass' : 'check-fail'}>
                    <span className="dashicons dashicons-yes-alt"></span>
                    {__('Keyword in title', 'instarank')}
                </li>
                <li className={checks.inDescription ? 'check-pass' : 'check-fail'}>
                    <span className="dashicons dashicons-yes-alt"></span>
                    {__('Keyword in description', 'instarank')}
                </li>
                <li className={checks.inUrl ? 'check-pass' : 'check-fail'}>
                    <span className="dashicons dashicons-yes-alt"></span>
                    {__('Keyword in URL', 'instarank')}
                </li>
                <li className={checks.inContent ? 'check-pass' : 'check-fail'}>
                    <span className="dashicons dashicons-yes-alt"></span>
                    {__('Keyword in content', 'instarank')}
                </li>
            </ul>
        </div>
    );
};

/**
 * pSEO Fields Panel Component - EDITABLE VERSION
 * Displays and allows editing of dataset field values for programmatically generated pages
 */
const PseoFieldsPanel = ({ pseoData, onFieldChange }) => {
    const [expanded, setExpanded] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [editedFields, setEditedFields] = useState({});
    const [hasChanges, setHasChanges] = useState(false);
    const [imageLoadErrors, setImageLoadErrors] = useState({});

    if (!pseoData?.isPseoPage || !pseoData?.fields || Object.keys(pseoData.fields).length === 0) {
        return null;
    }

    const fields = pseoData.fields;
    const fieldCount = Object.keys(fields).length;

    // Merge original fields with edited fields
    const currentFields = { ...fields, ...editedFields };

    // Filter fields based on search term
    const filteredFields = Object.entries(currentFields).filter(([key, value]) => {
        // Skip internal fields
        if (key.startsWith('_')) return false;
        if (!searchTerm) return true;
        const searchLower = searchTerm.toLowerCase();
        return key.toLowerCase().includes(searchLower) ||
               (value && String(value).toLowerCase().includes(searchLower));
    });

    // Check if field name suggests it's an image
    const isImageFieldName = (fieldKey) => {
        const imagePatterns = ['image', 'img', 'photo', 'picture', 'thumbnail', 'avatar', 'logo', 'icon', 'banner', 'hero'];
        const fieldLower = fieldKey.toLowerCase();
        return imagePatterns.some(pattern => fieldLower.includes(pattern));
    };

    // Check if URL points to an image
    const isImageUrl = (url) => {
        if (!url || typeof url !== 'string') return false;
        const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico'];
        const urlLower = url.toLowerCase();
        if (imageExtensions.some(ext => urlLower.endsWith('.' + ext))) return true;
        // Check for common image CDN patterns
        const imageCdnPatterns = ['unsplash.com', 'pexels.com', 'pixabay.com', 'cloudinary.com', 'imgix.net', 'wp-content/uploads'];
        return imageCdnPatterns.some(pattern => urlLower.includes(pattern));
    };

    // Categorize fields
    const categorizeField = (key, value) => {
        if (!value) return 'text';
        const strValue = String(value);
        // Check for image fields first
        if (isImageFieldName(key) || isImageUrl(strValue)) return 'image';
        if (strValue.startsWith('http://') || strValue.startsWith('https://')) return 'url';
        if (/<[^>]+>/.test(strValue)) return 'html';
        return 'text';
    };

    // Format field name for display
    const formatFieldName = (name) => {
        return name
            .replace(/[-_]/g, ' ')
            .replace(/([a-z])([A-Z])/g, '$1 $2')
            .split(' ')
            .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
            .join(' ');
    };

    // Handle field value change
    const handleFieldChange = (key, newValue) => {
        const updatedFields = { ...editedFields, [key]: newValue };
        setEditedFields(updatedFields);
        setHasChanges(true);

        // Notify parent component of change
        if (onFieldChange) {
            onFieldChange(key, newValue);
        }
    };

    // Group fields by category
    const imageFields = filteredFields.filter(([key, value]) => categorizeField(key, value) === 'image');
    const textFields = filteredFields.filter(([key, value]) => categorizeField(key, value) === 'text');
    const urlFields = filteredFields.filter(([key, value]) => categorizeField(key, value) === 'url');
    const htmlFields = filteredFields.filter(([key, value]) => categorizeField(key, value) === 'html');

    // Handle image upload via WordPress Media Library
    const openMediaLibrary = (fieldKey) => {
        if (typeof wp !== 'undefined' && wp.media) {
            const mediaFrame = wp.media({
                title: __('Select or Upload Image', 'instarank'),
                button: { text: __('Use this image', 'instarank') },
                multiple: false,
                library: { type: 'image' }
            });

            mediaFrame.on('select', () => {
                const attachment = mediaFrame.state().get('selection').first().toJSON();
                handleFieldChange(fieldKey, attachment.url);
                // Clear any previous error
                setImageLoadErrors(prev => ({ ...prev, [fieldKey]: false }));
            });

            mediaFrame.open();
        }
    };

    // Handle image load error
    const handleImageError = (key) => {
        setImageLoadErrors(prev => ({ ...prev, [key]: true }));
    };

    const renderFieldInput = (key, value, type) => {
        const isLong = String(value || '').length > 80;

        // Handle image fields
        if (type === 'image') {
            const hasImage = value && value.startsWith('http');
            const hasError = imageLoadErrors[key];

            return (
                <div>
                    {/* Image Preview */}
                    <div style={{ marginBottom: '8px' }}>
                        {hasImage && !hasError ? (
                            <div style={{ position: 'relative', display: 'inline-block' }}>
                                <img
                                    src={value}
                                    alt={formatFieldName(key)}
                                    style={{
                                        maxWidth: '100%',
                                        maxHeight: '120px',
                                        borderRadius: '4px',
                                        border: '1px solid #e2e4e7',
                                        display: 'block'
                                    }}
                                    onError={() => handleImageError(key)}
                                />
                            </div>
                        ) : hasError ? (
                            <div style={{
                                width: '100%',
                                height: '80px',
                                background: '#fef2f2',
                                border: '1px solid #fecaca',
                                borderRadius: '4px',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                color: '#dc2626',
                                fontSize: '11px'
                            }}>
                                <span className="dashicons dashicons-warning" style={{ marginRight: '4px', fontSize: '14px' }}></span>
                                {__('Image failed to load', 'instarank')}
                            </div>
                        ) : (
                            <div style={{
                                width: '100%',
                                height: '80px',
                                background: '#f9fafb',
                                border: '2px dashed #d1d5db',
                                borderRadius: '4px',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                color: '#9ca3af',
                                fontSize: '11px'
                            }}>
                                <span className="dashicons dashicons-format-image" style={{ fontSize: '20px', marginRight: '6px' }}></span>
                                {__('No image set', 'instarank')}
                            </div>
                        )}
                    </div>

                    {/* URL Input and Upload Button */}
                    <div style={{ display: 'flex', gap: '6px', alignItems: 'stretch' }}>
                        <input
                            type="url"
                            value={value || ''}
                            onChange={(e) => {
                                handleFieldChange(key, e.target.value);
                                setImageLoadErrors(prev => ({ ...prev, [key]: false }));
                            }}
                            placeholder={__('Enter image URL...', 'instarank')}
                            style={{
                                flex: 1,
                                padding: '6px 8px',
                                border: '1px solid #d1d5db',
                                borderRadius: '4px',
                                fontSize: '11px'
                            }}
                        />
                        <Button
                            isSecondary
                            onClick={() => openMediaLibrary(key)}
                            style={{ padding: '0 8px', height: '30px' }}
                        >
                            <span className="dashicons dashicons-upload" style={{ fontSize: '14px' }}></span>
                        </Button>
                        {hasImage && (
                            <Button
                                isDestructive
                                onClick={() => handleFieldChange(key, '')}
                                style={{ padding: '0 8px', height: '30px' }}
                            >
                                <span className="dashicons dashicons-no-alt" style={{ fontSize: '14px' }}></span>
                            </Button>
                        )}
                    </div>

                    {/* View Full Size Link */}
                    {hasImage && !hasError && (
                        <div style={{ marginTop: '4px' }}>
                            <a
                                href={value}
                                target="_blank"
                                rel="noopener noreferrer"
                                style={{ fontSize: '10px', color: '#6b7280', textDecoration: 'none' }}
                            >
                                <span className="dashicons dashicons-external" style={{ fontSize: '10px', verticalAlign: 'middle' }}></span>
                                {' '}{__('View full size', 'instarank')}
                            </a>
                        </div>
                    )}
                </div>
            );
        }

        if (type === 'url') {
            return (
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <input
                        type="url"
                        value={value || ''}
                        onChange={(e) => handleFieldChange(key, e.target.value)}
                        style={{
                            flex: 1,
                            padding: '6px 10px',
                            border: '1px solid #d1d5db',
                            borderRadius: '4px',
                            fontSize: '12px'
                        }}
                    />
                    {value && (
                        <a
                            href={value}
                            target="_blank"
                            rel="noopener noreferrer"
                            style={{ color: '#2271b1' }}
                        >
                            <span className="dashicons dashicons-external" style={{ fontSize: '14px' }}></span>
                        </a>
                    )}
                </div>
            );
        }

        if (type === 'html' || isLong) {
            return (
                <textarea
                    value={value || ''}
                    onChange={(e) => handleFieldChange(key, e.target.value)}
                    rows={type === 'html' ? 4 : 2}
                    style={{
                        width: '100%',
                        padding: '6px 10px',
                        border: '1px solid #d1d5db',
                        borderRadius: '4px',
                        fontSize: type === 'html' ? '11px' : '12px',
                        fontFamily: type === 'html' ? 'monospace' : 'inherit',
                        resize: 'vertical'
                    }}
                />
            );
        }

        return (
            <input
                type="text"
                value={value || ''}
                onChange={(e) => handleFieldChange(key, e.target.value)}
                style={{
                    width: '100%',
                    padding: '6px 10px',
                    border: '1px solid #d1d5db',
                    borderRadius: '4px',
                    fontSize: '12px'
                }}
            />
        );
    };

    const renderFieldSection = (sectionFields, title, type) => {
        if (sectionFields.length === 0) return null;

        return (
            <div style={{ marginBottom: '16px' }}>
                <h4 style={{
                    margin: '0 0 8px 0',
                    fontSize: '11px',
                    textTransform: 'uppercase',
                    color: '#6b7280',
                    borderBottom: '1px solid #e5e7eb',
                    paddingBottom: '4px',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '4px'
                }}>
                    {type === 'image' && (
                        <span className="dashicons dashicons-format-image" style={{ fontSize: '12px', color: '#f97316' }}></span>
                    )}
                    {title}
                </h4>
                {sectionFields.map(([key, value]) => (
                    <div key={key} style={{
                        marginBottom: '10px',
                        background: 'white',
                        padding: '8px 10px',
                        borderRadius: '4px',
                        border: '1px solid #e2e4e7'
                    }}>
                        <label style={{
                            display: 'block',
                            fontWeight: '600',
                            color: '#2271b1',
                            fontSize: '11px',
                            marginBottom: '4px'
                        }}>
                            {formatFieldName(key)}
                            {type === 'html' && (
                                <span style={{ fontWeight: 'normal', color: '#9ca3af', marginLeft: '6px' }}>
                                    (HTML)
                                </span>
                            )}
                        </label>
                        {renderFieldInput(key, value, type)}
                    </div>
                ))}
            </div>
        );
    };

    return (
        <PanelBody
            title={
                <span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <span className="dashicons dashicons-database" style={{ color: '#f97316', fontSize: '16px' }}></span>
                    {__('Dataset Fields', 'instarank')}
                    <span style={{
                        background: '#f97316',
                        color: 'white',
                        borderRadius: '10px',
                        padding: '2px 8px',
                        fontSize: '11px',
                        fontWeight: '600'
                    }}>{fieldCount}</span>
                    {hasChanges && (
                        <span style={{
                            background: '#059669',
                            color: 'white',
                            borderRadius: '10px',
                            padding: '2px 6px',
                            fontSize: '10px',
                            fontWeight: '600'
                        }}>
                            {__('Modified', 'instarank')}
                        </span>
                    )}
                </span>
            }
            initialOpen={true}
        >
            <div style={{
                marginBottom: '12px',
                padding: '10px',
                background: 'linear-gradient(135deg, #fef7ed 0%, #fff7ed 100%)',
                borderRadius: '6px',
                fontSize: '12px',
                border: '1px solid #fed7aa'
            }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
                    <span className="dashicons dashicons-edit" style={{ color: '#f97316', fontSize: '14px' }}></span>
                    <strong style={{ color: '#92400e' }}>{__('Editable Fields', 'instarank')}</strong>
                </div>
                <p style={{ margin: '0', color: '#78350f', fontSize: '11px' }}>
                    {__('Edit field values below. Changes will update the page content when you save the post.', 'instarank')}
                </p>
                {pseoData.generatedAt && (
                    <div style={{ marginTop: '6px', color: '#92400e', fontSize: '10px' }}>
                        {__('Generated:', 'instarank')} {pseoData.generatedAt}
                    </div>
                )}
            </div>

            {fieldCount > 5 && (
                <TextControl
                    placeholder={__('Search fields...', 'instarank')}
                    value={searchTerm}
                    onChange={setSearchTerm}
                    style={{ marginBottom: '12px' }}
                />
            )}

            <div style={{
                maxHeight: expanded ? 'none' : '400px',
                overflow: expanded ? 'visible' : 'auto'
            }}>
                {renderFieldSection(imageFields, __('Image Fields', 'instarank'), 'image')}
                {renderFieldSection(textFields, __('Text Fields', 'instarank'), 'text')}
                {renderFieldSection(urlFields, __('URL Fields', 'instarank'), 'url')}
                {renderFieldSection(htmlFields, __('HTML Content', 'instarank'), 'html')}
            </div>

            {fieldCount > 8 && (
                <Button
                    isLink
                    onClick={() => setExpanded(!expanded)}
                    style={{ marginTop: '8px', fontSize: '12px' }}
                >
                    {expanded ? __('Show less', 'instarank') : __('Show all fields', 'instarank')}
                </Button>
            )}

            {searchTerm && filteredFields.length === 0 && (
                <p style={{ textAlign: 'center', color: '#757575', padding: '20px', margin: 0 }}>
                    {__('No fields match your search', 'instarank')}
                </p>
            )}

            <div style={{
                marginTop: '12px',
                paddingTop: '10px',
                borderTop: '1px solid #e5e7eb',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                fontSize: '11px'
            }}>
                <span style={{ color: '#6b7280' }}>
                    {fieldCount} {__('fields from dataset', 'instarank')}
                </span>
                <span style={{ color: '#059669', fontWeight: '500' }}>
                    <span className="dashicons dashicons-saved" style={{ fontSize: '12px', verticalAlign: 'middle', marginRight: '4px' }}></span>
                    {__('Auto-saved with post', 'instarank')}
                </span>
            </div>
        </PanelBody>
    );
};

/**
 * Main InstaRank Panel Component
 */
const InstaRankPanel = () => {
    const { postId, postType, nonce, ajaxUrl, connected, projectId, metaData, pseoData, pendingChanges, limits } = window.instarankGutenberg;

    // State to track pSEO field changes for saving
    const [pseoFieldChanges, setPseoFieldChanges] = useState({});
    const [wasSaving, setWasSaving] = useState(false);

    // Get post data from editor
    const { postTitle, postContent, postSlug, isSaving, isAutosaving } = useSelect((select) => ({
        postTitle: select('core/editor').getEditedPostAttribute('title'),
        postContent: select('core/editor').getEditedPostContent(),
        postSlug: select('core/editor').getEditedPostAttribute('slug'),
        isSaving: select('core/editor').isSavingPost(),
        isAutosaving: select('core/editor').isAutosavingPost(),
    }));

    const { editPost } = useDispatch('core/editor');

    // Handle pSEO field changes
    const handlePseoFieldChange = (key, value) => {
        setPseoFieldChanges(prev => ({ ...prev, [key]: value }));
    };

    // Save pSEO fields when post is saved (not autosave)
    useEffect(() => {
        // Detect when saving finishes (transition from saving to not saving)
        if (wasSaving && !isSaving && !isAutosaving && Object.keys(pseoFieldChanges).length > 0) {
            // Save pSEO fields via AJAX
            const formData = new FormData();
            formData.append('action', 'instarank_save_pseo_fields');
            formData.append('nonce', nonce);
            formData.append('post_id', postId);
            formData.append('fields', JSON.stringify(pseoFieldChanges));

            fetch(ajaxUrl, {
                method: 'POST',
                body: formData,
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('InstaRank: pSEO fields saved successfully');
                    // Clear the changes after successful save
                    setPseoFieldChanges({});
                } else {
                    console.error('InstaRank: Failed to save pSEO fields', data);
                }
            })
            .catch(error => {
                console.error('InstaRank: Error saving pSEO fields', error);
            });
        }
        setWasSaving(isSaving && !isAutosaving);
    }, [isSaving, isAutosaving]);

    // Local state for meta fields
    const [metaTitle, setMetaTitle] = useState(metaData.metaTitle || '');
    const [metaDescription, setMetaDescription] = useState(metaData.metaDescription || '');
    const [focusKeyword, setFocusKeyword] = useState(metaData.focusKeyword || '');
    const [canonical, setCanonical] = useState(metaData.canonical || '');
    const [robotsNoindex, setRobotsNoindex] = useState(metaData.robotsNoindex === '1');
    const [ogTitle, setOgTitle] = useState(metaData.ogTitle || '');
    const [ogDescription, setOgDescription] = useState(metaData.ogDescription || '');
    const [ogImage, setOgImage] = useState(metaData.ogImage || '');
    const [twitterTitle, setTwitterTitle] = useState(metaData.twitterTitle || '');
    const [twitterDescription, setTwitterDescription] = useState(metaData.twitterDescription || '');
    const [twitterImage, setTwitterImage] = useState(metaData.twitterImage || '');

    // Save meta fields
    const saveMeta = (key, value) => {
        editPost({ meta: { [key]: value } });
    };

    // Display values with fallbacks
    const displayTitle = metaTitle || postTitle;
    const displayDescription = metaDescription || __('No description set', 'instarank');
    const siteUrl = window.location.origin;
    const displayUrl = `${siteUrl}/${postSlug || 'post-url'}`;

    return (
        <>
            {/* Connection Status */}
            {!connected && (
                <Notice status="warning" isDismissible={false}>
                    <p>{__('Not connected to InstaRank.', 'instarank')}</p>
                    <Button
                        isSecondary
                        href="/wp-admin/admin.php?page=instarank"
                        target="_blank"
                    >
                        {__('Connect Now', 'instarank')}
                    </Button>
                </Notice>
            )}

            {/* Pending Changes Alert */}
            {pendingChanges > 0 && (
                <Notice status="info" isDismissible={false}>
                    <p>
                        {pendingChanges === 1
                            ? __('1 pending change from InstaRank', 'instarank')
                            : __(`${pendingChanges} pending changes from InstaRank`, 'instarank')}
                    </p>
                    <Button
                        isPrimary
                        href="/wp-admin/admin.php?page=instarank-changes"
                        target="_blank"
                    >
                        {__('Review Changes', 'instarank')}
                    </Button>
                </Notice>
            )}

            {/* pSEO Dataset Fields - Show first if this is a generated page */}
            <PseoFieldsPanel pseoData={pseoData} onFieldChange={handlePseoFieldChange} />

            {/* SERP Preview */}
            <PanelBody title={__('Google Preview', 'instarank')} initialOpen={true}>
                <SerpPreview
                    title={displayTitle}
                    description={displayDescription}
                    url={displayUrl}
                />
            </PanelBody>

            {/* Tabbed Interface */}
            <TabPanel
                className="instarank-tabs"
                activeClass="is-active"
                tabs={[
                    {
                        name: 'general',
                        title: __('General', 'instarank'),
                    },
                    {
                        name: 'social',
                        title: __('Social', 'instarank'),
                    },
                    {
                        name: 'advanced',
                        title: __('Advanced', 'instarank'),
                    },
                ]}
            >
                {(tab) => (
                    <>
                        {tab.name === 'general' && (
                            <>
                                {/* Meta Title */}
                                <PanelBody title={__('SEO Title', 'instarank')} initialOpen={true}>
                                    <TextControl
                                        label={__('Meta Title', 'instarank')}
                                        value={metaTitle}
                                        onChange={(value) => {
                                            setMetaTitle(value);
                                            saveMeta('instarank_meta_title', value);
                                        }}
                                        placeholder={postTitle || __('Enter SEO title...', 'instarank')}
                                        help={__('If empty, post title will be used', 'instarank')}
                                    />
                                    <CharacterCounter
                                        current={(metaTitle || postTitle).length}
                                        max={limits.titleMax}
                                        optimal={limits.titleOptimal}
                                    />
                                </PanelBody>

                                {/* Meta Description */}
                                <PanelBody title={__('Meta Description', 'instarank')} initialOpen={true}>
                                    <TextareaControl
                                        label={__('Meta Description', 'instarank')}
                                        value={metaDescription}
                                        onChange={(value) => {
                                            setMetaDescription(value);
                                            saveMeta('instarank_meta_description', value);
                                        }}
                                        placeholder={__('Enter meta description...', 'instarank')}
                                        rows={3}
                                    />
                                    <CharacterCounter
                                        current={metaDescription.length}
                                        max={limits.descriptionMax}
                                        optimal={limits.descriptionOptimal}
                                    />
                                </PanelBody>

                                {/* Focus Keyword */}
                                <PanelBody title={__('Focus Keyword', 'instarank')} initialOpen={false}>
                                    <TextControl
                                        label={__('Focus Keyword', 'instarank')}
                                        value={focusKeyword}
                                        onChange={(value) => {
                                            setFocusKeyword(value);
                                            saveMeta('instarank_focus_keyword', value);
                                        }}
                                        placeholder={__('Enter target keyword...', 'instarank')}
                                        help={__('The main keyword you want this content to rank for', 'instarank')}
                                    />
                                    <FocusKeywordAnalysis
                                        keyword={focusKeyword}
                                        title={displayTitle}
                                        description={metaDescription}
                                        content={postContent}
                                        url={postSlug}
                                    />
                                </PanelBody>
                            </>
                        )}

                        {tab.name === 'social' && (
                            <>
                                {/* Open Graph */}
                                <PanelBody title={__('Facebook / Open Graph', 'instarank')} initialOpen={true}>
                                    <TextControl
                                        label={__('OG Title', 'instarank')}
                                        value={ogTitle}
                                        onChange={(value) => {
                                            setOgTitle(value);
                                            saveMeta('instarank_og_title', value);
                                        }}
                                        placeholder={metaTitle || postTitle}
                                    />
                                    <TextareaControl
                                        label={__('OG Description', 'instarank')}
                                        value={ogDescription}
                                        onChange={(value) => {
                                            setOgDescription(value);
                                            saveMeta('instarank_og_description', value);
                                        }}
                                        placeholder={metaDescription}
                                        rows={2}
                                    />
                                    <TextControl
                                        label={__('OG Image URL', 'instarank')}
                                        value={ogImage}
                                        onChange={(value) => {
                                            setOgImage(value);
                                            saveMeta('instarank_og_image', value);
                                        }}
                                        placeholder={__('https://example.com/image.jpg', 'instarank')}
                                    />
                                </PanelBody>

                                {/* Twitter Card */}
                                <PanelBody title={__('Twitter Card', 'instarank')} initialOpen={false}>
                                    <TextControl
                                        label={__('Twitter Title', 'instarank')}
                                        value={twitterTitle}
                                        onChange={(value) => {
                                            setTwitterTitle(value);
                                            saveMeta('instarank_twitter_title', value);
                                        }}
                                        placeholder={ogTitle || metaTitle || postTitle}
                                    />
                                    <TextareaControl
                                        label={__('Twitter Description', 'instarank')}
                                        value={twitterDescription}
                                        onChange={(value) => {
                                            setTwitterDescription(value);
                                            saveMeta('instarank_twitter_description', value);
                                        }}
                                        placeholder={ogDescription || metaDescription}
                                        rows={2}
                                    />
                                    <TextControl
                                        label={__('Twitter Image URL', 'instarank')}
                                        value={twitterImage}
                                        onChange={(value) => {
                                            setTwitterImage(value);
                                            saveMeta('instarank_twitter_image', value);
                                        }}
                                        placeholder={ogImage}
                                    />
                                </PanelBody>
                            </>
                        )}

                        {tab.name === 'advanced' && (
                            <>
                                {/* Canonical URL */}
                                <PanelBody title={__('Canonical URL', 'instarank')} initialOpen={true}>
                                    <TextControl
                                        label={__('Canonical URL', 'instarank')}
                                        value={canonical}
                                        onChange={(value) => {
                                            setCanonical(value);
                                            saveMeta('instarank_canonical', value);
                                        }}
                                        placeholder={displayUrl}
                                        help={__('Leave empty to use default URL', 'instarank')}
                                    />
                                </PanelBody>

                                {/* Robots Settings */}
                                <PanelBody title={__('Robots Meta', 'instarank')} initialOpen={false}>
                                    <ToggleControl
                                        label={__('No Index', 'instarank')}
                                        checked={robotsNoindex}
                                        onChange={(value) => {
                                            setRobotsNoindex(value);
                                            saveMeta('instarank_robots_noindex', value ? '1' : '0');
                                        }}
                                        help={__('Prevent search engines from indexing this page', 'instarank')}
                                    />
                                </PanelBody>
                            </>
                        )}
                    </>
                )}
            </TabPanel>

            {/* Footer Actions */}
            <div className="instarank-panel-footer">
                <ExternalLink href="/wp-admin/admin.php?page=instarank-settings">
                    {__('Plugin Settings', 'instarank')}
                </ExternalLink>
                {connected && (
                    <ExternalLink href={`${window.instarankGutenberg.apiUrl}/projects/${projectId}`}>
                        {__('Open InstaRank Dashboard', 'instarank')}
                    </ExternalLink>
                )}
            </div>
        </>
    );
};

// Register the plugin
registerPlugin('instarank-seo', {
    render: () => (
        <>
            <PluginSidebarMoreMenuItem target="instarank-seo-sidebar">
                {__('InstaRank SEO', 'instarank')}
            </PluginSidebarMoreMenuItem>
            <PluginSidebar
                name="instarank-seo-sidebar"
                title={__('InstaRank SEO', 'instarank')}
                icon="chart-line"
            >
                <InstaRankPanel />
            </PluginSidebar>
        </>
    ),
});
