<script lang="ts">
    import type { Snippet } from "svelte";

    type Variant =
        | "primary"
        | "secondary"
        | "success"
        | "danger"
        | "warning"
        | "ghost"
        | "toggle"
        | "icon";
    type Size = "sm" | "md" | "lg" | "icon" | "square" | "hug";

    interface Props {
        variant?: Variant;
        size?: Size;
        disabled?: boolean;
        active?: boolean;
        onclick?: () => void;
        children: Snippet;
        class?: string;
        ariaLabel?: string;
        type?: "button" | "submit" | "reset";
        href?: string;
        reload?: boolean;
    }

    let {
        variant = "primary",
        size = "md",
        disabled = false,
        active = false,
        onclick,
        children,
        class: className = "",
        ariaLabel,
        type = "button",
        href,
        reload = false,
    }: Props = $props();

    const baseClasses =
        "inline-flex items-center justify-center border-4 border-black box-border cursor-pointer transition-all hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed";

    const variantClasses: Record<Variant, string> = {
        primary: "bg-kv-blue text-kv-white kv-shadow-button",
        secondary: "bg-kv-yellow text-black kv-shadow-button",
        success: "bg-kv-green text-kv-white",
        danger: "bg-kv-red text-kv-white",
        warning: "bg-kv-yellow text-black",
        ghost: "bg-transparent text-kv-white",
        toggle: "bg-transparent",
        icon: "bg-transparent border-none p-0",
    };

    // Use -plain variants (no text shadow on buttons)
    const sizeClasses: Record<Size, string> = {
        sm: "px-3 py-1 kv-body-sm-plain",
        md: "px-4 py-2 kv-body-lg-plain",
        lg: "px-6 py-4 kv-h3-plain",
        icon: "w-10 h-10",
        square: "w-12 h-12 font-kv-body text-xl uppercase",
        hug: "px-4 h-12 font-kv-body text-xl uppercase",
    };

    // For toggle variant, apply active state colors (must be reactive)
    let activeClass = $derived(
        variant === "toggle" && active ? "text-kv-yellow" : "",
    );
    let inactiveClass = $derived(
        variant === "toggle" && !active ? "text-kv-white" : "",
    );
    let iconColorClass = $derived(variant === "icon" ? "text-kv-yellow" : "");

    let combinedClasses = $derived(
        `${baseClasses} ${variantClasses[variant]} ${sizeClasses[size]} ${activeClass} ${inactiveClass} ${iconColorClass} ${className}`,
    );
</script>

{#if href}
    <a
        {href}
        class={combinedClasses}
        aria-label={ariaLabel}
        data-sveltekit-reload={reload || undefined}
    >
        {@render children()}
    </a>
{:else}
    <button
        {type}
        class={combinedClasses}
        {disabled}
        {onclick}
        aria-label={ariaLabel}
        aria-disabled={disabled}
    >
        {@render children()}
    </button>
{/if}
