import './style.css';
import {
    InspectorControls,
    MediaUpload,
    MediaUploadCheck,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    TextControl,
    RangeControl,
    SelectControl,
    Button,
    Spinner,
    ToggleControl
} from '@wordpress/components';
import { useState } from '@wordpress/element';
import { ezhp_t, ezhp_isRTL } from './i18n';

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

    const {
        language = 'en',
        heroImageUrl = '',
        heroImageAlt = '',
        heroImageDisplayMode = 'inline',
        heroImageOverlayOpacity = 50,
        heroImageOverlayColor = 'black',
    } = attributes;

    // EDITOR-ONLY STATES (NOT SAVED)
    const [loading, setLoading] = useState(false);
    const [previewHtml, setPreviewHtml] = useState('');
    const [editorBirthDate, setEditorBirthDate] = useState('');
    const [rawHtml, setRawHtml] = useState('');



    React.useEffect(() => {
        if (!rawHtml) return;
        const finalHtml = buildHero(rawHtml, attributes);
        setPreviewHtml(finalHtml);
    }, [
        rawHtml,
        attributes.heroImageUrl,
        attributes.heroImageAlt,
        attributes.heroImageDisplayMode,
        attributes.heroImageTextWrap,
        attributes.heroImageAlignment,
        attributes.heroImageOverlayOpacity,
        attributes.heroImageOverlayColor,
        attributes.heroImageMaxWidth
    ]);


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

    // ⭐ ADDED — inject inline hero image into horoscopeText
    function ezhpInjectInlineImage(html, heroUrl, heroAlt) {
        if (!heroUrl) return html;

        return html.replace(
            '<section class="chinese-horoscope">',
            `<section class="chinese-horoscope"><img src="${heroUrl}" alt="${heroAlt || ''}" class="ezhp-inline-image">`
        );
    }

    function buildHero(raw, attributes) {
        if (!raw) return '';

        // Parse HTML
        const parser = new DOMParser();
        const doc = parser.parseFromString(raw, 'text/html');
        const section = doc.querySelector('section.chinese-horoscope');

        if (!section) return raw;

        // Extract hero pieces
        const h2 = section.querySelector('h2.horoscope-title');
        const dateP = section.querySelector('p.horoscope-date');
        const introP = section.querySelector('p.horoscope-intro');

        const heroPieces = [];
        if (h2 && !attributes.hideHeading) heroPieces.push(h2.outerHTML);
        if (dateP) heroPieces.push(dateP.outerHTML);
        if (introP) heroPieces.push(introP.outerHTML);

        // Remove them
        if (h2) {
            if (attributes.hideHeading) {
                h2.remove();  // remove completely
            } else {
                h2.remove();  // usual extraction path
            }
        }
        if (dateP) dateP.remove();
        if (introP) introP.remove();

        const bodyHtml = section.innerHTML;

        // Build base hero wrapper
        let heroHTML = `
        <section class="ez-hero">
            <div class="ez-hero-content">
                <div class="ez-hero-text">
                    ${heroPieces.join("")}
                </div>
            </div>
        </section>
    `;

        const mode = attributes.heroImageDisplayMode;
        const heroUrl = attributes.heroImageUrl;
        const heroAlt = attributes.heroImageAlt;

        // INLINE MODE
        if (mode === 'inline' && heroUrl) {
            const wrap = attributes.heroImageTextWrap || 'none';
            const maxWidth = attributes.heroImageMaxWidth || '40%';

            const floatCSS =
                wrap === 'left' ? 'float:left;margin:0 1rem 1rem 0;' :
                    wrap === 'right' ? 'float:right;margin:0 0 1rem 1rem;' :
                        'display:block;margin:0 auto 1rem auto;';

            const inlineImg = `
            <div class="ez-daily-inline-image" style="max-width:${maxWidth};position:relative;">
                <img src="${heroUrl}" alt="${heroAlt}" style="${floatCSS}border-radius:8px;max-width:100%;">
            </div>
        `;

            heroHTML = heroHTML.replace(
                '<div class="ez-hero-text">',
                `<div class="ez-hero-text">${inlineImg}`
            );
        }

        // BACKGROUND MODE
        if (mode === 'background' && heroUrl) {
            const align = attributes.heroImageAlignment || 'center';

            heroHTML = heroHTML.replace(
                '<section class="ez-hero">',
                `<section class="ez-hero" style="background-image:url('${heroUrl}');background-size:cover;background-repeat:no-repeat;background-position:${align};min-height:300px;position:relative;display:flex;flex-direction:column;">`
            );

            const opacity = parseFloat(attributes.heroImageOverlayOpacity || 50) / 100;
            const color = attributes.heroImageOverlayColor === 'white'
                ? '255,255,255'
                : '0,0,0';

            const overlay = `
            <div class="ez-hero-overlay" style="position:absolute;inset:0;background-color:rgba(${color},${opacity});pointer-events:none;border-radius:0;"></div>
        `;

            heroHTML = heroHTML.replace(
                '<div class="ez-hero-content">',
                overlay + '<div class="ez-hero-content">'
            );
        }

        return `
        <section class="chinese-horoscope">
            ${heroHTML}
            ${bodyHtml}
        </section>
    `;
    }


    // Fetch preview ONLY inside the editor
    async function fetchHoroscope() {
        const ezhp_birthDate = editorBirthDate;
        const ezhp_language = language;

        if (!ezhp_birthDate) return;

        setLoading(true);

        try {
            const response = await wp.apiFetch({
                path: `ezhp/v1/chinese-horoscope?birthDate=${encodeURIComponent(ezhp_birthDate)}&language=${encodeURIComponent(ezhp_language)}`
            });

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

            // Store RAW API HTML
            setRawHtml(html);

        } catch (e) {
            setRawHtml('<div>Error loading horoscope.</div>');
        }

        setLoading(false);
    }


    return (
        <>
            {/* Sidebar Controls */}
            <InspectorControls>
                <PanelBody title="Horoscope Settings" initialOpen={true}>

                    <label style={{ marginBottom: '6px', display: 'block', fontWeight: 600 }}>
                        Birthdate
                    </label>

                    {/* EDITOR DATE CONTROL */}
                    <input
                        type="date"
                        value={editorBirthDate}
                        onChange={(e) => setEditorBirthDate(e.target.value)}
                        style={{
                            width: '100%',
                            padding: '6px',
                            borderRadius: '4px',
                            border: '1px solid #ccc'
                        }}
                    />

                    <TextControl
                        label="Language"
                        value={language}
                        onChange={(value) => setAttributes({ language: value })}
                        style={{ marginTop: '12px' }}
                    />

                    <ToggleControl
                        label="Hide Heading"
                        checked={attributes.hideHeading}
                        onChange={(value) => setAttributes({ hideHeading: value })}
                    />

                </PanelBody>

                <PanelBody title="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="Display Mode"
                        value={attributes.heroImageDisplayMode}
                        options={[
                            { label: 'Background', value: 'background' },
                            { label: 'Inline', value: 'inline' },
                        ]}
                        onChange={(value) => setAttributes({ heroImageDisplayMode: value })}
                    />

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

                    <SelectControl
                        label="Alignment (background mode)"
                        value={attributes.heroImageAlignment}
                        options={[
                            { label: 'Center', value: 'center' },
                            { label: 'Left', value: 'left' },
                            { label: 'Right', value: 'right' },
                        ]}
                        onChange={(value) =>
                            setAttributes({ heroImageAlignment: value })
                        }
                    />

                    <RangeControl
                        label="Overlay Opacity (%)"
                        value={attributes.heroImageOverlayOpacity}
                        onChange={(value) =>
                            setAttributes({ heroImageOverlayOpacity: value })
                        }
                        min={0}
                        max={100}
                        step={5}
                    />

                    <SelectControl
                        label="Overlay Color"
                        value={attributes.heroImageOverlayColor}
                        options={[
                            { label: 'Black (dark)', value: 'black' },
                            { label: 'White (light)', value: 'white' },
                        ]}
                        onChange={(value) =>
                            setAttributes({ heroImageOverlayColor: value })
                        }
                    />

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

                </PanelBody>

            </InspectorControls>

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

                <div 
                    className="chinese-horoscope-editor-ui" 
                    style={{ marginBottom: '15px' }}
                    dir={ezhp_isRTL(language) ? 'rtl' : 'ltr'}
                >
                    <label style={{ fontWeight: '600' }}>{ezhp_t(language, 'enterBirthdate')}</label>

                    <input
                        type="date"
                        value={editorBirthDate}
                        onChange={(e) => setEditorBirthDate(e.target.value)}
                        style={{
                            width: '200px',
                            marginInlineEnd: '10px',
                            padding: '6px',
                            borderRadius: '4px',
                            border: '1px solid #ccc'
                        }}
                    />

                    <Button
                        variant="primary"
                        onClick={fetchHoroscope}
                        disabled={!editorBirthDate}
                    >
                        {ezhp_t(language, 'getHoroscope')}
                    </Button>
                </div>

                {/* Live Preview */}
                <div 
                    className="chinese-horoscope-result-editor" 
                    style={{ padding: '10px' }}
                    dir={ezhp_isRTL(language) ? 'rtl' : 'ltr'}
                >
                    {loading && <Spinner />}
                    {!loading && previewHtml && (
                        <div dangerouslySetInnerHTML={{ __html: previewHtml }}></div>
                    )}
                </div>

            </div>
        </>
    );
}