import React from "react";

function ensureStyle(id, css) {
  if (typeof document === "undefined") return;
  if (document.getElementById(id)) return;
  const el = document.createElement("style");
  el.id = id; el.textContent = css;
  document.head.appendChild(el);
}

ensureStyle("at-switch", `
  .at-switch{display:inline-flex;align-items:center;gap:8px;font-family:var(--font-sans);font-size:13px;
    line-height:18px;color:var(--fg-2);cursor:pointer}
  .at-switch input{position:absolute;width:1px;height:1px;opacity:0;margin:0}
  .at-switch__track{flex:0 0 34px;width:34px;height:20px;border-radius:var(--radius-pill);
    background:var(--border-subtle);position:relative;transition:background .14s ease,box-shadow .12s ease}
  .at-switch__track::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;
    border-radius:var(--radius-pill);background:var(--at-white);box-shadow:0 1px 2px rgba(43,24,38,.25);
    transition:transform .14s ease}
  .at-switch input:checked + .at-switch__track{background:var(--at-flush-600)}
  .at-switch input:checked + .at-switch__track::after{transform:translateX(14px)}
  .at-switch input:focus-visible + .at-switch__track{box-shadow:var(--ring-accent)}
  .at-switch.is-disabled{opacity:.5;cursor:not-allowed}
  @media (prefers-reduced-motion: reduce){
    .at-switch__track,.at-switch__track::after{transition:background .12s ease}
  }
`);

export function Switch({ disabled = false, children, ...rest }) {
  const cls = ["at-switch", disabled ? "is-disabled" : ""].filter(Boolean).join(" ");
  return (
    <label className={cls}>
      <input type="checkbox" role="switch" disabled={disabled} {...rest} />
      <span className="at-switch__track" />
      {children}
    </label>
  );
}
