import browser from "webextension-polyfill"
import { graphql } from "~/shared/messaging"
import type { GetDevToolStyleDocument } from "~/generated/graphql"

const gql = String.raw

const getStyle = gql`
  query GetDevToolStyle($url: String!) {
    preferences {
      enabled
    }
    files(filter: { url: $url, enabled: true }, logQuery: true) {
      sections {
        compiledCode
      }
    }
  }
`

void graphql<GetDevToolStyleDocument>(getStyle as any, {
  url: "chrome-devtools://devtools/bundled/inspector.html",
})
  .then(({ data }) => {
    if (data?.preferences.enabled) {
      const content = data.files.map(file => file.sections[0].compiledCode).join("\n")
      browser.devtools.panels.applyStyleSheet(content)
    }
  })
  .catch(err => {
    console.error(err)
  })

declare module "webextension-polyfill/namespaces/devtools_panels.d.ts" {
  namespace DevtoolsPanels {
    interface Static {
      applyStyleSheet(css: string): void
    }
  }
}
