import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import type { SetupConfig, DeviceStatus, GateConfig } from '../protocol/types';
import { DataChannel } from '../protocol/constants';
import { fileStorage } from '../utils/storage';

const DEFAULT_GATE_CONFIG: GateConfig = {
  tStart:  100,
  tEnd:    3000,
  count:   10,
  spacing: 'log',
};

const DEFAULT_CONFIG: SetupConfig = {
  channelNum: 3,
  sendFreq: 0x05,      // 16 Hz
  sampleFreq: 0x00,    // 250 kHz
  sampleDepth: 2000,
  accNum: 32,
  negAcc456: false,
  negAcc123: false,
  ampRatio: 0x03,      // 1×
  dataChannel: DataChannel.WIFI,
  compRes: 12,
  secondSampleFreq: 0x00,
  compDisableDelay: 60,
  sourceMode: 0x00,    // single source A
  batteryVoltageMin: 0,
  filePrefix: new Date().toISOString().slice(0, 10).replace(/-/g, ''),
};

interface DeviceState {
  // ── Device config (persisted) ──────────────────────────────────────────────
  config:       SetupConfig;
  gateConfig:   GateConfig;
  configDirty:  boolean;   // true when config changed but not yet sent to device
  // ── Runtime status (not persisted) ────────────────────────────────────────
  deviceStatus: DeviceStatus;
  // ── Telemetry (not persisted) ─────────────────────────────────────────────
  batteryVolt:  number;
  temperature:  number;
  gpsStatus:    number;
  sdStatus:     number;
  frameId:      number;
  accCount:     number;
  setConfig:        (cfg: SetupConfig) => void;
  updateConfig:     (partial: Partial<SetupConfig>) => void;
  setGateConfig:    (cfg: GateConfig) => void;
  setConfigDirty:   (v: boolean) => void;
  setDeviceStatus:  (s: DeviceStatus) => void;
  updateTelemetry:  (data: {
    batteryVolt?: number;
    temperature?: number;
    gpsStatus?: number;
    sdStatus?: number;
    frameId?: number;
    accCount?: number;
  }) => void;
}

export const useDeviceStore = create<DeviceState>()(
  persist(
    (set) => ({
      config:       DEFAULT_CONFIG,
      gateConfig:   DEFAULT_GATE_CONFIG,
      configDirty:  false,
      deviceStatus: 'idle',
      batteryVolt:  0,
      temperature:  0,
      gpsStatus:    0,
      sdStatus:     0,
      frameId:      0,
      accCount:     0,
      setConfig:       (config)      => set({ config, configDirty: true }),
      updateConfig:    (partial)     => set((s) => ({ config: { ...s.config, ...partial }, configDirty: true })),
      setGateConfig:   (gateConfig)  => set({ gateConfig }),
      setConfigDirty:  (configDirty) => set({ configDirty }),
      setDeviceStatus: (deviceStatus) => set({ deviceStatus }),
      updateTelemetry: (data) => set((s) => ({ ...s, ...data })),
    }),
    {
      name: 'device-config',
      storage: createJSONStorage(() => fileStorage),
      partialize: (state) => ({ config: state.config, gateConfig: state.gateConfig }),
    },
  ),
);
