// Shared UI primitives
const { useState, useEffect, useRef, useMemo } = React;

const uiStyles = {
  card: {
    background: "var(--card)",
    border: "1px solid var(--line)",
    borderRadius: "var(--radius)",
  },
};

function Tag({ cat, size = "sm" }) {
  const def = window.DATA.TAGS[cat];
  if (!def) return null;
  const bg = `var(--${def.color}-soft)`;
  const fg = def.color === "gold" ? "#7A5000" :
             def.color === "success" ? "#14504F" :
             def.color === "purple" ? "#14504F" :
             def.color === "warn" ? "#8C4000" :
             "var(--accent-ink)";
  const pad = size === "sm" ? "3px 8px" : "5px 11px";
  const fs = size === "sm" ? 11 : 12;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      background: bg, color: fg, padding: pad, borderRadius: 999,
      fontSize: fs, fontWeight: 500, letterSpacing: -0.01,
      whiteSpace: "nowrap",
    }}>
      <span style={{ width: 5, height: 5, borderRadius: 999, background: `var(--${def.color})` }} />
      {def.label}
    </span>
  );
}

function Btn({ children, variant = "primary", size = "md", icon, onClick, style, ...rest }) {
  const base = {
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7,
    borderRadius: 8, fontWeight: 500, fontSize: 13, letterSpacing: -0.005,
    transition: "background 120ms, border-color 120ms, color 120ms, transform 80ms",
    whiteSpace: "nowrap",
  };
  const sizes = {
    sm: { padding: "6px 10px", fontSize: 12.5 },
    md: { padding: "8px 14px", fontSize: 13 },
    lg: { padding: "11px 18px", fontSize: 14 },
  };
  const variants = {
    primary: { background: "var(--ink)", color: "white" },
    accent: { background: "var(--accent)", color: "white" },
    ghost: { background: "transparent", color: "var(--ink-2)" },
    outline: { background: "var(--card)", color: "var(--ink)", border: "1px solid var(--line-2)" },
    subtle: { background: "var(--bg-2)", color: "var(--ink-2)", border: "1px solid var(--line)" },
  };
  return (
    <button
      onClick={onClick}
      style={{ ...base, ...sizes[size], ...variants[variant], ...style }}
      onMouseDown={e => e.currentTarget.style.transform = "translateY(0.5px)"}
      onMouseUp={e => e.currentTarget.style.transform = ""}
      onMouseLeave={e => e.currentTarget.style.transform = ""}
      {...rest}
    >
      {icon && <span style={{ display: "inline-flex" }}>{icon}</span>}
      {children}
    </button>
  );
}

function Avatar({ initials, size = 32, color = "#2B8C8C" }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: 999,
      background: color, color: "white",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontWeight: 500, fontSize: size * 0.38, letterSpacing: -0.01,
      flexShrink: 0,
    }}>
      {initials}
    </div>
  );
}

function Progress({ value, max = 100, height = 6, color = "var(--ink)", bg = "var(--line)" }) {
  const pct = Math.min(100, (value / max) * 100);
  return (
    <div style={{ width: "100%", height, background: bg, borderRadius: 999, overflow: "hidden" }}>
      <div style={{
        width: `${pct}%`, height: "100%", background: color,
        transition: "width 400ms cubic-bezier(0.2, 0.8, 0.2, 1)",
      }} />
    </div>
  );
}

function Sparkline({ values, color = "var(--accent)", height = 36, width = 120 }) {
  const max = Math.max(...values);
  const min = Math.min(...values);
  const range = max - min || 1;
  const step = width / (values.length - 1);
  const points = values.map((v, i) => `${i * step},${height - ((v - min) / range) * (height - 4) - 2}`).join(" ");
  return (
    <svg width={width} height={height} style={{ display: "block" }}>
      <polyline fill="none" stroke={color} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" points={points} />
      {values.map((v, i) => (
        <circle key={i} cx={i * step} cy={height - ((v - min) / range) * (height - 4) - 2} r={i === values.length - 1 ? 3 : 1.5} fill={color} />
      ))}
    </svg>
  );
}

function Modal({ open, onClose, children, width = 720 }) {
  useEffect(() => {
    if (!open) return;
    const onKey = e => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, background: "rgba(27,61,47,0.55)",
        display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100,
        backdropFilter: "blur(4px)",
        padding: 20, overflow: "auto",
        animation: "fadeIn 160ms ease",
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width: "100%", maxWidth: width,
          background: "var(--card)", borderRadius: "var(--radius-lg)",
          boxShadow: "0 24px 60px -12px rgba(27,61,47,0.25), 0 0 0 1px var(--line)",
          maxHeight: "90vh", overflow: "auto",
          animation: "modalIn 220ms cubic-bezier(0.2, 0.8, 0.2, 1)",
        }}
      >
        {children}
      </div>
    </div>
  );
}

// Animations
const animStyle = document.createElement("style");
animStyle.textContent = `
  @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
  @keyframes modalIn { from { opacity: 0; transform: translateY(8px) scale(0.98) } to { opacity: 1; transform: translateY(0) scale(1) } }
  @keyframes slideUp { from { opacity: 0; transform: translateY(10px) } to { opacity: 1; transform: translateY(0) } }
  @keyframes pulse { 0%, 100% { opacity: 1 } 50% { opacity: 0.5 } }
  .hover-lift { transition: transform 140ms, box-shadow 140ms, border-color 140ms; }
  .hover-lift:hover { transform: translateY(-1px); border-color: var(--line-2) !important; box-shadow: 0 4px 12px -6px rgba(27,61,47,0.25); }
  .nav-item { transition: background 120ms, color 120ms; }
  .nav-item:hover { background: var(--bg-2); }
  .link-reset { color: inherit; text-decoration: none; }
  button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
  input, textarea, select { outline: none; }
`;
document.head.appendChild(animStyle);

window.UI = { Tag, Btn, Avatar, Progress, Sparkline, Modal };
