import React from "react";
import { Button } from "../core/Button";

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-drawer", `
  .at-drawer{width:min(420px,100%);border:1px solid var(--border-subtle);border-radius:var(--radius-md);
    background:var(--bg-page);box-shadow:var(--shadow-md);overflow:hidden;display:grid;
    grid-template-rows:auto 1fr auto;font-family:var(--font-sans)}
  .at-drawer__head{display:flex;align-items:start;justify-content:space-between;gap:10px;
    padding:14px 18px;border-bottom:1px solid var(--border-subtle)}
  .at-drawer__eyebrow{font-size:10px;letter-spacing:0.14em;text-transform:uppercase;color:var(--at-flush-700)}
  .at-drawer__title{font-family:var(--font-display);font-weight:600;font-size:22px;line-height:1.1;margin-top:2px;color:var(--fg-1)}
  .at-drawer__body{padding:18px;display:grid;gap:14px;overflow:auto}
  .at-drawer__foot{padding:12px 18px;border-top:1px solid var(--border-subtle);display:flex;align-items:center;gap:8px}
  .at-drawer__foot-spacer{flex:1}
`);

const CLOSE = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M18 6 6 18M6 6l12 12" />
  </svg>
);

/**
 * Reusable right-side drawer shell: header (eyebrow + title + close), a
 * scrollable body, and an optional footer for actions. It is chrome only — the
 * applied event drawers in ui_kits/app are instances that fill the body and foot.
 */
export function Drawer({ eyebrow, title, onClose, footer, children }) {
  return (
    <div className="at-drawer" role="dialog" aria-label={title}>
      <div className="at-drawer__head">
        <div>
          {eyebrow && <div className="at-drawer__eyebrow">{eyebrow}</div>}
          {title && <div className="at-drawer__title">{title}</div>}
        </div>
        {onClose && <Button variant="ghost" iconOnly icon={CLOSE} aria-label="Close" onClick={onClose} />}
      </div>
      <div className="at-drawer__body">{children}</div>
      {footer && <div className="at-drawer__foot">{footer}</div>}
    </div>
  );
}
