import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
// Import the JSON data
import buttonsData from "./buttons.json"

export default (() => {
  // Define the component
  const Btn8831: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps) => {
    // Group buttons by type
    const groupedButtons = groupButtonsByType(buttonsData)

    // Define the order of types
    const typeOrder = ["friend", "standard", "misc"]

    return (
      <div class={`btn8831-container ${displayClass ?? ""}`}>
        {typeOrder.map((type, index) => {
          const buttons = groupedButtons[type]
          if (buttons && buttons.length > 0) {
            return (
              <div key={type}>
                {/* Render buttons of the current type */}
                <div class="button-group">
                  {buttons.map((button, idx) => (
                    <div key={idx} class="button-item">
                      {renderButtonContent(button)}
                    </div>
                  ))}
                </div>
                {/* Add a horizontal line after the group except for the last one */}
                {index < typeOrder.length - 1 && <hr />}
              </div>
            )
          }
          return null
        })}
      </div>
    )
  }

  // Function to group buttons by type
  function groupButtonsByType(buttons: any[]) {
    const groups: { [key: string]: any[] } = {
      misc: [],
      friend: [],
      standard: [],
    }

    buttons.forEach((button: any) => {
      let type = button.type?.toLowerCase() || "standard"
      if (type === "fren") type = "friend"
      if (!groups[type]) type = "standard" // Default to 'standard' if type is unrecognized
      groups[type].push(button)
    })

    return groups
  }

  // Updated renderButtonContent function
  function renderButtonContent(button: any): preact.VNode | null {
    const contentType = button.contentType || "image" // Default to 'image'

    if (contentType === "image") {
      // Create the <img> element
      const imgElement = (
        <img
          src={button.image}
          alt={button.alt}
          title={button.title}
          loading="lazy"
          decoding="async"
        />
      )

      // If `button.url` is present, wrap the image in an `<a>` tag
      if (button.url) {
        return <a href={button.url}>{imgElement}</a>
      } else {
        // If no `url`, return the image element without wrapping
        return imgElement
      }
    } else if (contentType === "iframe") {
      const iframeAttrs = button.iframeAttributes || {}
      return <iframe src={button.url} title={button.title} {...iframeAttrs}></iframe>
    } else {
      // Handle other content types if necessary
      return null
    }
  }

  return Btn8831
}) satisfies QuartzComponentConstructor
