import { defineStore, acceptHMRUpdate } from 'pinia';

// 缁勪欢鏁版嵁缁撴瀯
type WidgetSize = '1x1' | '1x2' | '2x1' | '2x2' | '2x4';
const DEFAULT_GROUP_ID = 'home';
interface Widget {
  id: string;
  component: string; // 娓叉煋鐨勭粍浠跺悕
  size: WidgetSize; // 缁勪欢灏哄
  gridPosition: { x: number; y: number }; // 缃戞牸浣嶇疆
  data?: any; // 缁勪欢鏁版嵁
  groupId?: string;
  folderId?: string;
}

interface WidgetsState {
  widgets: Widget[];
}

const defaultWidgets: Widget[] = [
  { 
    id: 'widget-1', 
    component: 'CalendarWidget', 
    size: '1x1',
    gridPosition: { x: 0, y: 0 }
  },
  { 
    id: 'widget-2', 
    component: 'HotSearchWidget', 
    size: '2x1',
    gridPosition: { x: 1, y: 0 },
    data: {
      tabs: ['热点', '新闻', '视频'],
      items: [
        { title: '平台确认新品发售', value: '780.9万' },
        { title: '网友热议某话题', value: '771.2万' },
        { title: '新机性能实测数据', value: '761.8万' },
        { title: '首个万亿级经济区新闻', value: '752.2万' }
      ]
    }
  },
  {
    id: 'widget-3',
    component: 'CountdownWidget',
    size: '2x1',
    gridPosition: { x: 0, y: 1 }
  }
];

const savedWidgets = localStorage.getItem('itab_widgets');

const defaultGroupById: Record<string, string> = {
  'widget-1': 'home',
  'widget-2': 'fun',
  'widget-3': 'product',
};

const normalizeWidgets = (widgets: Widget[]): Widget[] =>
  widgets.map(widget => ({
    ...widget,
    groupId: widget.groupId ?? defaultGroupById[widget.id] ?? DEFAULT_GROUP_ID,
  }));

const loadWidgets = (): Widget[] => {
  if (!savedWidgets) return normalizeWidgets(defaultWidgets);
  try {
    return normalizeWidgets(JSON.parse(savedWidgets) as Widget[]);
  } catch {
    return normalizeWidgets(defaultWidgets);
  }
};

// 妯℃嫙鏁版嵁锛堟潵鑷埅鍥惧弬鑰冿級
export const useWidgetsStore = defineStore('widgets', {
  state: (): WidgetsState => ({
    widgets: loadWidgets(),
  }),
  actions: {
    addWidget(payload: { component: string; size?: WidgetSize; data?: any; groupId?: string }) {
      const nextId = `widget-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
      const nextWidget: Widget = {
        id: nextId,
        component: payload.component,
        size: payload.size ?? '1x1',
        gridPosition: { x: 0, y: 0 },
        data: payload.data,
        groupId: payload.groupId ?? DEFAULT_GROUP_ID,
      };
      this.widgets.push(nextWidget);
      localStorage.setItem('itab_widgets', JSON.stringify(this.widgets));
    },
    replaceWidget(widgetId: string, payload: { component: string; size?: WidgetSize; data?: any }) {
      const widget = this.widgets.find(item => item.id === widgetId);
      if (!widget) return;
      widget.component = payload.component;
      if (payload.size) {
        widget.size = payload.size;
      }
      widget.data = payload.data;
      localStorage.setItem('itab_widgets', JSON.stringify(this.widgets));
    },
    deleteWidget(widgetId: string) {
      const index = this.widgets.findIndex(widget => widget.id === widgetId);
      if (index !== -1) {
        this.widgets.splice(index, 1);
        localStorage.setItem('itab_widgets', JSON.stringify(this.widgets));
      }
    },
    updateWidgetSize(widgetId: string, newSize: WidgetSize) {
      const widget = this.widgets.find(w => w.id === widgetId);
      if (widget) {
        widget.size = newSize;
        localStorage.setItem('itab_widgets', JSON.stringify(this.widgets));
      }
    },
    updateWidgetPosition(widgetId: string, x: number, y: number) {
      const widget = this.widgets.find(w => w.id === widgetId);
      if (widget) {
        widget.gridPosition = { x, y };
        localStorage.setItem('itab_widgets', JSON.stringify(this.widgets));
      }
    },
    updateWidgetFolder(widgetId: string, folderId?: string, groupId?: string) {
      const widget = this.widgets.find(w => w.id === widgetId);
      if (!widget) return;
      widget.folderId = folderId;
      if (groupId) {
        widget.groupId = groupId;
      }
      localStorage.setItem('itab_widgets', JSON.stringify(this.widgets));
    },
    setWidgetOrder(orderIds: string[]) {
      const ordered: Widget[] = [];
      const seen = new Set<string>();
      for (const id of orderIds) {
        const widget = this.widgets.find(item => item.id === id);
        if (widget) {
          ordered.push(widget);
          seen.add(widget.id);
        }
      }
      for (const widget of this.widgets) {
        if (!seen.has(widget.id)) {
          ordered.push(widget);
        }
      }
      this.widgets = ordered;
      localStorage.setItem('itab_widgets', JSON.stringify(this.widgets));
    }
  }
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useWidgetsStore, import.meta.hot));
}

