import './style.css';
import {
    InspectorControls,
    MediaUpload,
    MediaUploadCheck,
    useBlockProps
} from '@wordpress/block-editor';

import {
    PanelBody,
    SelectControl,
    RangeControl,
    Button,
    Spinner,
    TextControl
} from '@wordpress/components';

import { useState, useEffect } from '@wordpress/element';
import { EZHP_UI, EZHP_ZODIAC, isRtlLanguage } from './i18n';

export default function Edit({ attributes, setAttributes }) {

    const {
        language = 'en',
        heroImageUrl = '',
        heroImageAlt = '',
        heroImageTextWrap = 'none',
        heroImageMaxWidth = '40%',
    } = attributes;

    // EDITOR-ONLY STATE
    const [loading, setLoading] = useState(false);
    const [previewHtml, setPreviewHtml] = useState('');
    const [yourSign, setYourSign] = useState('');
    const [theirSign, setTheirSign] = useState('');
    const [rawHtml, setRawHtml] = useState('');

    // Rebuild preview when inline hero settings change
    useEffect(() => {
        if (!rawHtml) return;
        const finalHtml = injectInlineHero(rawHtml);
        setPreviewHtml(finalHtml);
    }, [
        rawHtml,
        heroImageUrl,
        heroImageAlt,
        heroImageTextWrap,
        heroImageMaxWidth
    ]);



    // Determine if RTL
    const isRtl = isRtlLanguage(language);

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

    /* ---------------------------------------------------------
       INLINE HERO INJECTION
    --------------------------------------------------------- */
    function injectInlineHero(html) {
        if (!html) return html;

        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const firstH2 = doc.querySelector('h2');

        if (!firstH2) return html;

        // Build inline hero container
        if (heroImageUrl) {
            // Build wrapper WITHOUT float in inline styles (theme-safe)
            const ezhp_floatClass =
                heroImageTextWrap === 'left' ? 'ez-wrap-left' :
                    heroImageTextWrap === 'right' ? 'ez-wrap-right' :
                        '';

            const wrapper = `
    <img 
    src="${heroImageUrl}" 
    alt="${heroImageAlt}" 
    class="ez-inline-hero-img ${ezhp_floatClass}"
    style="border-radius:8px;max-width:${heroImageMaxWidth};height:auto;"
>
`;

            // Insert based on wrap mode
            if (heroImageTextWrap === 'none') {
                // Insert ABOVE the H2
                firstH2.insertAdjacentHTML('beforebegin', wrapper);
            } else {
                // Insert INSIDE the H2 so heading + paragraphs wrap
                firstH2.insertAdjacentHTML('afterbegin', wrapper);
            }

        }

        return doc.body.innerHTML;
    }

    /* ---------------------------------------------------------
       FETCH COMPATIBILITY (EDITOR ONLY)
    --------------------------------------------------------- */
    async function fetchCompatibility() {

        if (!yourSign || !theirSign) return;

        setLoading(true);

        try {
            const response = await wp.apiFetch({
                path: `ezhp/v1/zodiac-compatibility?yourSign=${encodeURIComponent(yourSign)}&theirSign=${encodeURIComponent(theirSign)}&language=${encodeURIComponent(language)}`
            });

            const html = response?.html || '<div>Unable to load compatibility.</div>';

            // Store raw API HTML for reprocessing
            setRawHtml(html);

        } catch (err) {
            setRawHtml('<div>Error loading compatibility.</div>');
        }

        setLoading(false);
    }

    const zodiacOptions = [
        { label: '--', value: '' },
        ...Object.keys(EZHP_ZODIAC[language] || {}).map(sign => ({
            label: EZHP_ZODIAC[language][sign],
            value: sign
        }))
    ];

    /* ---------------------------------------------------------
       EDITOR MARKUP
    --------------------------------------------------------- */
    return (
        <>
            <InspectorControls>
                <PanelBody title="Settings" initialOpen={true}>

                    <TextControl
                        label="Language"
                        value={language}
                        onChange={(value) => setAttributes({ language: value })}
                        help="Example: en, es, fr, de, hi, etc."
                    />

                </PanelBody>

                <PanelBody title="Inline Hero Image" initialOpen={false}>

                    <MediaUploadCheck>
                        <MediaUpload
                            onSelect={(media) =>
                                setAttributes({
                                    heroImageUrl: media.url,
                                    heroImageAlt: media.alt || '',
                                })
                            }
                            allowedTypes={['image']}
                            render={({ open }) => (
                                heroImageUrl ? (
                                    <>
                                        <img
                                            src={heroImageUrl}
                                            alt={heroImageAlt}
                                            style={{ maxWidth: '100%', marginBottom: '5px' }}
                                        />
                                        <Button
                                            isDestructive
                                            variant="secondary"
                                            onClick={() =>
                                                setAttributes({ heroImageUrl: '', heroImageAlt: '' })
                                            }
                                        >
                                            Remove Image
                                        </Button>
                                    </>
                                ) : (
                                    <Button variant="primary" onClick={open}>
                                        Select Image
                                    </Button>
                                )
                            )}
                        />
                    </MediaUploadCheck>

                    <SelectControl
                        label="Text Wrap"
                        value={heroImageTextWrap}
                        options={[
                            { label: 'None', value: 'none' },
                            { label: 'Wrap Left', value: 'left' },
                            { label: 'Wrap Right', value: 'right' },
                        ]}
                        onChange={(value) =>
                            setAttributes({ heroImageTextWrap: value })
                        }
                    />

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

                </PanelBody>
            </InspectorControls>

            {/* Editor UI */}
            <div {...blockProps}>

                <div className="ezhp-form" style={{ marginBottom: '15px' }}>

                    <label style={{ fontWeight: '600' }}>
                        {(EZHP_UI[language] || EZHP_UI['en']).yourSign}
                    </label>
                    <SelectControl
                        value={yourSign}
                        options={zodiacOptions}
                        onChange={(value) => setYourSign(value)}
                    />

                    <label style={{ fontWeight: '600', marginTop: '10px' }}>
                        {(EZHP_UI[language] || EZHP_UI['en']).theirSign}
                    </label>
                    <SelectControl
                        value={theirSign}
                        options={zodiacOptions}
                        onChange={(value) => setTheirSign(value)}
                    />

                    <Button
                        variant="primary"
                        style={{ marginTop: '10px' }}
                        onClick={fetchCompatibility}
                        disabled={!yourSign || !theirSign}
                    >
                        {(EZHP_UI[language] || EZHP_UI['en']).button}
                    </Button>

                </div>


                {/* Live Preview */}
                <div className="ezhp-compatibility-result-editor" style={{ padding: '10px' }}>
                    {loading && (
                        <div>
                            <div className="ezhp-progress-container">
                                <div className="ezhp-progress-bar"></div>
                            </div>
                            <p>{(EZHP_UI[language] || EZHP_UI['en']).loading}</p>
                        </div>
                    )}
                    {!loading && previewHtml && (
                        <div dangerouslySetInnerHTML={{ __html: previewHtml }}></div>
                    )}
                </div>

            </div>
        </>
    );
}