import { useEffect, useState } from 'react';

export default function Tweaks({ state, setState }) {
    const [open, setOpen] = useState(false);

    useEffect(() => {
        const onKey = (e) => {
            if (e.key === '`' || (e.altKey && e.key.toLowerCase() === 't')) {
                setOpen((v) => !v);
            }
        };
        window.addEventListener('keydown', onKey);
        return () => window.removeEventListener('keydown', onKey);
    }, []);

    const set = (k, v) => {
        setState((s) => {
            const next = { ...s, [k]: v };
            try {
                localStorage.setItem('moonwell.tweaks', JSON.stringify(next));
            } catch (e) {
                // ignore
            }
            return next;
        });
    };

    return (
        <>
            <button
                className="tweaks-fab"
                onClick={() => setOpen((v) => !v)}
                aria-label="Tweaks"
                title="Настройки внешнего вида (alt+T)"
            >
                ✦
            </button>
            <div className={`tweaks ${open ? 'open' : ''}`}>
                <div className="tweaks-title">
                    <span>Tweaks</span>
                    <button onClick={() => setOpen(false)} aria-label="Close">×</button>
                </div>

                <div className="tweak-row">
                    <label>Настроение</label>
                    <div className="tweak-seg">
                        <button
                            className={state.variant === 'forest' ? 'active' : ''}
                            onClick={() => set('variant', 'forest')}
                        >
                            Лес
                        </button>
                        <button
                            className={state.variant === 'temple' ? 'active' : ''}
                            onClick={() => set('variant', 'temple')}
                        >
                            Храм
                        </button>
                    </div>
                </div>

                <div className="tweak-row">
                    <label>Частицы и анимации</label>
                    <div
                        className={`tweak-switch ${state.particles ? 'on' : ''}`}
                        onClick={() => set('particles', !state.particles)}
                        role="switch"
                        aria-checked={state.particles}
                    />
                </div>

                <div className="tweak-row">
                    <label>Луна на фоне</label>
                    <div
                        className={`tweak-switch ${state.moon ? 'on' : ''}`}
                        onClick={() => set('moon', !state.moon)}
                        role="switch"
                        aria-checked={state.moon}
                    />
                </div>
            </div>
        </>
    );
}
