// Smart AC IR Controller detail screen — Controls | Live | Schedule | Settings

const AC_BRANDS = [
  { id: 'daikin',    name: 'Daikin',    models: ['FTKF35TV', 'FTKG50TV', 'JTKJ35TV', 'FTRE50TV'] },
  { id: 'voltas',    name: 'Voltas',    models: ['185V DZW', '185V CZT', '243V DZW', '183V DZU'] },
  { id: 'bluestar',  name: 'Blue Star', models: ['IC318YATX', 'IC524YATX', 'FA318YAW'] },
  { id: 'hitachi',   name: 'Hitachi',   models: ['RSB318HBDO', 'RSB524HCEA', 'RSB724HCEA'] },
  { id: 'lg',        name: 'LG',        models: ['KS-Q18YNZA', 'MS-Q18YNZA', 'PS-Q19YNZE'] },
  { id: 'samsung',   name: 'Samsung',   models: ['AR18CY3YAWK', 'AR18NV3HLTR', 'AR24TY3YAWK'] },
  { id: 'carrier',   name: 'Carrier',   models: ['CAI18EK3C8F0', 'ESTER+ 1.5T', 'CAI24EK3C8F0'] },
  { id: 'panasonic', name: 'Panasonic', models: ['CS/CU-SU12ZKYW', 'CS/CU-TZ12ZKYW'] },
  { id: 'ogeneral',  name: 'O General', models: ['ASGG18CGTA', 'ASGG12CGTA', 'AOGA18FETA'] },
  { id: 'godrej',    name: 'Godrej',    models: ['GSC 12 MINV 5 RGOG', 'GIC 18 INV 5 RGOG'] },
];
window.AC_BRANDS = AC_BRANDS;

const AC_MODES = [
  { id: 'cool', label: 'Cool', icon: 'snowflake', color: 'var(--cyan)'  },
  { id: 'fan',  label: 'Fan',  icon: 'wind',      color: 'var(--teal)'  },
  { id: 'dry',  label: 'Dry',  icon: 'droplet',   color: 'var(--info)'  },
  { id: 'heat', label: 'Heat', icon: 'flame',     color: 'var(--amber)' },
];
window.AC_MODES = AC_MODES;

const AC_FANS = [
  { id: 'low',  label: 'Low'  },
  { id: 'med',  label: 'Med'  },
  { id: 'high', label: 'High' },
  { id: 'auto', label: 'Auto' },
];
window.AC_FANS = AC_FANS;

const _AC_STORE_KEY = 'velonics_ac_data';
function _acLoad(id) { try { return JSON.parse(localStorage.getItem(_AC_STORE_KEY) || '{}')[id] || {}; } catch { return {}; } }
function _acSave(id, data) { try { const all = JSON.parse(localStorage.getItem(_AC_STORE_KEY) || '{}'); all[id] = { ...all[id], ...data }; localStorage.setItem(_AC_STORE_KEY, JSON.stringify(all)); } catch {} }

/* ============================================================
   AcDetail — main component
   ============================================================ */
const AcDetail = ({ tank: ac, onBack, updateTank, issueCmd, pendingCmds }) => {
  const toast = useToast();
  const _isVirtual = !ac.deviceId || !!ac.virtual;
  const acRef = useRef(ac);
  useEffect(() => { acRef.current = ac; }, [ac]);

  const [tab,  setTab]  = useState('controls');
  const [tick, setTick] = useState(0);
  const [scheduleEditor, setScheduleEditor] = useState(null);

  useEffect(() => {
    const stored = _acLoad(ac.id);
    const patch = {};
    if (stored.brand      != null)  patch.brand      = stored.brand;
    if (stored.model      != null)  patch.model      = stored.model;
    if (stored.switchType != null)  patch.switchType = stored.switchType;
    if (stored.presets    != null)  patch.presets    = stored.presets;
    if (stored.sleepCurve != null)  patch.sleepCurve = stored.sleepCurve;
    if (stored.wakeTimer  != null)  patch.wakeTimer  = stored.wakeTimer;
    if (Object.keys(patch).length)  updateTank(ac.id, patch);
  }, []); // eslint-disable-line

  useEffect(() => {
    if (!ac.timer) return;
    const id = setInterval(() => setTick(x => x + 1), 1000);
    return () => clearInterval(id);
  }, [ac.timer]);

  useEffect(() => {
    if (!ac.timer) return;
    if (ac.timer.endsAt <= Date.now()) updateTank(ac.id, { timer: null });
  }, [tick]); // eslint-disable-line

  // Simulation loop for virtual devices
  useEffect(() => {
    if (!_isVirtual) return;
    const id = setInterval(() => {
      const cur = acRef.current;
      if (!cur.on) return;
      const basePower = cur.mode === 'heat' ? 1600 : cur.mode === 'fan' ? 200 : 1400;
      const jitter = (Math.random() - 0.5) * 100;
      const pwr = Math.round(basePower + jitter);
      const volt = 230 + Math.round((Math.random() - 0.5) * 4);
      const amp = +(pwr / volt).toFixed(2);
      updateTank(cur.id, { power: pwr, voltage: volt, current: amp });
    }, 2000);
    return () => clearInterval(id);
  }, [_isVirtual]); // eslint-disable-line

  // Sleep curve executor: raise temp by 1°C/hr while sleeping
  useEffect(() => {
    if (!ac.on || !ac.sleepCurve) return;
    const id = setInterval(() => {
      const cur = acRef.current;
      if (!cur.on || !cur.sleepCurve) return;
      const newTemp = Math.min(30, (cur.temp || 24) + 1);
      updateTank(cur.id, { temp: newTemp });
      _acSave(cur.id, { temp: newTemp });
      if (!_isVirtual && cur.deviceId && window.MQ)
        MQ.publishCmd(cur.deviceId, 'settemp', newTemp);
    }, 60000);
    return () => clearInterval(id);
  }, [ac.on, !!ac.sleepCurve]); // eslint-disable-line

  const handlePowerToggle = () => {
    const next = !ac.on;
    if (_isVirtual) {
      updateTank(ac.id, { on: next, power: next ? 1400 : 0, current: next ? 6.1 : 0 });
      _acSave(ac.id, { on: next });
      toast(`AC turned ${next ? 'on' : 'off'}`, { kind: next ? 'success' : 'info', icon: 'power' });
    } else if (ac.deviceId && window.MQ) {
      issueCmd(ac.id, 'power', () => MQ.publishCmd(ac.deviceId, 'power', next));
      toast(`Turning AC ${next ? 'ON' : 'OFF'}…`, { kind: 'info', icon: 'power' });
    }
  };

  const handleTempChange = (delta) => {
    const newTemp = Math.max(16, Math.min(30, (ac.temp || 24) + delta));
    updateTank(ac.id, { temp: newTemp });
    _acSave(ac.id, { temp: newTemp });
    if (!_isVirtual && ac.deviceId && window.MQ)
      MQ.publishCmd(ac.deviceId, 'settemp', newTemp);
  };

  const handleModeChange = (newMode) => {
    updateTank(ac.id, { mode: newMode });
    _acSave(ac.id, { mode: newMode });
    if (!_isVirtual && ac.deviceId && window.MQ)
      MQ.publishCmd(ac.deviceId, 'mode', newMode);
  };

  const handleFanChange = (newFan) => {
    updateTank(ac.id, { fanSpeed: newFan });
    _acSave(ac.id, { fanSpeed: newFan });
    if (!_isVirtual && ac.deviceId && window.MQ)
      MQ.publishCmd(ac.deviceId, 'fan', newFan);
  };

  const applyPreset = (preset) => {
    updateTank(ac.id, { temp: preset.temp, mode: preset.mode, fanSpeed: preset.fanSpeed });
    _acSave(ac.id, { temp: preset.temp, mode: preset.mode, fanSpeed: preset.fanSpeed });
    if (!_isVirtual && ac.deviceId && window.MQ) {
      MQ.publishCmd(ac.deviceId, 'settemp', preset.temp);
      MQ.publishCmd(ac.deviceId, 'mode', preset.mode);
      MQ.publishCmd(ac.deviceId, 'fan', preset.fanSpeed);
    }
    toast(`Preset "${preset.name}" applied`, { kind: 'success' });
  };

  const setAcTimer = (minutes, action) => {
    if (minutes <= 0) {
      updateTank(ac.id, { timer: null });
      _acSave(ac.id, { timer: null });
      toast('Timer cancelled', { kind: 'info' });
    } else {
      const endsAt = Date.now() + minutes * 60_000;
      const t = { endsAt, action, label: `${minutes} min` };
      updateTank(ac.id, { timer: t });
      _acSave(ac.id, { timer: t });
      toast(`AC will turn ${action} in ${minutes} min`, { kind: 'success', icon: 'clock' });
    }
  };

  const saveAcSchedule = (sched) => {
    const schedules = acRef.current.schedules || [];
    const exists = sched.id && schedules.some(s => s.id === sched.id);
    const newSched = exists
      ? schedules.map(s => s.id === sched.id ? { ...s, ...sched } : s)
      : [...schedules, { ...sched, id: 'acs_' + Date.now() }];
    updateTank(ac.id, { schedules: newSched });
    _acSave(ac.id, { schedules: newSched });
    setScheduleEditor(null);
    toast(exists ? 'Schedule updated' : 'Schedule added', { kind: 'success', icon: 'calendar' });
  };

  const deleteAcSchedule = (id) => {
    const newSched = (acRef.current.schedules || []).filter(s => s.id !== id);
    updateTank(ac.id, { schedules: newSched });
    _acSave(ac.id, { schedules: newSched });
    setScheduleEditor(null);
    toast('Schedule removed', { kind: 'info' });
  };

  const toggleAcSchedule = (id, enabled) => {
    const newSched = (acRef.current.schedules || []).map(s => s.id === id ? { ...s, enabled } : s);
    updateTank(ac.id, { schedules: newSched });
    _acSave(ac.id, { schedules: newSched });
  };

  const _acTabs = [
    { key: 'controls', label: 'Controls' },
    { key: 'live',     label: 'Live'     },
    { key: 'schedule', label: 'Schedule' },
    { key: 'settings', label: 'Settings' },
  ];

  const swipe = typeof useSwipeTabs === 'function' ? useSwipeTabs(_acTabs, tab, setTab, onBack) : { onTouchStart: undefined, onTouchEnd: undefined };

  const isOn = _isVirtual ? ac.on : (ac.on && ac.online);
  const statusColor = !ac.deviceId ? 'gray' : ac.virtual ? 'amber' : !ac.online ? 'red' : 'green';
  const statusLabel = !ac.deviceId ? 'Demo' : ac.virtual ? 'Virtual' : !ac.online ? 'Offline' : 'Online';

  return (
    <div onTouchStart={swipe.onTouchStart} onTouchEnd={swipe.onTouchEnd} style={{ paddingBottom: 32, minHeight: '100dvh' }}>
      {/* Header */}
      <div style={{ position: 'sticky', top: 0, zIndex: 5, display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', background: 'rgba(10,14,39,0.85)', backdropFilter: 'blur(12px)', borderBottom: '1px solid var(--border)' }}>
        <button onClick={onBack} style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', borderRadius: 10, width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
          <Ic name="chevronLeft" size={18}/>
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 16, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{ac.name}</div>
          <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 1 }}>{ac.location} · Smart AC</div>
        </div>
        {_isVirtual && <Badge color="amber">Virtual</Badge>}
        <Badge color={isOn ? 'green' : 'gray'}>
          <StatusDot kind={isOn ? 'green' : 'gray'} size={6} pulse={isOn}/>
          {' '}{isOn ? 'On' : 'Off'}
        </Badge>
      </div>

      {/* Tab bar */}
      <div style={{ display: 'flex', borderBottom: '1px solid var(--border)', background: 'var(--bg)', position: 'sticky', top: 65, zIndex: 9 }}>
        {_acTabs.map(t => (
          <button key={t.key} onClick={() => setTab(t.key)} style={{
            flex: 1, padding: '12px 0', border: 'none', background: 'none', cursor: 'pointer',
            fontSize: 13, fontWeight: tab === t.key ? 700 : 500,
            color: tab === t.key ? 'var(--cyan)' : 'var(--text-3)',
            borderBottom: `2px solid ${tab === t.key ? 'var(--cyan)' : 'transparent'}`,
            transition: 'all 150ms',
          }}>{t.label}</button>
        ))}
      </div>

      <div style={{ padding: '20px 16px 16px' }}>
        {tab === 'controls' && (
          <_AcControlsTab
            ac={ac}
            isOn={isOn}
            _isVirtual={_isVirtual}
            onPowerToggle={handlePowerToggle}
            onTempChange={handleTempChange}
            onModeChange={handleModeChange}
            onFanChange={handleFanChange}
            onPreset={applyPreset}
            onTimer={setAcTimer}
            onSleepCurve={(v) => {
              const next = v ? { startTemp: ac.temp || 24, startTime: Date.now() } : null;
              updateTank(ac.id, { sleepCurve: next });
              _acSave(ac.id, { sleepCurve: next });
            }}
            onWakeTimer={(wt) => {
              updateTank(ac.id, { wakeTimer: wt });
              _acSave(ac.id, { wakeTimer: wt });
            }}
            tick={tick}
          />
        )}

        {tab === 'live' && (
          <_AcLiveTab ac={ac} isOn={isOn}/>
        )}

        {tab === 'schedule' && (
          <_AcScheduleTab
            ac={ac}
            scheduleEditor={scheduleEditor}
            setScheduleEditor={setScheduleEditor}
            onSave={saveAcSchedule}
            onDelete={deleteAcSchedule}
            onToggle={toggleAcSchedule}
          />
        )}

        {tab === 'settings' && (
          <_AcSettingsTab
            ac={ac}
            _isVirtual={_isVirtual}
            onSave={(patch) => {
              updateTank(ac.id, patch);
              _acSave(ac.id, patch);
              if (!_isVirtual && ac.deviceId && window.MQ) {
                if ('iMax' in patch || 'vLow' in patch || 'vHigh' in patch || 'powerMax' in patch) {
                  MQ.publishSetpoints(ac.deviceId, {
                    vLow: patch.vLow ?? ac.vLow ?? 180,
                    vHigh: patch.vHigh ?? ac.vHigh ?? 260,
                    iMax: patch.iMax ?? ac.iMax ?? 10,
                    powerMax: patch.powerMax ?? ac.powerMax ?? 2500,
                  });
                }
              }
              toast('Settings saved', { kind: 'success' });
            }}
          />
        )}
      </div>

      {scheduleEditor && (
        <_AcScheduleEditorSheet
          initial={scheduleEditor === 'new' ? null : scheduleEditor}
          onSave={saveAcSchedule}
          onDelete={scheduleEditor === 'new' ? null : () => deleteAcSchedule(scheduleEditor.id)}
          onClose={() => setScheduleEditor(null)}
        />
      )}
    </div>
  );
};

/* ============================================================
   Controls Tab
   ============================================================ */
const _AcControlsTab = ({ ac, isOn, _isVirtual, onPowerToggle, onTempChange, onModeChange, onFanChange, onPreset, onTimer, onSleepCurve, onWakeTimer, tick }) => {
  const [timerSheet, setTimerSheet] = useState(false);
  const modes = AC_MODES;
  const fans  = AC_FANS;
  const modeEntry = modes.find(m => m.id === ac.mode) || modes[0];
  const canInteract = isOn || _isVirtual;

  const t = ac.timer;
  const msLeft = t ? Math.max(0, t.endsAt - Date.now()) : 0;
  const mm = Math.floor(msLeft / 60000);
  const ss = Math.floor((msLeft % 60000) / 1000);

  return (
    <>
      {/* Hero temperature display */}
      <div style={{
        background: isOn
          ? 'radial-gradient(120% 100% at 50% 0%, rgba(0,212,255,0.14), transparent 60%), rgba(255,255,255,0.03)'
          : 'rgba(255,255,255,0.03)',
        border: `1px solid ${isOn ? 'rgba(0,212,255,0.28)' : 'var(--border)'}`,
        borderRadius: 20, overflow: 'hidden', marginBottom: 20,
        transition: 'background 400ms ease, border-color 400ms ease',
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '28px 16px 16px' }}>
          <div style={{ fontSize: 11, color: 'var(--text-3)', letterSpacing: 0.8, marginBottom: 10 }}>SET TEMPERATURE</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
            <button
              onClick={() => onTempChange(-1)}
              disabled={!canInteract}
              style={{ width: 44, height: 44, borderRadius: '50%', background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', color: 'var(--text)', fontSize: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: canInteract ? 'pointer' : 'default', opacity: canInteract ? 1 : 0.35 }}>
              −
            </button>
            <div style={{ textAlign: 'center' }}>
              <span className="num" style={{ fontSize: 60, fontWeight: 700, color: isOn ? 'var(--cyan)' : 'var(--text-3)', lineHeight: 1, letterSpacing: -2 }}>{ac.temp || 24}</span>
              <span style={{ fontSize: 22, color: 'var(--text-2)', fontWeight: 500 }}>°C</span>
            </div>
            <button
              onClick={() => onTempChange(1)}
              disabled={!canInteract}
              style={{ width: 44, height: 44, borderRadius: '50%', background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', color: 'var(--text)', fontSize: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: canInteract ? 'pointer' : 'default', opacity: canInteract ? 1 : 0.35 }}>
              +
            </button>
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 6 }}>Range: 16°C – 30°C</div>
        </div>

        {/* Power toggle */}
        {window._HeroSwitch
          ? <_HeroSwitch isOn={isOn} offline={!_isVirtual && !!ac.deviceId && !ac.online} kind={ac.switchType || 'round'} onClick={onPowerToggle}/>
          : <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0 16px' }}>
              <button onClick={onPowerToggle} style={{ width: 80, height: 80, borderRadius: '50%', background: isOn ? 'radial-gradient(circle at 30% 25%, #6dffb0, #00b860 70%)' : 'rgba(255,255,255,0.06)', border: `2px solid ${isOn ? 'rgba(0,230,118,0.55)' : 'var(--border)'}`, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Ic name="power" size={34} color={isOn ? '#062b18' : 'var(--text-2)'} strokeWidth={2.2}/>
              </button>
            </div>
        }
      </div>

      {/* Mode selector */}
      <SectionTitle>Mode</SectionTitle>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8, marginBottom: 20 }}>
        {modes.map(m => {
          const active = ac.mode === m.id;
          return (
            <button key={m.id} onClick={() => onModeChange(m.id)} style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              padding: '12px 6px',
              background: active ? `rgba(0,212,255,0.12)` : 'rgba(255,255,255,0.04)',
              border: `1px solid ${active ? 'var(--cyan)' : 'var(--border)'}`,
              borderRadius: 14, color: active ? m.color : 'var(--text-3)', cursor: 'pointer',
              transition: 'all 200ms ease',
            }}>
              <Ic name={m.icon} size={18} color={active ? m.color : 'var(--text-3)'}/>
              <span style={{ fontSize: 11, fontWeight: 600 }}>{m.label}</span>
            </button>
          );
        })}
      </div>

      {/* Fan speed */}
      <SectionTitle>Fan Speed</SectionTitle>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8, marginBottom: 20 }}>
        {fans.map(f => {
          const active = ac.fanSpeed === f.id;
          return (
            <button key={f.id} onClick={() => onFanChange(f.id)} style={{
              padding: '10px 4px',
              background: active ? 'rgba(0,212,255,0.12)' : 'rgba(255,255,255,0.04)',
              border: `1px solid ${active ? 'var(--cyan)' : 'var(--border)'}`,
              color: active ? 'var(--cyan)' : 'var(--text-2)',
              borderRadius: 12, cursor: 'pointer', fontSize: 13, fontWeight: 600,
              transition: 'all 200ms ease',
            }}>{f.label}</button>
          );
        })}
      </div>

      {/* Quick presets */}
      {(ac.presets || []).length > 0 && (
        <>
          <SectionTitle>Quick Presets</SectionTitle>
          <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4, scrollbarWidth: 'none', marginBottom: 20 }}>
            {(ac.presets || []).map(p => (
              <button key={p.id} onClick={() => onPreset(p)} style={{
                flexShrink: 0, padding: '8px 14px', borderRadius: 20,
                background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border)',
                color: 'var(--text-2)', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 6,
                transition: 'all 150ms ease',
              }}>
                <span style={{ fontSize: 11 }}>{p.temp}°C</span>
                <span>{p.name}</span>
              </button>
            ))}
          </div>
        </>
      )}

      {/* Timer */}
      <SectionTitle action={
        t && (
          <button onClick={() => onTimer(0, 'off')} style={{ background: 'transparent', border: 'none', color: 'var(--red)', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
            Cancel
          </button>
        )
      }>Quick Timer</SectionTitle>
      <Card style={{ padding: 14, marginBottom: 20 }} onClick={() => setTimerSheet(true)}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }}>
          <div style={{ width: 38, height: 38, borderRadius: 11, background: t ? 'rgba(255,171,64,0.16)' : 'rgba(255,171,64,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: t ? 'pulse-glow 2s ease-in-out infinite' : undefined }}>
            <Ic name="clock" size={18} color="var(--amber)"/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            {t ? (
              <>
                <div style={{ fontSize: 13, color: 'var(--text-2)' }}>Will turn <strong style={{ color: '#fff' }}>{t.action.toUpperCase()}</strong> in</div>
                <div className="num" style={{ fontSize: 22, fontWeight: 700, color: 'var(--amber)', letterSpacing: -0.5, fontFamily: 'JetBrains Mono, monospace' }}>
                  {String(mm).padStart(2, '0')}:{String(ss).padStart(2, '0')}
                </div>
              </>
            ) : (
              <>
                <div style={{ fontSize: 14, fontWeight: 500 }}>No active timer</div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>Set a countdown to auto on/off</div>
              </>
            )}
          </div>
          <Ic name="chevronRight" size={16} color="var(--text-3)"/>
        </div>
      </Card>

      {/* Sleep Curve */}
      <SectionTitle>Sleep Curve</SectionTitle>
      <Card style={{ padding: 14, marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500 }}>Rise 1°C/hr while sleeping</div>
            <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>Gradually warms to save energy overnight</div>
            {ac.sleepCurve && (
              <div style={{ fontSize: 11, color: 'var(--cyan)', marginTop: 4 }}>Active · started at {ac.sleepCurve.startTemp}°C</div>
            )}
          </div>
          <Toggle on={!!ac.sleepCurve} onChange={v => onSleepCurve(v)} color="var(--cyan)"/>
        </div>
      </Card>

      {/* Wake-up timer */}
      <SectionTitle>Wake-up Timer</SectionTitle>
      <Card style={{ padding: 14 }}>
        <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 12 }}>Pre-cool before waking</div>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 10 }}>
          <div style={{ fontSize: 12, color: 'var(--text-3)', flex: '0 0 auto' }}>Wake time</div>
          <input type="time" value={ac.wakeTimer?.wakeAt || ''} onChange={e => onWakeTimer({ ...ac.wakeTimer, wakeAt: e.target.value })}
            style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', borderRadius: 10, padding: '8px 10px', color: '#fff', fontSize: 14, fontFamily: 'JetBrains Mono, monospace', colorScheme: 'dark', flex: 1 }}/>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 13, color: 'var(--text-2)' }}>Pre-cool 30 min before wake</div>
          <Toggle on={!!ac.wakeTimer?.preCool} onChange={v => onWakeTimer({ ...ac.wakeTimer, preCool: v })} color="var(--cyan)" size="sm"/>
        </div>
      </Card>

      {timerSheet && (
        <_AcTimerSheet currentOn={ac.on} onApply={(min, action) => { onTimer(min, action); setTimerSheet(false); }} onClose={() => setTimerSheet(false)}/>
      )}
    </>
  );
};

const _AcTimerSheet = ({ currentOn, onApply, onClose }) => {
  const [minutes, setMinutes] = useState(30);
  const presets = [15, 30, 60, 120];
  const action = currentOn ? 'off' : 'on';
  const BottomSh = window.BottomSheet;
  if (!BottomSh) return null;
  return (
    <BottomSh onClose={onClose} title={`Turn ${action.toUpperCase()} after…`}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8, marginBottom: 16 }}>
        {presets.map(p => (
          <button key={p} onClick={() => setMinutes(p)} style={{
            padding: '12px 0',
            background: minutes === p ? 'rgba(0,212,255,0.16)' : 'rgba(255,255,255,0.04)',
            border: `1px solid ${minutes === p ? 'var(--cyan)' : 'var(--border)'}`,
            color: minutes === p ? 'var(--cyan)' : '#fff',
            borderRadius: 12, cursor: 'pointer', fontSize: 14, fontWeight: 600,
          }}>{p}m</button>
        ))}
      </div>
      <div style={{ fontSize: 11, color: 'var(--text-2)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>Custom · {minutes} minutes</div>
      <input type="range" min={1} max={240} step={1} value={minutes} onChange={e => setMinutes(+e.target.value)} style={{ accentColor: 'var(--cyan)', width: '100%' }}/>
      <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
        <Btn variant="ghost" full onClick={onClose}>Cancel</Btn>
        <Btn full icon="clock" onClick={() => onApply(minutes, action)}>Start timer</Btn>
      </div>
    </BottomSh>
  );
};

/* ============================================================
   Live Tab
   ============================================================ */
const _AcLiveTab = ({ ac, isOn }) => {
  const waitingForLive = !!ac.deviceId && ac.online && !ac.mqttReceived;
  return (
    <>
      <SectionTitle>Real-time Telemetry</SectionTitle>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, opacity: waitingForLive ? 0.35 : 1, transition: 'opacity 180ms ease', marginBottom: 8 }}>
        <Metric icon="zap"      label="Voltage" value={waitingForLive ? '—' : (ac.voltage || 0)} unit="V"/>
        <Metric icon="bolt"     label="Current" value={waitingForLive ? '—' : (isOn ? (ac.current || 0).toFixed(2) : '0.00')} unit="A"
          tone={!waitingForLive && isOn && ac.current > (ac.iMax || 10) * 0.85 ? 'amber' : undefined}/>
        <Metric icon="activity" label="Power"   value={waitingForLive ? '—' : (isOn ? AC.fmtNum(ac.power) : 0)} unit="W"
          tone={!waitingForLive && isOn ? 'cyan' : undefined}/>
      </div>

      <Card style={{ padding: 14, marginBottom: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ fontSize: 13, color: 'var(--text-2)' }}>Runtime today</div>
          <span className="num" style={{ fontSize: 14, fontWeight: 600, color: 'var(--cyan)' }}>
            {Math.floor((ac.runtimeToday || 0) / 60)}h {Math.round(ac.runtimeToday || 0) % 60}m
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ fontSize: 13, color: 'var(--text-2)' }}>Energy today</div>
          <span className="num" style={{ fontSize: 14, fontWeight: 600, color: 'var(--amber)' }}>
            {(ac.energyToday || 0).toFixed(2)} kWh
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0' }}>
          <div style={{ fontSize: 13, color: 'var(--text-2)' }}>IR Signal</div>
          <Badge color={ac.irLearned ? 'green' : 'amber'} size="sm">
            {ac.irLearned ? 'Learned' : 'No Signal'}
          </Badge>
        </div>
      </Card>

      <Card style={{ padding: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ fontSize: 13, color: 'var(--text-2)' }}>Mode</div>
          <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--cyan)' }}>
            {(AC_MODES.find(m => m.id === ac.mode) || AC_MODES[0]).label}
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ fontSize: 13, color: 'var(--text-2)' }}>Fan Speed</div>
          <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
            {(AC_FANS.find(f => f.id === ac.fanSpeed) || AC_FANS[3]).label}
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0' }}>
          <div style={{ fontSize: 13, color: 'var(--text-2)' }}>Set Temperature</div>
          <span className="num" style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>{ac.temp || 24}°C</span>
        </div>
      </Card>
    </>
  );
};

/* ============================================================
   Schedule Tab
   ============================================================ */
const _AcScheduleTab = ({ ac, scheduleEditor, setScheduleEditor, onSave, onDelete, onToggle }) => {
  const SchedCard   = window.ScheduleCard;
  const SchedEditor = window.ScheduleEditor;

  return (
    <>
      <SectionTitle action={
        <button onClick={() => setScheduleEditor('new')} style={{ background: 'transparent', border: 'none', color: 'var(--cyan)', fontSize: 12, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 4, cursor: 'pointer', padding: '4px 0' }}>
          <Ic name="plus" size={12}/> Add Schedule
        </button>
      }>Schedules</SectionTitle>

      {(ac.schedules || []).length === 0 ? (
        <Card style={{ padding: 20, textAlign: 'center' }}>
          <Ic name="calendar" size={28} color="var(--text-3)"/>
          <div style={{ fontSize: 13, fontWeight: 500, marginTop: 8 }}>No schedules yet</div>
          <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 4 }}>Automate your AC to turn on or off at specific times.</div>
          <div style={{ marginTop: 14 }}>
            <Btn icon="plus" size="sm" onClick={() => setScheduleEditor('new')}>Create schedule</Btn>
          </div>
        </Card>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {(ac.schedules || []).map(s => SchedCard
            ? <SchedCard key={s.id} sched={s} onEdit={() => setScheduleEditor(s)} onToggle={v => onToggle(s.id, v)}/>
            : <div key={s.id}>{s.label || s.action}</div>
          )}
        </div>
      )}
    </>
  );
};

const _AcScheduleEditorSheet = ({ initial, onSave, onDelete, onClose }) => {
  const SchedEditor = window.ScheduleEditor;
  if (SchedEditor) {
    return <SchedEditor initial={initial} onSave={onSave} onDelete={onDelete} onClose={onClose}/>;
  }
  return null;
};

/* ============================================================
   Settings Tab
   ============================================================ */
const _AcSettingsTab = ({ ac, _isVirtual, onSave }) => {
  const [draftBrand,     setDraftBrand]     = useState(ac.brand || '');
  const [draftModel,     setDraftModel]     = useState(ac.model || '');
  const [draftSwitch,    setDraftSwitch]    = useState(ac.switchType || 'round');
  const [draftIMax,      setDraftIMax]      = useState(ac.iMax || 10);
  const [draftVLow,      setDraftVLow]      = useState(ac.vLow || 180);
  const [draftVHigh,     setDraftVHigh]     = useState(ac.vHigh || 260);
  const [draftPowerMax,  setDraftPowerMax]  = useState(ac.powerMax || 2500);
  const [draftName,      setDraftName]      = useState(ac.name || '');
  const [learnState,     setLearnState]     = useState('idle'); // idle | counting | done
  const [learnCount,     setLearnCount]     = useState(10);
  const [saved, setSaved] = useState(false);
  const toast = useToast();

  const brands = AC_BRANDS;
  const selectedBrand = brands.find(b => b.id === draftBrand);
  const models = selectedBrand ? selectedBrand.models : [];

  const startLearn = () => {
    if (_isVirtual) {
      setLearnState('counting');
      setLearnCount(10);
      let c = 10;
      const id = setInterval(() => {
        c--;
        setLearnCount(c);
        if (c <= 0) {
          clearInterval(id);
          setLearnState('done');
          onSave({ irLearned: true });
          toast('IR signal learned successfully', { kind: 'success' });
        }
      }, 500);
    } else if (ac.deviceId && window.MQ) {
      MQ.publishCmd(ac.deviceId, 'ir_learn', true);
      setLearnState('counting');
      setLearnCount(10);
      let c = 10;
      const id = setInterval(() => { c--; setLearnCount(c); if (c <= 0) { clearInterval(id); setLearnState('idle'); } }, 1000);
      toast('Point remote at device and press any button', { kind: 'info' });
    }
  };

  const handleSave = () => {
    const patch = {};
    if (draftName    !== ac.name)      patch.name       = draftName;
    if (draftBrand   !== ac.brand)     patch.brand      = draftBrand;
    if (draftModel   !== ac.model)     patch.model      = draftModel;
    if (draftSwitch  !== ac.switchType) patch.switchType = draftSwitch;
    if (draftIMax    !== ac.iMax)      patch.iMax       = draftIMax;
    if (draftVLow    !== ac.vLow)      patch.vLow       = draftVLow;
    if (draftVHigh   !== ac.vHigh)     patch.vHigh      = draftVHigh;
    if (draftPowerMax !== ac.powerMax) patch.powerMax   = draftPowerMax;
    if (Object.keys(patch).length) {
      onSave(patch);
      setSaved(true);
      setTimeout(() => setSaved(false), 2500);
    }
  };

  const SwitchTypes = window._SWITCH_TYPES || [];
  const SwitchPreview = window._SwitchPreview;

  return (
    <>
      <SectionTitle>Device Name</SectionTitle>
      <Card style={{ padding: 14, marginBottom: 4 }}>
        <TextInput icon="edit" value={draftName} onChange={v => setDraftName(v)} placeholder="e.g. Living Room AC"/>
      </Card>

      <SectionTitle>AC Brand &amp; Model</SectionTitle>
      <Card style={{ padding: 14 }}>
        <div style={{ marginBottom: 10 }}>
          <div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 6 }}>Brand</div>
          <select value={draftBrand} onChange={e => { setDraftBrand(e.target.value); setDraftModel(''); }}
            style={{ width: '100%', padding: '10px 12px', borderRadius: 10, background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', color: 'var(--text)', fontSize: 14, colorScheme: 'dark' }}>
            <option value="">Select Brand</option>
            {brands.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
          </select>
        </div>
        {models.length > 0 && (
          <div>
            <div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 6 }}>Model</div>
            <select value={draftModel} onChange={e => setDraftModel(e.target.value)}
              style={{ width: '100%', padding: '10px 12px', borderRadius: 10, background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', color: 'var(--text)', fontSize: 14, colorScheme: 'dark' }}>
              <option value="">Select Model</option>
              {models.map(m => <option key={m} value={m}>{m}</option>)}
            </select>
          </div>
        )}
      </Card>

      <SectionTitle>IR Learning</SectionTitle>
      <Card style={{ padding: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500 }}>Learn Remote</div>
            <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>
              {ac.irLearned ? 'IR signal has been learned' : 'No IR signal — tap to learn from remote'}
            </div>
            {learnState === 'counting' && (
              <div style={{ fontSize: 12, color: 'var(--amber)', marginTop: 4 }}>Point remote at device… {learnCount}s</div>
            )}
            {learnState === 'done' && (
              <div style={{ fontSize: 12, color: 'var(--green)', marginTop: 4 }}>Signal learned!</div>
            )}
          </div>
          <Btn size="sm" variant={ac.irLearned ? 'ghost' : 'primary'} onClick={startLearn} disabled={learnState === 'counting'}>
            {learnState === 'counting' ? 'Learning…' : ac.irLearned ? 'Re-learn' : 'Learn'}
          </Btn>
        </div>
      </Card>

      {SwitchTypes.length > 0 && (
        <>
          <SectionTitle>Switch Style</SectionTitle>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 8 }}>
            {SwitchTypes.map(st => {
              const active = draftSwitch === st.id;
              return (
                <button key={st.id} onClick={() => setDraftSwitch(st.id)} style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, padding: '14px 8px',
                  background: active ? 'rgba(0,212,255,0.10)' : 'rgba(255,255,255,0.04)',
                  border: `1px solid ${active ? 'var(--cyan)' : 'var(--border)'}`,
                  borderRadius: 14, color: '#fff', cursor: 'pointer', transition: 'all 200ms ease',
                }}>
                  {SwitchPreview && <SwitchPreview kind={st.id} active={active}/>}
                  <div style={{ fontSize: 12, fontWeight: 600, marginTop: 4 }}>{st.label}</div>
                  <div style={{ fontSize: 10, color: 'var(--text-3)' }}>{st.desc}</div>
                </button>
              );
            })}
          </div>
        </>
      )}

      <SectionTitle>Protection</SectionTitle>
      <Card style={{ padding: 14 }}>
        <SliderRow label="Overload threshold"
          hint={`Cut power if current exceeds ${draftIMax} A`}
          value={draftIMax} onChange={v => setDraftIMax(v)}
          min={1} max={16} step={1} unit=" A" color="var(--red)"/>
        <div style={{ height: 1, background: 'var(--border)', margin: '6px 0' }}/>
        <SliderRow label="Max power"
          hint={`Trip if power exceeds ${draftPowerMax} W`}
          value={draftPowerMax} onChange={v => setDraftPowerMax(v)}
          min={500} max={5000} step={100} unit=" W" color="var(--amber)"/>
        <div style={{ height: 1, background: 'var(--border)', margin: '6px 0' }}/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, paddingTop: 8 }}>
          <div>
            <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 6 }}>Low voltage (V)</div>
            <input type="number" value={draftVLow} onChange={e => setDraftVLow(+e.target.value)} min={100} max={220}
              style={{ width: '100%', padding: '8px 10px', borderRadius: 10, background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', color: '#fff', fontSize: 14 }}/>
          </div>
          <div>
            <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 6 }}>High voltage (V)</div>
            <input type="number" value={draftVHigh} onChange={e => setDraftVHigh(+e.target.value)} min={230} max={300}
              style={{ width: '100%', padding: '8px 10px', borderRadius: 10, background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', color: '#fff', fontSize: 14 }}/>
          </div>
        </div>
      </Card>

      <SectionTitle>Quick Test</SectionTitle>
      <Card style={{ padding: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500 }}>IR Test Pulse</div>
            <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>Verify IR blaster is working</div>
          </div>
          <Btn size="sm" variant="ghost" onClick={() => {
            if (_isVirtual) {
              toast('IR test pulse sent', { kind: 'success' });
            } else if (ac.deviceId && window.MQ) {
              MQ.publishCmd(ac.deviceId, 'ir_test', true);
              toast('IR test pulse sent', { kind: 'info' });
            }
          }}>Test</Btn>
        </div>
      </Card>

      <Btn full variant="primary" icon="check" onClick={handleSave}
        style={{ marginTop: 16, transition: 'all 300ms', ...(saved ? { background: 'linear-gradient(135deg,var(--green),var(--teal))', color: '#062b18' } : {}) }}>
        {saved ? 'Saved ✓' : 'Save Settings'}
      </Btn>
    </>
  );
};

window.AcDetail = AcDetail;
