// Written by retoor@molodetz.nl

// This JavaScript class defines a custom HTML element <fancy-button>, which creates a styled, clickable button element with customizable size, text, and URL redirect functionality.

// MIT License

class FancyButton extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.url = null;
    this.type = "button";
    this.value = null;
  }

  connectedCallback() {
    this.container = document.createElement("span");
    let size = this.getAttribute("size");
    console.info({ GG: size });
    size = size === "auto" ? "1%" : "33%";

    this.styleElement = document.createElement("style");
    this.styleElement.innerHTML = `
        :root {
            width: 100%;
            --width: 100%;
        }
        button {
            width: var(--width);
            min-width: ${size};
            padding: 10px;
            background-color: #f05a28;
            border: none;
            border-radius: 5px;
            color: white;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s;
            border: 1px solid #f05a28;
        }
        button:hover {
            color: #EFEFEF;
            background-color: #e04924;
            border: 1px solid #efefef;
        }
        `;

    this.container.appendChild(this.styleElement);
    this.buttonElement = document.createElement("button");
    this.container.appendChild(this.buttonElement);
    this.shadowRoot.appendChild(this.container);

    this.url = this.getAttribute("url");

    this.value = this.getAttribute("value");
    this.buttonElement.appendChild(
      document.createTextNode(this.getAttribute("text")),
    );
    this.buttonElement.addEventListener("click", () => {
      if (this.url == "submit") {
        this.closest("form").submit();
        return;
      }

      if (this.url === "/back" || this.url === "/back/") {
        window.history.back();
      } else if (this.url) {
        window.location = this.url;
      }
    });
  }
}

customElements.define("fancy-button", FancyButton);
