/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="dom" />
import type { Scrapbox } from "https://raw.githubusercontent.com/scrapbox-jp/types/0.3.2/userscript.ts";
declare const scrapbox: Scrapbox;

export interface Button {
  title: string;
  onClick: () => string;
  className?: string;
};

export const defaultSettings: Button[] = ["[]", "#", "*", "/", ">", "``", ".", ">", "+"]
  .map(
    (text) => ({
      title: text,
      onClick: () => text,
    })
  );

export const setup = (settings: Button[]) => {
  const supporter = makeSupporter();
  supporter.append(...settings.map(
    ({ title, className, onClick }) => makeButton(title, onClick, className)
  ));
  
  const app = document.createElement("div");
  const shadowRoot = app.attachShadow({ mode: "open" });
  const style = document.createElement("style");
  style.textContent = ".input-supporter{position:fixed;right:0;bottom:0;left:0;justify-content:space-between;width:100%;border-radius:8px 8px 0 0;background:#FFF;border:solid 1px #37352f17;box-shadow:#0f0f0f0d 0 0 0 1px,#0f0f0f1a 0 3px 6px,#0f0f0f33 0 9px 24px;z-index:300}.ins-btn{width:12.5%;width:calc(100% / 8);padding:12px 0;background:none;border:none;color:#111}.ins-btn:not(:first-child){border-left:solid 1px #37352f17}@media (max-width: 767px){.input-supporter{display:flex}}";
  shadowRoot.appendChild(style);
  shadowRoot.appendChild(supporter);
  document.body.append(app);
  
  const changeVisible = () =>
    app.style.display = scrapbox.Layout === "page" ? "" : "none";
  
  changeVisible();
  scrapbox.addListener("layout:changed", changeVisible);
};

const makeSupporter = () => {
  const div = document.createElement("div");
  div.classList.add("input-supporter");
  return div;
};

const makeButton = (title: string, onClick: () => string, className?: string) => {
  const button = document.createElement("button");
  button.classList.add("ins-btn");
  if (className) button.classList.add(className);
  button.textContent = title;
  button.addEventListener("click", () => {
 	const cursor = document.getElementById('text-input') as HTMLTextAreaElement | null;
    if (!cursor) {
      throw Error("#text-input is not ditected.");
    }
    
    cursor.focus();
    cursor.value = onClick();
  
    const event = new InputEvent("input", { bubbles: true });
    cursor.dispatchEvent(event);
  });
  return button;
};