import { vi } from 'vitest'

const storage = {}
let notificationId = 0
let notifications = []

export const mockBrowser = {
  storage: {
    local: {
      get: vi.fn((keys) => {
        if (typeof keys === 'string') {
          return Promise.resolve({ [keys]: storage[keys] })
        }
        if (Array.isArray(keys)) {
          const result = {}
          keys.forEach((key) => {
            result[key] = storage[key]
          })
          return Promise.resolve(result)
        }
        if (keys && typeof keys === 'object') {
          const result = {}
          Object.keys(keys).forEach((key) => {
            result[key] = storage[key] !== undefined ? storage[key] : keys[key]
          })
          return Promise.resolve(result)
        }
        return Promise.resolve({})
      }),
      set: vi.fn((obj) => {
        Object.assign(storage, obj)
        return Promise.resolve()
      }),
      remove: vi.fn((keys) => {
        if (Array.isArray(keys)) {
          keys.forEach((key) => delete storage[key])
        } else {
          delete storage[keys]
        }
        return Promise.resolve()
      }),
      clear: vi.fn(() => {
        Object.keys(storage).forEach((key) => delete storage[key])
        return Promise.resolve()
      }),
      _reset: () => {
        Object.keys(storage).forEach((key) => delete storage[key])
      }
    }
  },
  notifications: {
    create: vi.fn((id, options) => {
      notifications.push({ id, options })
      return `notification-${++notificationId}`
    }),
    _notifications: notifications,
    _reset: () => {
      notifications.length = 0
      notificationId = 0
    }
  },
  windows: {
    getLastFocused: vi.fn(() =>
      Promise.resolve({
        top: 100,
        left: 100,
        width: 1920,
        height: 1080
      })
    ),
    create: vi.fn(() => Promise.resolve({ id: 123 })),
    remove: vi.fn(() => Promise.resolve()),
    get: vi.fn(() => Promise.resolve({ id: 123, top: 100, left: 100 }))
  },
  tabs: {
    create: vi.fn(() => Promise.resolve({ id: 456 })),
    remove: vi.fn(() => Promise.resolve())
  },
  runtime: {
    getURL: vi.fn((path) => `chrome-extension://abc123/${path}`)
  }
}

global.browser = mockBrowser

export { storage }
