import React, { useEffect, useState, useRef, Suspense, lazy } from 'react'; import { API_URL } from '../config.js'; import { authFetch } from '../utils/authFetch.js'; import Wheel from '@uiw/react-color-wheel'; export default function Lighting() { const [state, setState] = useState({ power: '', red: 0, blue: 0, green: 0, brightness: 100 }); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); const [success, setSuccess] = useState(false); useEffect(() => { authFetch(`${API_URL}/lighting/state`) .then(res => res.json()) .then(data => { setState(data); setLoading(false); }) .catch(() => { setError('Failed to fetch lighting state'); setLoading(false); }); }, []); useEffect(() => { setState({ power: '', red: 0, blue: 0, green: 0, brightness: 100 }); }, []); const handleColorChange = (color) => { console.log('Handle color change:', color); const { r, g, b } = color.rgb; updateLighting({ ...state, red: r, green: g, blue: b, }); }; const debounceRef = useRef(); const updateLighting = (newState) => { setState(newState); // Clear any pending timeout if (debounceRef.current) { clearTimeout(debounceRef.current); } // Set new timeout for API call debounceRef.current = setTimeout(() => { authFetch(`${API_URL}/lighting/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newState), }) .then(() => setSuccess(true)) .catch(() => setError('Failed to update lighting state')); }, 100); // 100ms debounce for 25 req/2s rate limit }; const handleSubmit = (e) => { e.preventDefault(); setLoading(true); authFetch(`${API_URL}/lighting/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(state), }) .then(() => setSuccess(true)) .catch(() => setError('Failed to update lighting state')) .finally(() => setLoading(false)); }; const handlePowerToggle = () => { const newPower = state.power === 'on' ? 'off' : 'on'; updateLighting({ ...state, power: newPower }); }; // Guard against undefined values const colorPreview = `rgb(${state.red ?? 0},${state.green ?? 0},${state.blue ?? 0})`; return (

Lighting Controls

Power