import { defineStore } from 'pinia';

// 组件数据结构
type WidgetSize = '1x1' | '1x2' | '2x1' | '2x2' | '2x4';
interface Widget {
  id: string;
  component: string; // 渲染的组件名
  size: WidgetSize; // 组件尺寸
  gridPosition: { x: number; y: number }; // 网格位置
  data?: any; // 组件数据
}

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: '突破8100亿元这场双向奔赴很燃', value: '761.8万' },
        { title: '第一个2万亿经济大区要来了', value: '752.2万' }
      ]
    }
  },
  {
    id: 'widget-3',
    component: 'CountdownWidget',
    size: '2x1',
    gridPosition: { x: 0, y: 1 }
  }
];

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

// 模拟数据（来自截图参考）
export const useWidgetsStore = defineStore('widgets', {
  state: (): WidgetsState => ({
    widgets: savedWidgets ? JSON.parse(savedWidgets) : defaultWidgets,
  }),
  actions: {
    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));
      }
    },
    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));
    }
  }
});
