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-check", `
  .at-check{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-check input{position:absolute;width:1px;height:1px;opacity:0;margin:0}
  .at-check__box{flex:0 0 16px;width:16px;height:16px;border:1px solid var(--border-subtle);
    border-radius:var(--radius-sm);background:var(--at-white);display:grid;place-items:center;
    transition:background .12s ease,border-color .12s ease,box-shadow .12s ease}
  .at-check--radio .at-check__box{border-radius:var(--radius-pill)}
  .at-check__box svg{width:11px;height:11px;color:var(--at-white);opacity:0;transition:opacity .1s ease}
  .at-check--radio .at-check__box::after{content:"";width:6px;height:6px;border-radius:var(--radius-pill);
    background:var(--at-white);opacity:0;transition:opacity .1s ease}
  .at-check input:checked + .at-check__box{background:var(--at-flush-600);border-color:var(--at-flush-600)}
  .at-check input:checked + .at-check__box svg,
  .at-check--radio input:checked + .at-check__box::after{opacity:1}
  .at-check input:focus-visible + .at-check__box{box-shadow:var(--ring-accent)}
  .at-check.is-disabled,
  .at-check input:disabled + .at-check__box{opacity:.5;cursor:not-allowed}
`);

const CHECK = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 13l4 4L19 7" />
  </svg>
);

export function Checkbox({ type = "checkbox", disabled = false, children, ...rest }) {
  const radio = type === "radio";
  const cls = ["at-check", radio ? "at-check--radio" : "", disabled ? "is-disabled" : ""].filter(Boolean).join(" ");
  return (
    <label className={cls}>
      <input type={radio ? "radio" : "checkbox"} disabled={disabled} {...rest} />
      <span className="at-check__box">{!radio && CHECK}</span>
      {children}
    </label>
  );
}
