import { useMemo } from '@wordpress/element';
import useEditorStore from '../store/useEditorStore';

/**
 * Renders a live preview of the advanced template (e.g. Yeti character + form).
 * Text labels update in real-time from the zustand store.
 */
export default function AdvancedCanvas() {
    const editingTemplate = useEditorStore((s) => s.editingTemplate);
    const devicePreview = useEditorStore((s) => s.devicePreview);

    const blocks = editingTemplate?.jsonData?.blocks || [];
    const pageSettings = editingTemplate?.jsonData?.pageSettings || {};
    const loginForm = blocks.find((b) => b.type === 'loginForm');
    const s = loginForm?.settings || {};

    const deviceWidths = {
        desktop: '100%',
        tablet: '768px',
        mobile: '375px',
    };

    const bgStyle = useMemo(() => ({
        background: pageSettings.backgroundColor || '#eff3f4',
        minHeight: '100%',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '2rem 1rem',
        boxSizing: 'border-box',
    }), [pageSettings.backgroundColor]);

    const editorCss = useMemo(() => {
        if (!pageSettings.customCss) return '';
        // Replace body.login and other common prefixes with the canvas wrapper so editor styles apply correctly
        return pageSettings.customCss
            .replace(/body\.login/g, '.lpcd-canvas-wrapper .lpcd-advanced-canvas')
            .replace(/\.login/g, '.lpcd-canvas-wrapper .lpcd-advanced-canvas')
            .replace(/#loginform(?![a-zA-Z0-9_-])/g, '.lpcd-block-loginform')
            .replace(/#login(?![a-zA-Z0-9_-])/g, '.lpcd-advanced-canvas');
    }, [pageSettings.customCss]);

    return (
        <div className="lpcd-canvas-wrapper">
            <style>{editorCss}</style>
            <div
                className="lpcd-canvas lpcd-advanced-canvas"
                style={{ ...bgStyle, maxWidth: deviceWidths[devicePreview], position: 'relative' }}
            >
                {/* Yeti SVG Character */}
                <div className="lpcd-advanced-yeti-wrap" style={{ position: 'relative', zIndex: 10 }}>
                    <svg className="lpcd-yeti-svg-preview" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200">
                        <defs>
                            <circle id="armMaskPathP" cx="100" cy="100" r="100" />
                        </defs>
                        <clipPath id="armMaskP">
                            <use xlinkHref="#armMaskPathP" overflow="visible" />
                        </clipPath>
                        <circle cx="100" cy="100" r="100" fill="#a9ddf3" />
                        <g className="body">
                            <path stroke="#3A5E77" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" fill="#FFFFFF" d="M200,158.5c0-20.2-14.8-36.5-35-36.5h-14.9V72.8c0-27.4-21.7-50.4-49.1-50.8c-28-0.5-50.9,22.1-50.9,50v50 H35.8C16,122,0,138,0,157.8L0,213h200L200,158.5z" />
                            <path fill="#DDF1FA" d="M100,156.4c-22.9,0-43,11.1-54.1,27.7c15.6,10,34.2,15.9,54.1,15.9s38.5-5.8,54.1-15.9 C143,167.5,122.9,156.4,100,156.4z" />
                        </g>
                        <g className="earL">
                            <g fill="#ddf1fa" stroke="#3a5e77" strokeWidth="2.5">
                                <circle cx="47" cy="83" r="11.5" />
                                <path d="M46.3 78.9c-2.3 0-4.1 1.9-4.1 4.1 0 2.3 1.9 4.1 4.1 4.1" strokeLinecap="round" strokeLinejoin="round" />
                            </g>
                        </g>
                        <g className="earR">
                            <circle fill="#DDF1FA" stroke="#3A5E77" strokeWidth="2.5" cx="153" cy="83" r="11.5" />
                            <path fill="#DDF1FA" stroke="#3A5E77" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" d="M153.7,78.9 c2.3,0,4.1,1.9,4.1,4.1c0,2.3-1.9,4.1-4.1,4.1" />
                        </g>
                        <path className="face" fill="#DDF1FA" d="M134.5,46v35.5c0,21.815-15.446,39.5-34.5,39.5s-34.5-17.685-34.5-39.5V46" />
                        <path className="hair" fill="#FFFFFF" stroke="#3A5E77" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" d="M81.457,27.929 c1.755-4.084,5.51-8.262,11.253-11.77c0.979,2.565,1.883,5.14,2.712,7.723c3.162-4.265,8.626-8.27,16.272-11.235 c-0.737,3.293-1.588,6.573-2.554,9.837c4.857-2.116,11.049-3.64,18.428-4.156c-2.403,3.23-5.021,6.391-7.852,9.474" />
                        <g className="eyebrow">
                            <path fill="#FFFFFF" d="M138.142,55.064c-4.93,1.259-9.874,2.118-14.787,2.599c-0.336,3.341-0.776,6.689-1.322,10.037 c-4.569-1.465-8.909-3.222-12.996-5.226c-0.98,3.075-2.07,6.137-3.267,9.179c-5.514-3.067-10.559-6.545-15.097-10.329 c-1.806,2.889-3.745,5.73-5.816,8.515c-7.916-4.124-15.053-9.114-21.296-14.738l1.107-11.768h73.475V55.064z" />
                            <path fill="#FFFFFF" stroke="#3A5E77" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" d="M63.56,55.102 c6.243,5.624,13.38,10.614,21.296,14.738c2.071-2.785,4.01-5.626,5.816-8.515c4.537,3.785,9.583,7.263,15.097,10.329 c1.197-3.043,2.287-6.104,3.267-9.179c4.087,2.004,8.427,3.761,12.996,5.226c0.545-3.348,0.986-6.696,1.322-10.037 c4.913-0.481,9.857-1.34,14.787-2.599" />
                        </g>
                        <g className="eyeL">
                            <circle cx="85.5" cy="78.5" r="3.5" fill="#3a5e77" />
                            <circle cx="84" cy="76" r="1" fill="#fff" />
                        </g>
                        <g className="eyeR">
                            <circle cx="114.5" cy="78.5" r="3.5" fill="#3a5e77" />
                            <circle cx="113" cy="76" r="1" fill="#fff" />
                        </g>
                        <g className="mouth">
                            <path fill="#617E92" d="M100.2,101c-0.4,0-1.4,0-1.8,0c-2.7-0.3-5.3-1.1-8-2.5c-0.7-0.3-0.9-1.2-0.6-1.8 c0.2-0.5,0.7-0.7,1.2-0.7c0.2,0,0.5,0.1,0.6,0.2c3,1.5,5.8,2.3,8.6,2.3s5.7-0.7,8.6-2.3c0.2-0.1,0.4-0.2,0.6-0.2 c0.5,0,1,0.3,1.2,0.7c0.4,0.7,0.1,1.5-0.6,1.9c-2.6,1.4-5.3,2.2-7.9,2.5C101.7,101,100.5,101,100.2,101z" />
                        </g>
                        <path className="nose" d="M97.7 79.9h4.7c1.9 0 3 2.2 1.9 3.7l-2.3 3.3c-.9 1.3-2.9 1.3-3.8 0l-2.3-3.3c-1.3-1.6-.2-3.7 1.8-3.7z" fill="#3a5e77" />
                    </svg>
                </div>

                {/* Live Form Preview */}
                <div id="loginform" className="lpcd-advanced-form-preview" style={{
                    position: 'relative',
                    zIndex: 10,
                    background: s.formBackground || '#ffffff',
                    borderRadius: `${s.formBorderRadius || 8}px`,
                    padding: `${s.formPadding || 36}px`,
                    width: `${s.formWidth || 400}px`,
                    maxWidth: '90%',
                    border: s.formBorderEnabled ? `${s.formBorderWidth || 1}px solid ${s.formBorderColor || '#ddd'}` : 'none',
                    boxSizing: 'border-box',
                }}>
                    {s.usernameShowLabel !== false && (
                        <label style={{ display: 'block', marginBottom: '6px', fontSize: '14px', fontWeight: '700', color: '#1e293b' }}>
                            {s.usernameLabel || 'Username or Email Address'}
                        </label>
                    )}
                    <input
                        type="text"
                        readOnly
                        placeholder={s.usernamePlaceholder || ''}
                        style={{
                            width: '100%', padding: '10px 12px', fontSize: `${s.usernameFontSize || 16}px`,
                            border: `1px solid ${s.usernameBorderColor || '#217093'}`,
                            borderRadius: `${s.usernameBorderRadius || 4}px`,
                            background: s.usernameBackgroundColor || '#f3fafd',
                            color: s.usernameTextColor || '#353538',
                            height: `${s.usernameHeight || 50}px`,
                            boxSizing: 'border-box', marginBottom: '16px', outline: 'none',
                        }}
                    />

                    {s.passwordShowLabel !== false && (
                        <label style={{ display: 'block', marginBottom: '6px', fontSize: '14px', fontWeight: '700', color: '#1e293b' }}>
                            {s.passwordLabel || 'Password'}
                        </label>
                    )}
                    <input
                        type="password"
                        readOnly
                        placeholder={s.passwordPlaceholder || ''}
                        style={{
                            width: '100%', padding: '10px 12px', fontSize: `${s.passwordFontSize || 16}px`,
                            border: `1px solid ${s.passwordBorderColor || '#217093'}`,
                            borderRadius: `${s.passwordBorderRadius || 4}px`,
                            background: s.passwordBackgroundColor || '#f3fafd',
                            color: s.passwordTextColor || '#353538',
                            height: `${s.passwordHeight || 50}px`,
                            boxSizing: 'border-box', marginBottom: '16px', outline: 'none',
                        }}
                    />

                    {s.showRememberMe !== false && (
                        <p className="forgetmenot" style={{ margin: 0, padding: 0 }}>
                            <label style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '13px', color: '#50575e', marginBottom: '14px' }}>
                                <input type="checkbox" readOnly />
                                {s.rememberMeText || 'Remember Me'}
                            </label>
                        </p>
                    )}

                    <p className="submit" style={{ margin: 0, padding: 0 }}>
                        <input type="submit" readOnly value={s.submitText || 'Log In'} style={{
                            width: s.submitFullWidth !== false ? '100%' : 'auto',
                            height: `${s.submitHeight || 50}px`,
                            background: s.submitBackgroundColor || '#4eb8dd',
                            color: s.submitTextColor || '#ffffff',
                            border: 'none',
                            borderRadius: `${s.submitBorderRadius || 4}px`,
                            fontSize: `${s.submitFontSize || 16}px`,
                            fontWeight: s.submitFontWeight || '600',
                            cursor: 'pointer',
                            marginBottom: '12px',
                        }} />
                    </p>

                    {s.showLostPassword !== false && (
                        <p className="lpcd-lost-password" style={{ textAlign: 'center', margin: 0, padding: 0 }}>
                            <a style={{ color: s.lostPasswordColor || '#217093', fontSize: '13px', textDecoration: 'none' }}>
                                {s.lostPasswordText || 'Lost your password?'}
                            </a>
                        </p>
                    )}
                </div>
            </div>
        </div>
    );
}
