import './style.css';
import { useState } from '@wordpress/element';
import {
    InspectorControls,
    MediaUpload,
    MediaUploadCheck,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    SelectControl,
    ToggleControl,
    TextControl,
    TextareaControl,
    RangeControl,
    Button,
    ButtonGroup,
    ColorPicker
} from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';

// RTL language codes
const RTL_LANGUAGES = [
    'ar', 'he', 'fa', 'ur', 'ps', 'sd', 'yi', 'ku', 'dv', 'ug',
    'arc', 'azb', 'ckb', 'mzn', 'pnb', 'ks', 'glk', 'bal', 'bqi',
    'luz', 'gbz', 'khw', 'lrc', 'prd', 'sdh', 'skr'
];

// Check if language code is RTL
const isRtlLanguage = (lang) => {
    if (!lang) return false;
    const baseLang = lang.toLowerCase().split('-')[0];
    return RTL_LANGUAGES.includes(baseLang);
};

// Get default images URL from localized script data
const getDefaultImagesUrl = () => {
    if (typeof ezWeeklyHoroscopeData !== 'undefined' && ezWeeklyHoroscopeData.defaultImagesUrl) {
        return ezWeeklyHoroscopeData.defaultImagesUrl;
    }
    return '';
};

// Get zodiac images URL from localized script data
const getZodiacImagesUrl = () => {
    if (typeof ezWeeklyHoroscopeData !== 'undefined' && ezWeeklyHoroscopeData.zodiacImagesUrl) {
        return ezWeeklyHoroscopeData.zodiacImagesUrl;
    }
    return '';
};

// Get the default hero image URL for a zodiac sign
const getDefaultHeroImageUrl = (sign) => {
    const baseUrl = getZodiacImagesUrl();
    if (baseUrl && sign) {
        return baseUrl + 'ez-' + sign + '.jpg';
    }
    return '';
};

// Map of section keys to default image filenames
const DEFAULT_IMAGE_FILES = {
    sundayImageUrl: 'sun.jpg',
    mondayImageUrl: 'moon.jpg',
    tuesdayImageUrl: 'mars.jpg',
    wednesdayImageUrl: 'mercury.jpg',
    thursdayImageUrl: 'jupiter.jpg',
    fridayImageUrl: 'venus.jpg',
    saturdayImageUrl: 'saturn.jpg',
    summaryImageUrl: 'cosmos.jpg',
};

// Get the default image URL for a given key
const getDefaultImageUrl = (key) => {
    const baseUrl = getDefaultImagesUrl();
    const filename = DEFAULT_IMAGE_FILES[key];
    if (baseUrl && filename) {
        return baseUrl + filename;
    }
    return '';
};

// Reusable component for daily image upload - now shows default images
const DailyImageUpload = ({ label, imageUrl, imageKey, onSelect, onRemove }) => {
    const defaultImageUrl = getDefaultImageUrl(imageKey);
    const isUsingDefault = !imageUrl && defaultImageUrl;
    const displayUrl = imageUrl || defaultImageUrl;

    return (
        <div style={{ marginBottom: '15px', paddingBottom: '15px', borderBottom: '1px solid #e0e0e0' }}>
            <p style={{ fontWeight: '600', marginBottom: '8px' }}>
                {label}
                {isUsingDefault && (
                    <span style={{ 
                        fontWeight: '400', 
                        fontSize: '11px', 
                        color: '#757575',
                        marginLeft: '8px',
                        backgroundColor: '#f0f0f0',
                        padding: '2px 6px',
                        borderRadius: '3px'
                    }}>
                        Default
                    </span>
                )}
            </p>
            <MediaUploadCheck>
                <MediaUpload
                    onSelect={onSelect}
                    allowedTypes={['image']}
                    render={({ open }) => (
                        <div>
                            {displayUrl ? (
                                <>
                                    <img
                                        src={displayUrl}
                                        alt={label}
                                        style={{
                                            maxWidth: '100%',
                                            maxHeight: '80px',
                                            objectFit: 'cover',
                                            borderRadius: '4px',
                                            marginBottom: '5px',
                                            display: 'block',
                                            opacity: isUsingDefault ? 0.8 : 1,
                                            border: isUsingDefault ? '2px dashed #ccc' : 'none',
                                        }}
                                    />
                                    <div style={{ display: 'flex', gap: '5px' }}>
                                        <Button variant="secondary" onClick={open} size="small">
                                            {isUsingDefault ? 'Replace Default' : 'Replace'}
                                        </Button>
                                        {!isUsingDefault && (
                                            <Button isDestructive variant="secondary" onClick={onRemove} size="small">
                                                Use Default
                                            </Button>
                                        )}
                                    </div>
                                </>
                            ) : (
                                <Button variant="secondary" onClick={open} size="small">
                                    Select Image
                                </Button>
                            )}
                        </div>
                    )}
                />
            </MediaUploadCheck>
        </div>
    );
};

export default function Edit({ attributes, setAttributes }) {
    const {
        sign = 'aries',
        language = 'en',
        suppressHeading = false,
        columnLayout = 1,
        heroImageUrl = '',
        heroImageAlt = '',
        heroImageDisplayMode = 'inline',
        heroImageAlignment = 'center',
        heroImageTextWrap = 'none',
        heroImageOverlayOpacity = 50,
        heroImageOverlayColor = 'black',
        heroImageMaxWidth = '40%',
        // Daily background images
        sundayImageUrl = '',
        mondayImageUrl = '',
        tuesdayImageUrl = '',
        wednesdayImageUrl = '',
        thursdayImageUrl = '',
        fridayImageUrl = '',
        saturdayImageUrl = '',
        summaryImageUrl = '',
        // Shared daily image controls - NEW DEFAULTS
        dailyImageDisplayMode = 'inline',
        dailyImageAlignment = 'center',
        dailyImageTextWrap = 'left',
        dailyImageMaxWidth = '40%',
        dailyImageOverlayOpacity = 40,
        dailyImageOverlayColor = 'black',
        // CTA settings
        ctaPlacement = 'none',
        ctaHeadline = '',
        ctaHeadingLevel = 'h3',
        ctaText = '',
        ctaButtonText = '',
        ctaButtonUrl = '',
        ctaImageUrl = '',
        ctaImageAlt = '',
        ctaImageClickable = true,
        ctaImageMaxWidth = '100%',
        ctaBackgroundColor = '',
        ctaBackgroundTransparent = false,
        ctaButtonColor = '',
        sectionHeadingLevel = 'bold',
    } = attributes;

    const isRtl = isRtlLanguage(language);

    // Check if EyeDropper API is supported
    const hasEyeDropper = typeof window !== 'undefined' && 'EyeDropper' in window;

    const signs = [
        { label: 'Aries', value: 'aries' },
        { label: 'Taurus', value: 'taurus' },
        { label: 'Gemini', value: 'gemini' },
        { label: 'Cancer', value: 'cancer' },
        { label: 'Leo', value: 'leo' },
        { label: 'Virgo', value: 'virgo' },
        { label: 'Libra', value: 'libra' },
        { label: 'Scorpio', value: 'scorpio' },
        { label: 'Sagittarius', value: 'sagittarius' },
        { label: 'Capricorn', value: 'capricorn' },
        { label: 'Aquarius', value: 'aquarius' },
        { label: 'Pisces', value: 'pisces' },
    ];

    const blockProps = useBlockProps({
        className: `ez-horoscope-block${isRtl ? ' ez-horoscope-rtl' : ''}`,
        style: { border: '1px solid #ddd', padding: '10px', borderRadius: '6px' },
        dir: isRtl ? 'rtl' : undefined,
    });

    // Daily image configuration
    const dailyImages = [
        { key: 'sundayImageUrl', label: 'Sunday', value: sundayImageUrl },
        { key: 'mondayImageUrl', label: 'Monday', value: mondayImageUrl },
        { key: 'tuesdayImageUrl', label: 'Tuesday', value: tuesdayImageUrl },
        { key: 'wednesdayImageUrl', label: 'Wednesday', value: wednesdayImageUrl },
        { key: 'thursdayImageUrl', label: 'Thursday', value: thursdayImageUrl },
        { key: 'fridayImageUrl', label: 'Friday', value: fridayImageUrl },
        { key: 'saturdayImageUrl', label: 'Saturday', value: saturdayImageUrl },
        { key: 'summaryImageUrl', label: 'Weekly Summary', value: summaryImageUrl },
    ];

    // Count how many daily images are customized (not using default)
    const dailyImagesCustomized = dailyImages.filter(img => img.value).length;

    return (
        <>
            <InspectorControls>
                {/* Horoscope Settings */}
                <PanelBody title="Horoscope Settings" initialOpen={true}>
                    <SelectControl
                        label="Zodiac Sign"
                        value={sign}
                        options={signs}
                        onChange={(value) => setAttributes({ sign: value })}
                    />
                    <TextControl
                        label="Language"
                        value={language}
                        onChange={(value) => setAttributes({ language: value })}
                        help={`Enter language code (e.g., en, es, fr, de, ar, he)${isRtl ? ' — RTL detected' : ''}`}
                    />
                    <ToggleControl
                        label="Hide Horoscope Heading (H1)"
                        checked={suppressHeading}
                        onChange={(value) => setAttributes({ suppressHeading: !!value })}
                    />
                    <SelectControl
                        label="Section Headings"
                        value={sectionHeadingLevel}
                        options={[
                            { label: 'Bold Text (Default)', value: 'bold' },
                            { label: 'H2 Heading', value: 'h2' },
                            { label: 'H3 Heading', value: 'h3' },
                            { label: 'H4 Heading', value: 'h4' },
                        ]}
                        onChange={(value) => setAttributes({ sectionHeadingLevel: value })}
                        help="Change the heading level for daily section headers (Week Ahead, Sunday, Monday, etc.)"
                    />
                </PanelBody>

                {/* Layout Settings */}
                <PanelBody title="Layout Settings" initialOpen={true}>
                    <div style={{ marginBottom: '16px' }}>
                        <p style={{ marginBottom: '8px', fontWeight: '500' }}>Column Layout</p>
                        <ButtonGroup>
                            {[1, 2, 3].map((cols) => (
                                <Button
                                    key={cols}
                                    variant={columnLayout === cols ? 'primary' : 'secondary'}
                                    onClick={() => setAttributes({ columnLayout: cols })}
                                >
                                    {cols} {cols === 1 ? 'Column' : 'Columns'}
                                </Button>
                            ))}
                        </ButtonGroup>
                    </div>
                </PanelBody>

                {/* Hero Image Settings */}
                <PanelBody title="Hero Image" initialOpen={false}>
                    <MediaUploadCheck>
                        <MediaUpload
                            onSelect={(media) => setAttributes({ 
                                heroImageUrl: media.url,
                                heroImageAlt: media.alt || ''
                            })}
                            allowedTypes={['image']}
                            render={({ open }) => {
                                const defaultHeroUrl = getDefaultHeroImageUrl(sign);
                                const isUsingDefault = !heroImageUrl && defaultHeroUrl;
                                const displayUrl = heroImageUrl || defaultHeroUrl;

                                return (
                                    <div style={{ marginBottom: '15px' }}>
                                        {displayUrl ? (
                                            <>
                                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>
                                                    Hero Image
                                                    {isUsingDefault && (
                                                        <span style={{ 
                                                            fontWeight: '400', 
                                                            fontSize: '11px', 
                                                            color: '#757575',
                                                            marginLeft: '8px',
                                                            backgroundColor: '#f0f0f0',
                                                            padding: '2px 6px',
                                                            borderRadius: '3px'
                                                        }}>
                                                            Default
                                                        </span>
                                                    )}
                                                </p>
                                                <img
                                                    src={displayUrl}
                                                    alt={heroImageAlt}
                                                    style={{
                                                        maxWidth: '100%',
                                                        maxHeight: '150px',
                                                        objectFit: 'cover',
                                                        borderRadius: '4px',
                                                        marginBottom: '10px',
                                                        display: 'block',
                                                        opacity: isUsingDefault ? 0.8 : 1,
                                                        border: isUsingDefault ? '2px dashed #ccc' : 'none',
                                                    }}
                                                />
                                                <div style={{ display: 'flex', gap: '8px' }}>
                                                    <Button variant="secondary" onClick={open}>
                                                        {isUsingDefault ? 'Replace Default' : 'Replace Image'}
                                                    </Button>
                                                    {!isUsingDefault && (
                                                        <Button
                                                            isDestructive
                                                            variant="secondary"
                                                            onClick={() => setAttributes({ 
                                                                heroImageUrl: '',
                                                                heroImageAlt: ''
                                                            })}
                                                        >
                                                            Use Default
                                                        </Button>
                                                    )}
                                                </div>
                                            </>
                                        ) : (
                                            <Button variant="secondary" onClick={open}>
                                                Select Hero Image
                                            </Button>
                                        )}
                                    </div>
                                );
                            }}
                        />
                    </MediaUploadCheck>

                    <SelectControl
                        label="Display Mode"
                        value={heroImageDisplayMode}
                        options={[
                            { label: 'Background', value: 'background' },
                            { label: 'Inline', value: 'inline' },
                        ]}
                        onChange={(value) => setAttributes({ heroImageDisplayMode: value })}
                    />

                    {heroImageDisplayMode === 'background' && (
                        <SelectControl
                            label="Image Position"
                            value={heroImageAlignment}
                            options={[
                                { label: 'Center', value: 'center' },
                                { label: 'Top', value: 'top' },
                                { label: 'Bottom', value: 'bottom' },
                                { label: 'Left', value: 'left' },
                                { label: 'Right', value: 'right' },
                            ]}
                            onChange={(value) => setAttributes({ heroImageAlignment: value })}
                        />
                    )}

                    {heroImageDisplayMode === 'inline' && (
                        <>
                            <SelectControl
                                label="Text Wrapping"
                                value={heroImageTextWrap}
                                options={[
                                    { label: 'None (Centered)', value: 'none' },
                                    { label: 'Wrap Left', value: 'left' },
                                    { label: 'Wrap Right', value: 'right' },
                                ]}
                                onChange={(value) => setAttributes({ heroImageTextWrap: value })}
                                help={isRtl ? 'Note: Left/Right will be mirrored for RTL languages' : ''}
                            />

                            <RangeControl
                                label="Max Image Width (%)"
                                value={parseInt(heroImageMaxWidth.replace('%', '')) || 40}
                                onChange={(value) => setAttributes({ heroImageMaxWidth: value + '%' })}
                                min={10}
                                max={100}
                                step={5}
                            />
                        </>
                    )}

                    <RangeControl
                        label="Overlay Opacity (%)"
                        value={heroImageOverlayOpacity ?? 50}
                        onChange={(value) => setAttributes({ heroImageOverlayOpacity: value })}
                        min={0}
                        max={100}
                        step={5}
                        help="Adjust overlay transparency (0% transparent — 100% opaque)."
                    />

                    <SelectControl
                        label="Overlay Color"
                        value={heroImageOverlayColor}
                        options={[
                            { label: 'Black (dark)', value: 'black' },
                            { label: 'White (light)', value: 'white' },
                        ]}
                        onChange={(value) => setAttributes({ heroImageOverlayColor: value })}
                        help="Choose dark or light tint depending on your image brightness."
                    />
                </PanelBody>

                {/* Daily Background Images */}
                <PanelBody 
                    title={`Daily Images${dailyImagesCustomized > 0 ? ` (${dailyImagesCustomized}/8 customized)` : ''}`} 
                    initialOpen={false}
                >
                    <p style={{ marginBottom: '15px', color: '#757575', fontSize: '12px' }}>
                        Each day shows a default planet image. Select a custom image to override.
                    </p>

                    {/* Shared Controls Section */}
                    <div style={{ 
                        marginBottom: '20px', 
                        paddingBottom: '15px', 
                        borderBottom: '2px solid #007cba',
                        backgroundColor: '#f0f6fc',
                        padding: '12px',
                        borderRadius: '4px'
                    }}>
                        <p style={{ fontWeight: '600', marginBottom: '12px', color: '#007cba' }}>
                            Shared Image Settings
                        </p>
                        
                        <SelectControl
                            label="Display Mode"
                            value={dailyImageDisplayMode}
                            options={[
                                { label: 'Background', value: 'background' },
                                { label: 'Inline', value: 'inline' },
                            ]}
                            onChange={(value) => setAttributes({ dailyImageDisplayMode: value })}
                            help={dailyImageDisplayMode === 'background' 
                                ? 'Images replace the section background.' 
                                : 'Images display inline with text wrapping.'}
                        />

                        {dailyImageDisplayMode === 'background' && (
                            <SelectControl
                                label="Background Position"
                                value={dailyImageAlignment}
                                options={[
                                    { label: 'Center', value: 'center' },
                                    { label: 'Top', value: 'top' },
                                    { label: 'Bottom', value: 'bottom' },
                                    { label: 'Left', value: 'left' },
                                    { label: 'Right', value: 'right' },
                                    { label: 'Top Left', value: 'top left' },
                                    { label: 'Top Right', value: 'top right' },
                                    { label: 'Bottom Left', value: 'bottom left' },
                                    { label: 'Bottom Right', value: 'bottom right' },
                                ]}
                                onChange={(value) => setAttributes({ dailyImageAlignment: value })}
                            />
                        )}

                        {dailyImageDisplayMode === 'inline' && (
                            <>
                                <SelectControl
                                    label="Text Wrapping"
                                    value={dailyImageTextWrap}
                                    options={[
                                        { label: 'None (Centered)', value: 'none' },
                                        { label: 'Wrap Left', value: 'left' },
                                        { label: 'Wrap Right', value: 'right' },
                                    ]}
                                    onChange={(value) => setAttributes({ dailyImageTextWrap: value })}
                                    help={isRtl ? 'Note: Left/Right will be mirrored for RTL languages' : ''}
                                />

                                <RangeControl
                                    label="Max Image Width (%)"
                                    value={parseInt(dailyImageMaxWidth.replace('%', '')) || 40}
                                    onChange={(value) => setAttributes({ dailyImageMaxWidth: value + '%' })}
                                    min={10}
                                    max={100}
                                    step={5}
                                />
                            </>
                        )}

                        <RangeControl
                            label="Overlay Opacity (%)"
                            value={dailyImageOverlayOpacity ?? 40}
                            onChange={(value) => setAttributes({ dailyImageOverlayOpacity: value })}
                            min={0}
                            max={100}
                            step={5}
                            help="Darkness/lightness of the overlay (0% = no overlay)."
                        />

                        <SelectControl
                            label="Overlay Color"
                            value={dailyImageOverlayColor}
                            options={[
                                { label: 'Black (dark)', value: 'black' },
                                { label: 'White (light)', value: 'white' },
                            ]}
                            onChange={(value) => setAttributes({ dailyImageOverlayColor: value })}
                            help="Dark overlay for light images, light overlay for dark images."
                        />
                    </div>

                    {/* Individual Image Uploads */}
                    {dailyImages.map(({ key, label, value }) => (
                        <DailyImageUpload
                            key={key}
                            label={label}
                            imageUrl={value}
                            imageKey={key}
                            onSelect={(media) => setAttributes({ [key]: media.url })}
                            onRemove={() => setAttributes({ [key]: '' })}
                        />
                    ))}

                    {dailyImagesCustomized > 0 && (
                        <Button
                            isDestructive
                            variant="secondary"
                            onClick={() => {
                                const resetAttrs = {};
                                dailyImages.forEach(({ key }) => {
                                    resetAttrs[key] = '';
                                });
                                setAttributes(resetAttrs);
                            }}
                            style={{ marginTop: '10px' }}
                        >
                            Reset All to Defaults
                        </Button>
                    )}
                </PanelBody>

                {/* Call to Action */}
                <PanelBody 
                    title={`Call to Action${ctaPlacement !== 'none' ? ' ✓' : ''} (Premium)`}
                    initialOpen={false}
                >
                    <SelectControl
                        label="Placement"
                        value={ctaPlacement}
                        options={[
                            { label: 'Disabled', value: 'none' },
                            { label: 'After Week Ahead', value: 'after-week-ahead' },
                            { label: 'After Sunday', value: 'after-sunday' },
                            { label: 'After Monday', value: 'after-monday' },
                            { label: 'After Tuesday', value: 'after-tuesday' },
                            { label: 'After Wednesday', value: 'after-wednesday' },
                            { label: 'After Thursday', value: 'after-thursday' },
                            { label: 'After Friday', value: 'after-friday' },
                            { label: 'After Saturday', value: 'after-saturday' },
                            { label: 'After Summary (End)', value: 'after-summary' },
                        ]}
                        onChange={(value) => setAttributes({ ctaPlacement: value })}
                        help="Choose where the CTA appears in the weekly horoscope."
                    />

                    {ctaPlacement !== 'none' && (
                        <>
                            {/* Headline */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <TextControl
                                    label="Headline"
                                    value={ctaHeadline}
                                    onChange={(value) => setAttributes({ ctaHeadline: value })}
                                    placeholder="e.g., Unlock Your Full Reading"
                                />
                                <SelectControl
                                    label="Heading Level"
                                    value={ctaHeadingLevel}
                                    options={[
                                        { label: 'H2', value: 'h2' },
                                        { label: 'H3', value: 'h3' },
                                        { label: 'H4', value: 'h4' },
                                    ]}
                                    onChange={(value) => setAttributes({ ctaHeadingLevel: value })}
                                />
                            </div>

                            {/* Description Text */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <TextareaControl
                                    label="Description"
                                    value={ctaText}
                                    onChange={(value) => setAttributes({ ctaText: value })}
                                    placeholder="e.g., Get personalized insights and detailed predictions..."
                                    rows={3}
                                />
                            </div>

                            {/* Button */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>Button</p>
                                <TextControl
                                    label="Button Text"
                                    value={ctaButtonText}
                                    onChange={(value) => setAttributes({ ctaButtonText: value })}
                                    placeholder="e.g., Get Premium"
                                />
                                <TextControl
                                    label="Button URL"
                                    value={ctaButtonUrl}
                                    onChange={(value) => setAttributes({ ctaButtonUrl: value })}
                                    placeholder="e.g., https://example.com/premium"
                                    type="url"
                                />
                            </div>

                            {/* Image */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>Image</p>
                                <MediaUploadCheck>
                                    <MediaUpload
                                        onSelect={(media) => setAttributes({ 
                                            ctaImageUrl: media.url,
                                            ctaImageAlt: media.alt || ''
                                        })}
                                        allowedTypes={['image']}
                                        render={({ open }) => (
                                            <div>
                                                {ctaImageUrl ? (
                                                    <>
                                                        <img
                                                            src={ctaImageUrl}
                                                            alt={ctaImageAlt}
                                                            style={{
                                                                maxWidth: '100%',
                                                                maxHeight: '120px',
                                                                objectFit: 'cover',
                                                                borderRadius: '4px',
                                                                marginBottom: '8px',
                                                                display: 'block',
                                                            }}
                                                        />
                                                        <div style={{ display: 'flex', gap: '5px', marginBottom: '10px' }}>
                                                            <Button variant="secondary" onClick={open} size="small">
                                                                Replace
                                                            </Button>
                                                            <Button 
                                                                isDestructive 
                                                                variant="secondary" 
                                                                onClick={() => setAttributes({ ctaImageUrl: '', ctaImageAlt: '' })} 
                                                                size="small"
                                                            >
                                                                Remove
                                                            </Button>
                                                        </div>
                                                    </>
                                                ) : (
                                                    <Button variant="secondary" onClick={open} style={{ marginBottom: '10px' }}>
                                                        Select Image
                                                    </Button>
                                                )}
                                            </div>
                                        )}
                                    />
                                </MediaUploadCheck>

                                {ctaImageUrl && (
                                    <>
                                        <TextControl
                                            label="Image Alt Text"
                                            value={ctaImageAlt}
                                            onChange={(value) => setAttributes({ ctaImageAlt: value })}
                                            placeholder="Describe the image"
                                        />
                                        <RangeControl
                                            label="Image Max Width (%)"
                                            value={parseInt(ctaImageMaxWidth.replace('%', '')) || 100}
                                            onChange={(value) => setAttributes({ ctaImageMaxWidth: value + '%' })}
                                            min={10}
                                            max={100}
                                            step={5}
                                        />
                                        <ToggleControl
                                            label="Make image clickable"
                                            checked={ctaImageClickable}
                                            onChange={(value) => setAttributes({ ctaImageClickable: value })}
                                            help={ctaImageClickable ? 'Image will link to the Button URL.' : 'Image will not be clickable.'}
                                        />
                                    </>
                                )}
                            </div>

                            {/* Background Color */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>Background</p>
                                
                                <ToggleControl
                                    label="Transparent background"
                                    checked={ctaBackgroundTransparent}
                                    onChange={(value) => setAttributes({ ctaBackgroundTransparent: value })}
                                />

                                {!ctaBackgroundTransparent && (
                                    <>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '10px' }}>
                                            <div 
                                                style={{
                                                    width: '36px',
                                                    height: '36px',
                                                    borderRadius: '4px',
                                                    border: '1px solid #ccc',
                                                    background: ctaBackgroundColor || 'linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)',
                                                }}
                                            />
                                            <span style={{ fontSize: '12px', color: '#757575' }}>
                                                {ctaBackgroundColor || 'Default gradient'}
                                            </span>
                                            {ctaBackgroundColor && (
                                                <Button
                                                    variant="secondary"
                                                    size="small"
                                                    onClick={() => setAttributes({ ctaBackgroundColor: '' })}
                                                >
                                                    Reset
                                                </Button>
                                            )}
                                        </div>

                                        {hasEyeDropper && (
                                            <Button
                                                variant="secondary"
                                                onClick={async () => {
                                                    try {
                                                        const eyeDropper = new window.EyeDropper();
                                                        const result = await eyeDropper.open();
                                                        setAttributes({ ctaBackgroundColor: result.sRGBHex });
                                                    } catch (e) {
                                                        // User cancelled or error
                                                    }
                                                }}
                                                style={{ marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '5px' }}
                                            >
                                                <span style={{ fontSize: '16px' }}>💧</span> Pick Color from Screen
                                            </Button>
                                        )}

                                        <ColorPicker
                                            color={ctaBackgroundColor || '#1a1a2e'}
                                            onChange={(color) => setAttributes({ ctaBackgroundColor: color })}
                                            enableAlpha={false}
                                        />
                                    </>
                                )}
                            </div>

                            {/* Button Color */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>Button Color</p>
                                
                                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '10px' }}>
                                    <div 
                                        style={{
                                            width: '36px',
                                            height: '36px',
                                            borderRadius: '4px',
                                            border: '1px solid #ccc',
                                            background: ctaButtonColor || 'linear-gradient(135deg, #e94560 0%, #c23a51 100%)',
                                        }}
                                    />
                                    <span style={{ fontSize: '12px', color: '#757575' }}>
                                        {ctaButtonColor || 'Default gradient'}
                                    </span>
                                    {ctaButtonColor && (
                                        <Button
                                            variant="secondary"
                                            size="small"
                                            onClick={() => setAttributes({ ctaButtonColor: '' })}
                                        >
                                            Reset
                                        </Button>
                                    )}
                                </div>

                                {hasEyeDropper && (
                                    <Button
                                        variant="secondary"
                                        onClick={async () => {
                                            try {
                                                const eyeDropper = new window.EyeDropper();
                                                const result = await eyeDropper.open();
                                                setAttributes({ ctaButtonColor: result.sRGBHex });
                                            } catch (e) {
                                                // User cancelled or error
                                            }
                                        }}
                                        style={{ marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '5px' }}
                                    >
                                        <span style={{ fontSize: '16px' }}>💧</span> Pick Color from Screen
                                    </Button>
                                )}

                                <ColorPicker
                                    color={ctaButtonColor || '#e94560'}
                                    onChange={(color) => setAttributes({ ctaButtonColor: color })}
                                    enableAlpha={false}
                                />
                            </div>
                        </>
                    )}
                </PanelBody>
            </InspectorControls>

            {/* Live preview area */}
            <div {...blockProps}>
                <ServerSideRender
                    block="ezhoroscope/weekly-horoscope"
                    attributes={attributes}
                    LoadingResponsePlaceholder={() => (
                        <p style={{ textAlign: isRtl ? 'right' : 'center', opacity: 0.7 }}>
                            Loading preview…
                        </p>
                    )}
                />
            </div>
        </>
    );
}