import { useBlockProps, useInnerBlocksProps, InspectorControls, PanelColorSettings, RichText } from '@wordpress/block-editor';
import { PanelBody, Notice, Tooltip, ToggleControl, SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useEffect } from '@wordpress/element';

// ProLock Component
const ProLock = ({ isPro, children }) => {
    if (isPro) return children;
    return (
        <div className="pro-lock-wrapper" style={{ position: 'relative', cursor: 'not-allowed' }}>
            <div style={{ opacity: 0.4, pointerEvents: 'none', filter: 'grayscale(100%)' }}>{children}</div>
            <a href="https://rswpthemes.com/author-portfolio-pro-wordpress-theme/" target="_blank" rel="noopener noreferrer" style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10, cursor: 'pointer' }} aria-label="Upgrade to Pro">
                <Tooltip text="🔒 Pro Feature - Click to Upgrade"><div style={{ width: '100%', height: '100%' }} /></Tooltip>
            </a>
        </div>
    );
};

// Default Template (3 Cards)
const TEMPLATE = [
    ['awt/child-author-activity-card', { title: 'Free Coloring Pages', description: 'Download and print characters.', hoverEffect: 'rotate-left', imageUrl: 'https://via.placeholder.com/300' }],
    ['awt/child-author-activity-card', { title: 'How-To-Draw', description: 'Learn to draw in 5 steps.', hoverEffect: 'scale', imageUrl: 'https://via.placeholder.com/300' }],
    ['awt/child-author-activity-card', { title: 'Reading Guides', description: 'Fun questions for parents.', hoverEffect: 'rotate-right', imageUrl: 'https://via.placeholder.com/300' }],
];

export default function Edit({ attributes, setAttributes, clientId }) {
    const { heading, sectionBgColor, sectionPadding, headingColor, hideCurve, curveColor, blockId, activityStyle } = attributes;
    const isPro = window.awtVars?.isPro || false;

    useEffect(() => {
        if (!blockId) setAttributes({ blockId: clientId });
    }, [blockId, clientId, setAttributes]);

    const isFun = activityStyle === 'fun';
    const isElegant = activityStyle === 'elegant';

    // Conditional Styles
    const defaultBgClass = isElegant ? 'bg-gray-50' : 'bg-blue-sky/10';
    const containerClass = sectionBgColor || sectionPadding !== null ? 'relative' : `py-24 ${defaultBgClass} relative`;

    const defaultHeadingClass = isElegant
        ? 'text-3xl md:text-5xl font-serif font-bold text-brand-dark text-center mb-12'
        : 'text-4xl md:text-5xl font-black text-center mb-12';

    const headingClass = headingColor ? `${defaultHeadingClass}` : `${defaultHeadingClass} ${isFun ? 'text-navy' : ''}`;

    // Spacing
    const contentSpacing = isElegant ? 'mt-0' : 'mt-12';

    const blockProps = useBlockProps({
        className: `block-${blockId} ${containerClass}`,
        style: {
            backgroundColor: sectionBgColor || undefined,
            paddingTop: sectionPadding !== null ? `${sectionPadding}px` : undefined,
            paddingBottom: sectionPadding !== null ? `${sectionPadding}px` : undefined,
        }
    });

    // 🔥 FIX: useInnerBlocksProps ব্যবহার করে Grid ক্লাস সরাসরি কন্টেইনারে বসানো হচ্ছে
    const innerBlocksProps = useInnerBlocksProps(
        { className: 'grid grid-cols-1 md:grid-cols-3 gap-8' }, // Grid classes here
        {
            allowedBlocks: ['awt/child-author-activity-card'],
            template: TEMPLATE,
            // orientation: 'horizontal' // Grid এর জন্য এটা জরুরি নয়, তবে রাখা যায়
        }
    );

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Design Settings', 'author-website-templates')} initialOpen={false}>
                    <SelectControl
                        label={__('Section Style', 'author-website-templates')}
                        value={activityStyle}
                        options={[
                            { label: __('Fun (Child)', 'author-website-templates'), value: 'fun' },
                            { label: __('Elegant (Author)', 'author-website-templates'), value: 'elegant' },
                        ]}
                        onChange={(value) => setAttributes({ activityStyle: value })}
                    />
                    <ProLock isPro={isPro}>
                        <PanelColorSettings
                            title={__('Colors', 'author-website-templates')}
                            colorSettings={[
                                { value: sectionBgColor, onChange: (c) => setAttributes({ sectionBgColor: c }), label: 'Background' },
                                { value: curveColor, onChange: (c) => setAttributes({ curveColor: c }), label: 'Curve Color' },
                                { value: headingColor, onChange: (c) => setAttributes({ headingColor: c }), label: 'Heading Color' },
                            ]}
                        />
                        <ToggleControl label="Hide Top Curve" checked={hideCurve} onChange={(v) => setAttributes({ hideCurve: v })} />
                    </ProLock>
                </PanelBody>
            </InspectorControls>

            <section {...blockProps}>
                {!hideCurve && isFun && (
                    <div className="absolute top-0 left-0 w-full pointer-events-none">
                        <svg viewBox="0 0 1440 100" fill="none" className="w-full h-auto"><path d="M0 0H1440V100C1192.5 50.503 919.5 25.503 720 25.503C520.5 25.503 247.5 50.503 0 100V0Z" fill={curveColor} /></svg>
                    </div>
                )}

                <div className={`awt-container mx-auto px-6 relative z-10 ${contentSpacing}`}>
                    <RichText tagName="h2" className={headingClass} value={heading} onChange={(v) => setAttributes({ heading: v })} style={{ color: headingColor }} />

                    {/* 🔥 FIX: Grid Container */}
                    <div {...innerBlocksProps} />
                </div>
            </section>
        </>
    );
}