// Device detail sheet + Geofence config sheet

// ── HSV helpers ─────────────────────────────────────────────
function hsvToRgb(h, s, v) {
  s /= 1000; v /= 1000;
  const c = v * s, x = c * (1 - Math.abs(((h / 60) % 2) - 1)), m = v - c;
  let r, g, b;
  if (h < 60)       { r = c; g = x; b = 0; }
  else if (h < 120) { r = x; g = c; b = 0; }
  else if (h < 180) { r = 0; g = c; b = x; }
  else if (h < 240) { r = 0; g = x; b = c; }
  else if (h < 300) { r = x; g = 0; b = c; }
  else              { r = c; g = 0; b = x; }
  return [Math.round((r + m) * 255), Math.round((g + m) * 255), Math.round((b + m) * 255)];
}
function rgbToHex(r, g, b) { return '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join(''); }
function parseHsvString(s) {
  if (!s || typeof s !== 'string') return { h: 0, s: 1000, v: 1000 };
  if (s.length === 12) {
    return { h: parseInt(s.slice(0, 4), 16), s: parseInt(s.slice(4, 8), 16), v: parseInt(s.slice(8, 12), 16) };
  }
  return { h: 0, s: 1000, v: 1000 };
}
function hsvToString(h, s, v) {
  return [h, s, v].map(x => Math.round(x).toString(16).padStart(4, '0')).join('');
}

// ── Reusable control row ────────────────────────────────────
function ControlRow({ label, children }) {
  return (
    <div style={{ padding: '10px 0', borderBottom: '1px solid var(--hh-border, rgba(128,128,128,0.12))' }}>
      <div style={{ fontSize: 12, color: 'var(--hh-ink-mute)', marginBottom: 6, fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
      {children}
    </div>
  );
}

// ── LED Scene Presets ───────────────────────────────────────
const LED_PRESETS = [
  { name: 'Warm Glow', h: 30, s: 900, v: 1000 },
  { name: 'Ocean', h: 200, s: 800, v: 700 },
  { name: 'Sunset', h: 15, s: 1000, v: 1000 },
  { name: 'Forest', h: 130, s: 700, v: 600 },
  { name: 'Purple Night', h: 270, s: 800, v: 500 },
  { name: 'Ice Blue', h: 190, s: 600, v: 900 },
  { name: 'Fire', h: 5, s: 1000, v: 1000 },
  { name: 'Lavender', h: 280, s: 500, v: 800 },
  { name: 'Coral', h: 10, s: 700, v: 900 },
  { name: 'Electric', h: 260, s: 900, v: 1000 },
  { name: 'Deep Red', h: 0, s: 1000, v: 700 },
  { name: 'Mint', h: 160, s: 600, v: 800 },
];

// ── Timer / Schedule Panel ──────────────────────────────────
const DAYS = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
function TimerPanel({ device, store }) {
  const [expanded, setExpanded] = React.useState(false);
  const [timers, setTimers] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [showAdd, setShowAdd] = React.useState(false);
  const [time, setTime] = React.useState('07:00');
  const [loops, setLoops] = React.useState('0000000'); // Mon-Sun
  const [fnCode, setFnCode] = React.useState('switch_led');
  const [fnVal, setFnVal] = React.useState('true');

  const isTuyaCloud = device?._raw?.integration === 'tuya_cloud';
  if (!isTuyaCloud) return null;

  const loadTimers = () => {
    if (loading) return;
    setLoading(true);
    store.listTimers(device.id).then(res => {
      setTimers(res.timers || []);
    }).finally(() => setLoading(false));
  };

  const toggleDay = (i) => {
    const a = loops.split('');
    a[i] = a[i] === '1' ? '0' : '1';
    setLoops(a.join(''));
  };

  const handleCreate = () => {
    const payload = {
      loops,
      time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'Europe/Brussels',
      instruct: [{ functions: { code: fnCode, value: fnVal === 'true' }, date: '', time, loops }],
    };
    store.createTimer(device.id, payload).then(() => {
      setShowAdd(false);
      loadTimers();
    }).catch(() => {});
  };

  const handleDelete = (groupId) => {
    store.deleteTimer(device.id, groupId).then(() => {
      setTimers(ts => ts.filter(t => (t.id || t.group_id) !== groupId));
    }).catch(() => {});
  };

  return (
    <div style={{ borderTop: '1px solid var(--hh-border, rgba(128,128,128,0.12))', marginTop: 8 }}>
      <button onClick={() => { setExpanded(e => !e); if (!expanded) loadTimers(); }} className="press" style={{
        width: '100%', textAlign: 'left', padding: '12px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontSize: 13, fontWeight: 600, color: 'var(--hh-ink)',
      }}>
        <span>⏰ Schedules</span>
        <span style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{expanded ? '▾' : '▸'} {timers.length > 0 ? `${timers.length} active` : ''}</span>
      </button>

      {expanded && (
        <div style={{ paddingBottom: 8 }}>
          {loading && <div style={{ fontSize: 12, color: 'var(--hh-ink-mute)', padding: '8px 0' }}>Loading…</div>}

          {timers.map((t, i) => {
            const gid = t.id || t.group_id || i;
            return (
              <div key={gid} style={{ display: 'flex', gap: 8, alignItems: 'center', padding: '6px 0', borderBottom: '1px solid var(--hh-border, rgba(128,128,128,0.08))' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{t.time || '??:??'}</div>
                  <div style={{ fontSize: 10, color: 'var(--hh-ink-mute)' }}>
                    {t.loops && t.loops !== '0000000' ? t.loops.split('').map((c, i) => c === '1' ? DAYS[i] : '').filter(Boolean).join(' ') : 'Once'}
                    {t.instruct && t.instruct[0]?.functions ? ` · ${t.instruct[0].functions.code}: ${String(t.instruct[0].functions.value)}` : ''}
                  </div>
                </div>
                <button onClick={() => handleDelete(gid)} className="press" style={{ width: 24, height: 24, borderRadius: 6, background: '#fee2e2', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <span style={{ fontSize: 11, color: '#ef4444' }}>✕</span>
                </button>
              </div>
            );
          })}

          {!showAdd ? (
            <button onClick={() => setShowAdd(true)} className="press" style={{ width: '100%', padding: '8px 0', fontSize: 12, color: 'var(--hh-accent)', marginTop: 4 }}>+ Add schedule</button>
          ) : (
            <div style={{ marginTop: 8, padding: 10, background: 'var(--hh-surface-2, rgba(128,128,128,0.06))', borderRadius: 12 }}>
              <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
                <input type="time" value={time} onChange={e => setTime(e.target.value)}
                  style={{ flex: 1, height: 34, borderRadius: 8, border: '1px solid var(--hh-line-soft)', padding: '0 8px', background: 'var(--hh-surface)', color: 'var(--hh-ink)', fontSize: 13, outline: 'none' }}/>
              </div>
              <div style={{ display: 'flex', gap: 4, marginBottom: 8 }}>
                {DAYS.map((d, i) => (
                  <button key={d} onClick={() => toggleDay(i)} className="press" style={{
                    flex: 1, height: 28, borderRadius: 6, fontSize: 10, fontWeight: 600,
                    background: loops[i] === '1' ? 'var(--hh-accent)' : 'var(--hh-surface)',
                    color: loops[i] === '1' ? '#fff' : 'var(--hh-ink-mute)',
                    border: `1px solid ${loops[i] === '1' ? 'var(--hh-accent)' : 'var(--hh-line-soft)'}`,
                  }}>{d}</button>
                ))}
              </div>
              <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
                <input value={fnCode} onChange={e => setFnCode(e.target.value)} placeholder="Function code"
                  style={{ flex: 1, height: 30, borderRadius: 8, border: '1px solid var(--hh-line-soft)', padding: '0 8px', background: 'var(--hh-surface)', color: 'var(--hh-ink)', fontSize: 12, outline: 'none' }}/>
                <select value={fnVal} onChange={e => setFnVal(e.target.value)}
                  style={{ width: 80, height: 30, borderRadius: 8, border: '1px solid var(--hh-line-soft)', padding: '0 4px', background: 'var(--hh-surface)', color: 'var(--hh-ink)', fontSize: 12, outline: 'none' }}>
                  <option value="true">On</option>
                  <option value="false">Off</option>
                </select>
              </div>
              <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                <button onClick={() => setShowAdd(false)} className="press" style={{ height: 30, padding: '0 12px', borderRadius: 8, fontSize: 11, color: 'var(--hh-ink-mute)' }}>Cancel</button>
                <button onClick={handleCreate} className="press hh-btn accent" style={{ height: 30, padding: '0 14px', fontSize: 11 }}>Create</button>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function DeviceDetailSheet({ device, open, onClose, store, cfg }) {
  if (!device) return null;
  const [state, setState] = React.useState(null);
  const [spec, setSpec] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [hsv, setHsv] = React.useState({ h: 30, s: 900, v: 1000 });
  const [acSetpoint, setAcSetpoint] = React.useState(22);
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    if (!open || !device) return;
    setLoading(true);
    setErr(null);
    setState(null);
    setSpec(null);
    const proms = [
      store.getDeviceState(device.id).then(r => {
        if (r && r.state) {
          setState(r.state);
          const colorVal = r.state['24'] || r.state['colour_data'];
          if (colorVal) setHsv(parseHsvString(colorVal));
          if (r.state.setpoint != null) setAcSetpoint(r.state.setpoint);
        }
      }),
    ];
    if (device.brand === 'tuya_cloud' || (device._raw && device._raw.integration === 'tuya_cloud')) {
      proms.push(store.getDeviceSpec(device.id).then(r => { if (r) setSpec(r); }));
    }
    Promise.all(proms)
      .catch(e => setErr(e.message || 'Failed to load device state'))
      .finally(() => setLoading(false));
  }, [open, device && device.id]);

  const sendControl = (action, value) => {
    store.controlDevice(device.id, action, value)
      .then(r => { if (r && r.state) setState(r.state); })
      .catch(e => setErr(e.message || 'Control failed'));
  };

  const handlePowerToggle = () => {
    setErr(null);
    store.toggleDevice(device.id)
      .then(r => { if (r && r.state) setState(r.state); })
      .catch(e => setErr(e.message || 'Power toggle failed'));
  };

  const refreshState = () => {
    setLoading(true);
    setErr(null);
    store.getDeviceState(device.id)
      .then(r => { if (r && r.state) setState(r.state); })
      .finally(() => setLoading(false));
  };

  const isLight = device.type === 'bulb' || (device._raw && (device._raw.type === 'light' || device._raw.type === 'strip'));
  const isAc = device.type === 'ac';
  const isWasher = device.type === 'washer';
  const isTuyaCloud = device.brand === 'tuya_cloud' || (device._raw && device._raw.integration === 'tuya_cloud');

  const brightness = state ? Math.round(((state['22'] || state['bright_value'] || 0) / 10)) : device.value;
  const colorTemp = state ? Math.round(((state['23'] || state['temp_value'] || 500) / 10)) : 50;
  const workMode = (state && (state['21'] || state['work_mode'])) || 'white';
  const currentRgb = hsvToRgb(hsv.h, hsv.s, hsv.v);
  const currentHex = rgbToHex(currentRgb[0], currentRgb[1], currentRgb[2]);

  return (
    <Sheet open={open} onClose={onClose} title={device.name} presentation="modal" width="min(860px, calc(100vw - 20px))">
      <div style={{ padding: '0 20px 20px', overflowY: 'auto' }}>
        <div className="hh-card" style={{ padding: 18, marginBottom: 16, background: 'linear-gradient(135deg, var(--hh-accent-tint), var(--hh-surface))' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 14 }}>
            <div>
              <div style={{ fontSize: 12, color: 'var(--hh-ink-mute)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6 }}>
                {device.room} · {device.brand || (device._raw && device._raw.integration) || 'local'}
              </div>
              <div className="hh-serif" style={{ fontSize: 30, lineHeight: 1.05 }}>{device.name}</div>
              <div style={{ fontSize: 12, color: 'var(--hh-ink-soft)', marginTop: 8 }}>
                {state ? 'Live status connected' : 'Tap refresh to load the latest device state'}
              </div>
            </div>
            <button className="press" onClick={refreshState}
              style={{ height: 36, padding: '0 14px', borderRadius: 999, background: 'var(--hh-surface)', color: 'var(--hh-ink-soft)', fontSize: 12, fontWeight: 600, border: '1px solid var(--hh-line-soft)' }}>
              {loading ? 'Refreshing…' : 'Refresh'}
            </button>
          </div>
        </div>

        {err && <div style={{ padding: '8px 12px', background: '#FF634720', color: '#FF6347', borderRadius: 8, fontSize: 12, marginBottom: 12 }}>{err}</div>}

        <div className="hh-card" style={{ padding: 14, marginBottom: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>Power</div>
            <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{device.on ? 'Currently on' : 'Currently off'}</div>
          </div>
          <Toggle on={device.on} onChange={handlePowerToggle} />
        </div>

        {isLight && (<>
          <ControlRow label={'Brightness — ' + brightness + '%'}>
            <input type="range" min="0" max="100" value={brightness}
              onMouseUp={(e) => sendControl('brightness', +e.target.value)}
              onTouchEnd={(e) => sendControl('brightness', +e.target.value)}
              onChange={() => {}}
              style={{ width: '100%', accentColor: 'var(--hh-accent)' }} />
          </ControlRow>

          <ControlRow label={'Color Temperature — ' + colorTemp + '%'}>
            <div style={{ height: 8, borderRadius: 999, background: 'linear-gradient(90deg, #B8DCEA, #FFF3D6, #F3C784, #E8A96B)', marginBottom: 8 }} />
            <input type="range" min="0" max="100" value={colorTemp}
              onMouseUp={(e) => sendControl('temperature', +e.target.value)}
              onTouchEnd={(e) => sendControl('temperature', +e.target.value)}
              onChange={() => {}}
              style={{ width: '100%', accentColor: 'var(--hh-accent)' }} />
          </ControlRow>

          <ControlRow label="Mode">
            <div style={{ display: 'flex', gap: 6 }}>
              {['white', 'colour', 'scene'].map(m => (
                <button key={m} className="press" onClick={() => sendControl('mode', m)}
                  style={{ flex: 1, padding: '10px 0', borderRadius: 10, fontSize: 13, fontWeight: 500, cursor: 'pointer', border: 'none',
                    background: workMode === m ? 'var(--hh-accent)' : 'var(--hh-surface-2)',
                    color: workMode === m ? '#fff' : 'var(--hh-ink)' }}>
                  {m.charAt(0).toUpperCase() + m.slice(1)}
                </button>
              ))}
            </div>
          </ControlRow>

          {(workMode === 'colour' || workMode === 'color') && (
            <ControlRow label="Color">
              <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 10 }}>
                <div style={{ width: 56, height: 56, borderRadius: 12, background: currentHex,
                  boxShadow: '0 0 20px ' + currentHex + '66', border: '2px solid var(--hh-border, rgba(128,128,128,0.2))' }} />
                <div style={{ fontSize: 18, fontWeight: 600, fontFamily: 'var(--hh-font)' }}>{currentHex}</div>
              </div>
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)', marginBottom: 2 }}>Hue: {hsv.h}°</div>
              <input type="range" min="0" max="360" value={hsv.h}
                onChange={(e) => setHsv(p => ({ ...p, h: +e.target.value }))}
                onMouseUp={() => sendControl('color', hsvToString(hsv.h, hsv.s, hsv.v))}
                onTouchEnd={() => sendControl('color', hsvToString(hsv.h, hsv.s, hsv.v))}
                style={{ width: '100%', background: 'linear-gradient(90deg, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)', borderRadius: 999, height: 8, marginBottom: 8 }} />
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)', marginBottom: 2 }}>Saturation: {Math.round(hsv.s / 10)}%</div>
              <input type="range" min="0" max="1000" value={hsv.s}
                onChange={(e) => setHsv(p => ({ ...p, s: +e.target.value }))}
                onMouseUp={() => sendControl('color', hsvToString(hsv.h, hsv.s, hsv.v))}
                onTouchEnd={() => sendControl('color', hsvToString(hsv.h, hsv.s, hsv.v))}
                style={{ width: '100%', accentColor: 'var(--hh-accent)', marginBottom: 8 }} />
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)', marginBottom: 2 }}>Value: {Math.round(hsv.v / 10)}%</div>
              <input type="range" min="0" max="1000" value={hsv.v}
                onChange={(e) => setHsv(p => ({ ...p, v: +e.target.value }))}
                onMouseUp={() => sendControl('color', hsvToString(hsv.h, hsv.s, hsv.v))}
                onTouchEnd={() => sendControl('color', hsvToString(hsv.h, hsv.s, hsv.v))}
                style={{ width: '100%', accentColor: 'var(--hh-accent)' }} />
            </ControlRow>
          )}

          {workMode === 'scene' && (
            <ControlRow label="Scene Presets">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
                {LED_PRESETS.map(function(p) {
                  var c = rgbToHex.apply(null, hsvToRgb(p.h, p.s, p.v));
                  return (
                    <button key={p.name} className="press" onClick={() => {
                      sendControl('color', hsvToString(p.h, p.s, p.v));
                      setHsv({ h: p.h, s: p.s, v: p.v });
                    }} style={{ padding: '10px 4px', borderRadius: 10, border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 500,
                      background: 'linear-gradient(135deg, ' + c + '44, ' + c + '22)', color: 'var(--hh-ink)' }}>
                      <div style={{ width: 16, height: 16, borderRadius: '50%', background: c, margin: '0 auto 4px', boxShadow: '0 0 8px ' + c + '88' }} />
                      {p.name}
                    </button>
                  );
                })}
              </div>
            </ControlRow>
          )}
        </>)}

        {isAc && (<>
          <div style={{ padding: '20px 0', textAlign: 'center' }}>
            <div className="hh-numeric" style={{ fontSize: 64, color: 'var(--hh-ink)' }}>
              {(state && state.setpoint) || acSetpoint}<span style={{ fontSize: 24, color: 'var(--hh-ink-mute)' }}>°C</span>
            </div>
            {state && state.current_temperature != null && (
              <div style={{ fontSize: 13, color: 'var(--hh-ink-mute)' }}>
                Room: {state.current_temperature}°C{state.humidity != null ? (' · ' + state.humidity + '% humidity') : ''}
              </div>
            )}
          </div>

          <ControlRow label={'Set Temperature — ' + acSetpoint + '°C'}>
            <input type="range" min={(state && state.min_setpoint) || 16} max={(state && state.max_setpoint) || 30}
              value={acSetpoint}
              onChange={(e) => setAcSetpoint(+e.target.value)}
              onMouseUp={(e) => sendControl('setpoint', +e.target.value)}
              onTouchEnd={(e) => sendControl('setpoint', +e.target.value)}
              style={{ width: '100%', accentColor: 'var(--hh-accent)' }} />
          </ControlRow>

          <ControlRow label="Mode">
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {((state && state.supported_modes) || ['cool', 'heat', 'auto', 'dry', 'fan']).map(m => (
                <button key={m} className="press" onClick={() => sendControl('mode', m)}
                  style={{ flex: '1 0 auto', minWidth: 50, padding: '10px 8px', borderRadius: 10, fontSize: 12, fontWeight: 500, cursor: 'pointer', border: 'none', textTransform: 'capitalize',
                    background: state && state.mode === m ? 'var(--hh-accent)' : 'var(--hh-surface-2)',
                    color: state && state.mode === m ? '#fff' : 'var(--hh-ink)' }}>
                  {m}
                </button>
              ))}
            </div>
          </ControlRow>

          <ControlRow label="Fan Speed">
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {((state && state.supported_fan_modes) || ['auto', 'low', 'medium', 'high', 'turbo']).map(m => (
                <button key={m} className="press" onClick={() => sendControl('fan_mode', m)}
                  style={{ flex: '1 0 auto', minWidth: 50, padding: '10px 8px', borderRadius: 10, fontSize: 12, fontWeight: 500, cursor: 'pointer', border: 'none', textTransform: 'capitalize',
                    background: state && state.fan_mode === m ? 'var(--hh-accent)' : 'var(--hh-surface-2)',
                    color: state && state.fan_mode === m ? '#fff' : 'var(--hh-ink)' }}>
                  {m}
                </button>
              ))}
            </div>
          </ControlRow>

          <ControlRow label="Swing">
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {((state && state.supported_swing_modes) || ['fixed', 'vertical', 'horizontal', 'both']).map(m => (
                <button key={m} className="press" onClick={() => sendControl('swing', m)}
                  style={{ flex: '1 0 auto', minWidth: 60, padding: '10px 8px', borderRadius: 10, fontSize: 12, fontWeight: 500, cursor: 'pointer', border: 'none', textTransform: 'capitalize',
                    background: state && state.swing_mode === m ? 'var(--hh-accent)' : 'var(--hh-surface-2)',
                    color: state && state.swing_mode === m ? '#fff' : 'var(--hh-ink)' }}>
                  {m}
                </button>
              ))}
            </div>
          </ControlRow>

          <ControlRow label="Quick Presets">
            <div style={{ display: 'flex', gap: 8 }}>
              {[
                { label: 'Eco 25', mode: 'auto', temp: 25, icon: '🌿' },
                { label: 'Comfort 22', mode: 'cool', temp: 22, icon: '❄️' },
                { label: 'Heat 24', mode: 'heat', temp: 24, icon: '🔥' },
              ].map(p => (
                <button key={p.label} className="press" onClick={() => {
                  sendControl('setpoint', p.temp);
                  setTimeout(() => sendControl('mode', p.mode), 300);
                  setAcSetpoint(p.temp);
                }} style={{ flex: 1, padding: '12px 8px', borderRadius: 12, border: 'none', cursor: 'pointer',
                  background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', fontSize: 12, fontWeight: 500 }}>
                  {p.icon} {p.label}
                </button>
              ))}
            </div>
          </ControlRow>

          {state && state.power_consumption != null && (
            <ControlRow label="Info">
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <div className="hh-card" style={{ padding: 10, textAlign: 'center' }}>
                  <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>Power</div>
                  <div style={{ fontSize: 18, fontWeight: 600 }}>{state.power_consumption} kWh</div>
                </div>
                {state.dust_filter != null && (
                  <div className="hh-card" style={{ padding: 10, textAlign: 'center' }}>
                    <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>Dust Filter</div>
                    <div style={{ height: 6, background: 'var(--hh-surface-2)', borderRadius: 999, margin: '6px 0', overflow: 'hidden' }}>
                      <div style={{ width: state.dust_filter + '%', height: '100%', borderRadius: 999,
                        background: state.dust_filter < 50 ? '#4CAF50' : state.dust_filter < 80 ? '#FF9800' : '#F44336' }} />
                    </div>
                    <div style={{ fontSize: 12 }}>{state.dust_filter}%</div>
                  </div>
                )}
              </div>
            </ControlRow>
          )}

          {state && state.volume != null && (
            <ControlRow label={'Volume — ' + state.volume + '%'}>
              <input type="range" min="0" max="100" value={state.volume}
                onMouseUp={(e) => sendControl('volume', +e.target.value)}
                onTouchEnd={(e) => sendControl('volume', +e.target.value)}
                onChange={() => {}}
                style={{ width: '100%', accentColor: 'var(--hh-accent)' }} />
            </ControlRow>
          )}
        </>)}

        {isWasher && (<>
          <div style={{ padding: '20px 0', textAlign: 'center' }}>
            <div style={{ fontSize: 48, marginBottom: 8 }}>🫧</div>
            <div className="hh-numeric" style={{ fontSize: 48 }}>
              {state && state.completion_percentage != null ? (state.completion_percentage + '%') : '—'}
            </div>
            <div style={{ fontSize: 13, color: 'var(--hh-ink-mute)' }}>
              {state && state.machine_state ? ('Status: ' + state.machine_state) : 'Unknown status'}
              {state && state.remaining_time ? (' · ' + state.remaining_time + ' min remaining') : ''}
            </div>
            {state && state.completion_percentage != null && (
              <div style={{ height: 10, background: 'var(--hh-surface-2)', borderRadius: 999, margin: '16px 0', overflow: 'hidden' }}>
                <div style={{ width: state.completion_percentage + '%', height: '100%', background: 'var(--hh-accent)', borderRadius: 999, transition: 'width .3s' }} />
              </div>
            )}
          </div>
          <ControlRow label="Controls">
            <div style={{ display: 'flex', gap: 8 }}>
              {['start', 'pause', 'stop'].map(a => (
                <button key={a} className="press" onClick={() => sendControl(a)}
                  style={{ flex: 1, padding: '12px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
                    background: 'var(--hh-surface-2)', color: 'var(--hh-ink)', fontSize: 13, fontWeight: 500, textTransform: 'capitalize' }}>
                  {a === 'start' ? '▶ Start' : a === 'pause' ? '⏸ Pause' : '⏹ Stop'}
                </button>
              ))}
            </div>
          </ControlRow>
        </>)}

        {!isLight && !isAc && !isWasher && (
          <div style={{ padding: '30px 0', textAlign: 'center' }}>
            <div style={{ fontSize: 48, marginBottom: 8 }}>
              {device.type === 'plug' ? '🔌' : device.type === 'thermo' ? '🌡' : device.type === 'lock' ? '🔒' : '💡'}
            </div>
            {state && state['19'] != null && (
              <div className="hh-numeric" style={{ fontSize: 32, marginBottom: 8 }}>{(state['19'] / 10).toFixed(1)}W</div>
            )}
          </div>
        )}

        {isTuyaCloud && spec && spec.specification && spec.specification.functions && (<>
          <div className="hh-section-h" style={{ padding: '16px 0 8px' }}>Advanced Controls</div>
          {spec.specification.functions
            .filter(f => !/^colou?r_data$/.test(f.code) && f.code !== 'control_data')
            .map(function(f) {
              var vals = f.values ? (typeof f.values === 'string' ? JSON.parse(f.values) : f.values) : {};
              var currentVal = spec.status && spec.status[f.code];
              var humanName = f.code.replace(/_/g, ' ').replace(/\b\w/g, function(c) { return c.toUpperCase(); });

              if (vals.type === 'bool' || vals.type === 'boolean' || f.type === 'Boolean') {
                return (
                  <ControlRow key={f.code} label={humanName}>
                    <button className="press" onClick={() => sendControl('spec_command', { code: f.code, value: !currentVal })}
                      style={{ padding: '8px 16px', borderRadius: 8, border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 500,
                        background: currentVal ? 'var(--hh-accent)' : 'var(--hh-surface-2)',
                        color: currentVal ? '#fff' : 'var(--hh-ink)' }}>
                      {currentVal ? 'ON' : 'OFF'}
                    </button>
                  </ControlRow>
                );
              }

              if (vals.type === 'enum' && vals.range) {
                return (
                  <ControlRow key={f.code} label={humanName}>
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      {vals.range.map(opt => (
                        <button key={opt} className="press" onClick={() => sendControl('spec_command', { code: f.code, value: opt })}
                          style={{ padding: '8px 12px', borderRadius: 8, border: 'none', cursor: 'pointer', fontSize: 12, fontWeight: 500, textTransform: 'capitalize',
                            background: currentVal === opt ? 'var(--hh-accent)' : 'var(--hh-surface-2)',
                            color: currentVal === opt ? '#fff' : 'var(--hh-ink)' }}>
                          {opt.replace(/_/g, ' ')}
                        </button>
                      ))}
                    </div>
                  </ControlRow>
                );
              }

              if (vals.type === 'value' || vals.type === 'integer' || vals.type === 'int' || vals.type === 'number') {
                var min = vals.min || 0, max = vals.max || 1000, step = vals.step || 1;
                var scale = vals.scale || 0;
                var display = currentVal != null ? (currentVal / Math.pow(10, scale)).toFixed(scale) + (vals.unit || '') : '—';
                return (
                  <ControlRow key={f.code} label={humanName + ' — ' + display}>
                    <input type="range" min={min} max={max} step={step} value={currentVal || min}
                      onMouseUp={(e) => sendControl('spec_command', { code: f.code, value: +e.target.value })}
                      onTouchEnd={(e) => sendControl('spec_command', { code: f.code, value: +e.target.value })}
                      onChange={() => {}}
                      style={{ width: '100%', accentColor: 'var(--hh-accent)' }} />
                  </ControlRow>
                );
              }

              return null;
            })}
        </>)}

        {/* ── Countdown Timer Display ── */}
        {state && Object.entries(state).filter(([k]) => /^countdown/.test(k)).map(([code, val]) => {
          const secs = Number(val) || 0;
          const h = Math.floor(secs / 3600);
          const m = Math.floor((secs % 3600) / 60);
          const s = secs % 60;
          return (
            <ControlRow key={code} label={`⏱ Countdown (${code})`}>
              <div className="hh-numeric" style={{ fontSize: 28, textAlign: 'center', padding: '8px 0' }}>
                {String(h).padStart(2, '0')}:{String(m).padStart(2, '0')}:{String(s).padStart(2, '0')}
              </div>
            </ControlRow>
          );
        })}

        {/* ── Schedules / Timers Panel ── */}
        <TimerPanel device={device} store={store}/>

        <div className="hh-section-h" style={{ padding: '16px 0 6px' }}>Device Info</div>
        <div style={{ fontSize: 12, color: 'var(--hh-ink-mute)', lineHeight: 1.6 }}>
          <div>Type: {(device._raw && device._raw.type) || device.type}</div>
          <div>Integration: {(device._raw && device._raw.integration) || device.brand || 'unknown'}</div>
          {device._raw && device._raw.device_id && <div>ID: {device._raw.device_id}</div>}
          {device._raw && device._raw.ip && <div>IP: {device._raw.ip}</div>}
        </div>
      </div>
    </Sheet>
  );
}

window.DeviceDetailSheet = DeviceDetailSheet;
