"use client";

import { useState } from "react";

interface ToggleProps {
  defaultChecked?: boolean;
  disabled?: boolean;
  label?: string;
  onChange?: (checked: boolean) => void;
}

export function Toggle({ defaultChecked = false, disabled = false, label, onChange }: ToggleProps) {
  const [checked, setChecked] = useState(defaultChecked);

  function handleToggle() {
    if (disabled) return;
    const next = !checked;
    setChecked(next);
    onChange?.(next);
  }

  return (
    <div
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 10,
        cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.5 : 1,
        userSelect: "none",
      }}
      onClick={handleToggle}
      role="switch"
      aria-checked={checked}
      tabIndex={disabled ? -1 : 0}
      onKeyDown={(e) => {
        if (e.key === " " || e.key === "Enter") {
          e.preventDefault();
          handleToggle();
        }
      }}
    >
      <div
        className="bb-toggle-track"
        style={{ background: checked ? "var(--brand-073m)" : "#d1d5db" }}
      >
        <div
          className="bb-toggle-thumb"
          style={{ transform: checked ? "translateX(20px)" : "translateX(0)" }}
        />
      </div>
      {label && (
        <span style={{ fontSize: 14, color: "var(--bb-text)", fontFamily: "var(--font-web)" }}>
          {label}
        </span>
      )}
    </div>
  );
}
