import { useState } from "react";
import Menu from "./menu";
import Message from "~components/ui/message";
import { clsn } from "~utils";
import "assets/global.less";
import styles from "./popup.module.less";

function IndexPopup() {
  const [tab, setTab] = useState<string>();

  const onBack = () => {
    setTab(undefined);
  }

  const onClickMenu = (value: string) => {
    if (value === "options") {
      chrome.runtime.openOptionsPage();

      return;
    }
    else if (value === "home") {
      chrome.storage.local.get(["siteUrl"]).then((res) => {
        if (res.siteUrl) {
          chrome.tabs.create({ url: res.siteUrl });
        }
      });

      return;
    }

    chrome.tabs.query({ active: true, lastFocusedWindow: true }).then((tabs) => {
      const { id, windowId } = tabs[0];

      chrome.sidePanel.setOptions({ path: `sidepanel.html?type=${value}` })
      chrome.sidePanel.open({ tabId: id, windowId });

      window.close();
    });
  }

  return (
    <>
      <div className={clsn(styles.root, tab && styles.hasTab)}>
        <Menu onClick={onClickMenu} />
      </div>
      <Message />
    </>
  );
}

export default IndexPopup;
