/* Wood OS — UI primitives + background. JSX module. */
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;
const { motion, AnimatePresence } = window.framerMotion || {};

/* ============================================================
   Icon set (inline SVGs, stroke-based, Lucide-style)
   ============================================================ */
const Icon = ({ name, size = 16, strokeWidth = 1.75, className = "", style }) => {
  const s = size;
  const p = { width: s, height: s, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth, strokeLinecap: "round", strokeLinejoin: "round", className, style };
  switch (name) {
    case "home": return <svg {...p}><path d="M3 11l9-8 9 8" /><path d="M5 10v10h14V10" /></svg>;
    case "inbox": return <svg {...p}><path d="M3 13l3-8h12l3 8" /><path d="M3 13v7h18v-7" /><path d="M3 13h5l1 2h6l1-2h5" /></svg>;
    case "plus": return <svg {...p}><path d="M12 5v14M5 12h14" /></svg>;
    case "plus-circle": return <svg {...p}><circle cx="12" cy="12" r="9" /><path d="M12 8v8M8 12h8" /></svg>;
    case "hammer": return <svg {...p}><path d="M15 12l-8 8-3-3 8-8" /><path d="M17.6 6.5L21 9.9l-3.4 3.4-5-5L16 5l1.6 1.5z" /><path d="M13 7l4 4" /></svg>;
    case "users": return <svg {...p}><circle cx="9" cy="8" r="3.5" /><path d="M3 20c0-3.3 2.7-6 6-6s6 2.7 6 6" /><circle cx="17" cy="7" r="2.5" /><path d="M21 18c0-2.2-1.8-4-4-4" /></svg>;
    case "package": return <svg {...p}><path d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3z" /><path d="M12 12l8-4.5M12 12v9M12 12L4 7.5M8 5.25l8 4.5" /></svg>;
    case "truck": return <svg {...p}><rect x="2" y="7" width="11" height="9" rx="1" /><path d="M13 10h4l3 3v3h-7" /><circle cx="7" cy="18" r="2" /><circle cx="17" cy="18" r="2" /></svg>;
    case "boxes": return <svg {...p}><path d="M3 8.5L12 4l9 4.5v7L12 20l-9-4.5v-7z" /><path d="M12 13L3 8.5M12 13l9-4.5M12 13v7" /></svg>;
    case "clock": return <svg {...p}><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></svg>;
    case "search": return <svg {...p}><circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" /></svg>;
    case "bell": return <svg {...p}><path d="M6 8a6 6 0 0112 0c0 6 3 6 3 9H3c0-3 3-3 3-9z" /><path d="M10 21a2 2 0 004 0" /></svg>;
    case "settings": return <svg {...p}><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.6 1.6 0 00.4 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.6 1.6 0 00-1.8-.4 1.6 1.6 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.6 1.6 0 00-1-1.5 1.6 1.6 0 00-1.8.4l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.6 1.6 0 00.4-1.8 1.6 1.6 0 00-1.5-1H3a2 2 0 110-4h.1a1.6 1.6 0 001.5-1 1.6 1.6 0 00-.4-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.6 1.6 0 001.8.4h0a1.6 1.6 0 001-1.5V3a2 2 0 114 0v.1a1.6 1.6 0 001 1.5 1.6 1.6 0 001.8-.4l.1-.1a2 2 0 112.8 2.8l-.1.1a1.6 1.6 0 00-.4 1.8 1.6 1.6 0 001.5 1H21a2 2 0 110 4h-.1a1.6 1.6 0 00-1.5 1z" /></svg>;
    case "sun": return <svg {...p}><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.93 4.93l1.42 1.42M17.66 17.66l1.42 1.42M2 12h2M20 12h2M4.93 19.07l1.42-1.42M17.66 6.34l1.42-1.42" /></svg>;
    case "moon": return <svg {...p}><path d="M21 13A9 9 0 1111 3a7 7 0 0010 10z" /></svg>;
    case "chevron-right": return <svg {...p}><path d="M9 6l6 6-6 6" /></svg>;
    case "chevron-left": return <svg {...p}><path d="M15 6l-6 6 6 6" /></svg>;
    case "chevron-down": return <svg {...p}><path d="M6 9l6 6 6-6" /></svg>;
    case "arrow-right": return <svg {...p}><path d="M5 12h14M13 5l7 7-7 7" /></svg>;
    case "arrow-up-right": return <svg {...p}><path d="M7 17L17 7M8 7h9v9" /></svg>;
    case "check": return <svg {...p}><path d="M5 12l5 5L20 7" /></svg>;
    case "check-circle": return <svg {...p}><circle cx="12" cy="12" r="9" /><path d="M8 12l3 3 5-6" /></svg>;
    case "x": return <svg {...p}><path d="M6 6l12 12M18 6L6 18" /></svg>;
    case "alert": return <svg {...p}><path d="M12 3l10 18H2L12 3z" /><path d="M12 10v5M12 18v.5" /></svg>;
    case "alert-circle": return <svg {...p}><circle cx="12" cy="12" r="9" /><path d="M12 8v4M12 16v.5" /></svg>;
    case "info": return <svg {...p}><circle cx="12" cy="12" r="9" /><path d="M12 11v5M12 8v.5" /></svg>;
    case "menu": return <svg {...p}><path d="M3 6h18M3 12h18M3 18h18" /></svg>;
    case "panel-left": return <svg {...p}><rect x="3" y="4" width="18" height="16" rx="2" /><path d="M9 4v16" /></svg>;
    case "calendar": return <svg {...p}><rect x="3" y="5" width="18" height="16" rx="2" /><path d="M3 9h18M8 3v4M16 3v4" /></svg>;
    case "filter": return <svg {...p}><path d="M3 5h18l-7 9v6l-4-2v-4L3 5z" /></svg>;
    case "more": return <svg {...p}><circle cx="6" cy="12" r="1.5" /><circle cx="12" cy="12" r="1.5" /><circle cx="18" cy="12" r="1.5" /></svg>;
    case "trend-up": return <svg {...p}><path d="M3 17l6-6 4 4 8-8" /><path d="M21 7h-5M21 7v5" /></svg>;
    case "trend-down": return <svg {...p}><path d="M3 7l6 6 4-4 8 8" /><path d="M21 17h-5M21 17v-5" /></svg>;
    case "activity": return <svg {...p}><path d="M3 12h4l3-8 4 16 3-8h4" /></svg>;
    case "layers": return <svg {...p}><path d="M12 3l9 5-9 5-9-5 9-5z" /><path d="M3 13l9 5 9-5M3 18l9 5 9-5" /></svg>;
    case "shield": return <svg {...p}><path d="M12 3l8 3v6c0 5-3.5 8.5-8 9-4.5-.5-8-4-8-9V6l8-3z" /></svg>;
    case "credit-card": return <svg {...p}><rect x="2" y="5" width="20" height="14" rx="2" /><path d="M2 10h20M6 15h4" /></svg>;
    case "building": return <svg {...p}><rect x="4" y="3" width="16" height="18" rx="1" /><path d="M8 7h2M14 7h2M8 11h2M14 11h2M8 15h2M14 15h2M10 21v-4h4v4" /></svg>;
    case "map-pin": return <svg {...p}><path d="M12 22s-8-7.2-8-13a8 8 0 1116 0c0 5.8-8 13-8 13z" /><circle cx="12" cy="9" r="3" /></svg>;
    case "paperclip": return <svg {...p}><path d="M21 11l-8.5 8.5a5 5 0 11-7-7L14 4a3.5 3.5 0 115 5l-9 9a2 2 0 11-3-3l8-8" /></svg>;
    case "send": return <svg {...p}><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" /></svg>;
    case "logout": return <svg {...p}><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" /></svg>;
    case "command": return <svg {...p}><path d="M18 3a3 3 0 100 6h-3V6a3 3 0 013-3zM6 3a3 3 0 100 6h3V6a3 3 0 00-3-3zM6 21a3 3 0 110-6h3v3a3 3 0 01-3 3zM18 21a3 3 0 110-6h-3v3a3 3 0 003 3zM9 9h6v6H9z" /></svg>;
    case "saw": return <svg {...p}><path d="M3 12l3-1 1-2 2 1 1-2 2 1 1-2 2 1 1-2 2 1 1-2 2 1v6H3z" /><path d="M3 18h18" /></svg>;
    case "ruler": return <svg {...p}><path d="M3 9l12-6 6 12-12 6z" /><path d="M7 11l2-1M10 13l2-1M13 15l2-1M16 17l2-1" /></svg>;
    case "spark": return <svg {...p}><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8L12 3z" /></svg>;
    case "fire": return <svg {...p}><path d="M12 3c2 4 6 5 6 10a6 6 0 01-12 0c0-3 2-4 2-7 2 1 3 1 4-3z" /></svg>;
    case "history": return <svg {...p}><path d="M3 12a9 9 0 109-9 9.7 9.7 0 00-7 3" /><path d="M3 4v5h5M12 7v5l3 2" /></svg>;
    case "trash": return <svg {...p}><path d="M4 7h16M9 7V5a2 2 0 012-2h2a2 2 0 012 2v2M6 7l1 13a2 2 0 002 2h6a2 2 0 002-2l1-13" /></svg>;
    case "edit": return <svg {...p}><path d="M12 20h9M16.5 3.5a2.1 2.1 0 113 3L7 19l-4 1 1-4 12.5-12.5z" /></svg>;
    case "eye": return <svg {...p}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z" /><circle cx="12" cy="12" r="3" /></svg>;
    case "wrench": return <svg {...p}><path d="M14 7a4 4 0 014.5 5.3L21 14.8 19 17l-2.5-2.5A4 4 0 0111 10l-7 7-2-2 7-7a4 4 0 013 0z" /></svg>;
    case "globe": return <svg {...p}><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18" /></svg>;
    case "tag": return <svg {...p}><path d="M3 12l9-9h8v8l-9 9-8-8z" /><circle cx="15" cy="9" r="1.5" /></svg>;
    case "dollar": return <svg {...p}><path d="M12 2v20M16 6H10a3 3 0 000 6h4a3 3 0 010 6H8" /></svg>;
    case "star": return <svg {...p}><path d="M12 2l3 6.5 7 1-5 5 1.3 7-6.3-3.5L5.7 21.5 7 14.5 2 9.5l7-1L12 2z" /></svg>;
    case "trending": return <svg {...p}><path d="M3 17l6-6 4 4 8-8" /></svg>;
    case "git-branch": return <svg {...p}><circle cx="6" cy="3" r="2" /><circle cx="6" cy="18" r="2" /><circle cx="18" cy="6" r="2" /><path d="M6 5v13M18 8a4 4 0 01-4 4H10" /></svg>;
    case "zap": return <svg {...p}><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z" /></svg>;
    case "key": return <svg {...p}><circle cx="8" cy="15" r="4" /><path d="M21 2l-9 9M15 5l3 3M19 7l2 2" /></svg>;
    case "file": return <svg {...p}><path d="M14 3H6a2 2 0 00-2 2v14a2 2 0 002 2h12a2 2 0 002-2V9l-6-6z" /><path d="M14 3v6h6" /></svg>;
    case "file-text": return <svg {...p}><path d="M14 3H6a2 2 0 00-2 2v14a2 2 0 002 2h12a2 2 0 002-2V9l-6-6z" /><path d="M14 3v6h6M8 13h8M8 17h6" /></svg>;
    case "circle": return <svg {...p}><circle cx="12" cy="12" r="9" /></svg>;
    case "dot": return <svg {...p}><circle cx="12" cy="12" r="2" fill="currentColor" /></svg>;
    case "play": return <svg {...p}><path d="M6 4l14 8-14 8V4z" /></svg>;
    case "pause": return <svg {...p}><rect x="6" y="4" width="4" height="16" /><rect x="14" y="4" width="4" height="16" /></svg>;
    case "external": return <svg {...p}><path d="M14 4h6v6M20 4L10 14M19 13v6a1 1 0 01-1 1H5a1 1 0 01-1-1V6a1 1 0 011-1h6" /></svg>;
    case "compass": return <svg {...p}><circle cx="12" cy="12" r="9" /><path d="M15 9l-2 5-5 2 2-5 5-2z" /></svg>;
    case "shield-check": return <svg {...p}><path d="M12 3l8 3v6c0 5-3.5 8.5-8 9-4.5-.5-8-4-8-9V6l8-3z" /><path d="M9 12l2 2 4-4" /></svg>;
    case "log": return <svg {...p}><path d="M4 7h16M4 12h16M4 17h10" /></svg>;
    case "support": return <svg {...p}><circle cx="12" cy="12" r="9" /><path d="M9 9a3 3 0 116 0c0 1.5-1.5 2-2 2.5-.4.4-1 1-1 2M12 17v.5" /></svg>;
    case "flag": return <svg {...p}><path d="M5 22V4M5 4h13l-2 4 2 4H5" /></svg>;
    case "wallet": return <svg {...p}><path d="M3 7c0-1.1.9-2 2-2h14a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" /><path d="M16 12h3M3 10h18" /></svg>;
    case "feature": return <svg {...p}><path d="M12 3l2.5 5.5L20 10l-5.5 1.5L12 17l-2.5-5.5L4 10l5.5-1.5L12 3z" /><path d="M19 17l1 2 2 1-2 1-1 2-1-2-2-1 2-1 1-2z" /></svg>;
    default: return <svg {...p}><circle cx="12" cy="12" r="9" /></svg>;
  }
};

/* ============================================================
   Logo — sheep over fence + WoodOs wordmark
   ============================================================ */
const WoodLogo = ({ size = 32, showText = true, textSize = 15, variant = "auto" }) => {
  // variant: "auto" (themed), "dark-on-light", "light-on-dark"
  // For dark UI, sheep is white/cream; for light UI, sheep is dark navy
  const stroke = "currentColor";
  return (
    <div className="wood-logo" style={{ gap: showText ? 10 : 0, color: "var(--text)" }}>
      <svg width={size} height={size * 0.78} viewBox="0 0 64 50" style={{ flexShrink: 0, overflow: "visible" }}>
        {/* Fence */}
        <g stroke={stroke} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" fill="none">
          {/* posts */}
          <line x1="6" y1="34" x2="6" y2="48" />
          <line x1="20" y1="34" x2="20" y2="48" />
          <line x1="34" y1="34" x2="34" y2="48" />
          {/* rails */}
          <line x1="2" y1="40" x2="38" y2="40" />
          <line x1="2" y1="46" x2="38" y2="46" />
        </g>
        {/* Sheep — leaping */}
        <g stroke={stroke} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" fill="none">
          {/* Body wool — bumpy top */}
          <path d="M22 28 Q24 22 28 22 Q30 18 34 20 Q37 17 41 19 Q45 17 48 21 Q52 20 54 25 Q56 28 54 32 L 52 33 L 28 33 Z" />
          {/* Head */}
          <path d="M52 26 Q57 24 59 28 Q60 31 57 33 L54 32" />
          {/* Eye */}
          <circle cx="56.5" cy="28.5" r="0.6" fill={stroke} stroke="none" />
          {/* Legs — extended in mid-leap */}
          <path d="M30 32 L26 38" />
          <path d="M36 33 L34 38" />
          <path d="M44 33 L46 38" />
          <path d="M50 32 L52 36" />
          {/* Tail */}
          <path d="M22 27 Q19 26 19 24" />
        </g>
      </svg>
      {showText && (
        <span className="wood-logo-text" style={{ fontSize: textSize, lineHeight: 1, fontWeight: 700, letterSpacing: "-0.02em" }}>
          <b style={{ color: "var(--text)", fontWeight: 700 }}>Wood</b><em style={{ color: "var(--amber)", fontStyle: "normal", fontWeight: 700 }}>Os</em>
        </span>
      )}
    </div>
  );
};

/* ============================================================
   Background
   ============================================================ */
const AnimatedBackground = ({ intensity = "high", variant = "default" }) => {
  return (
    <div className="wood-bg-fixed">
      <div className="wood-bg-grad" />
      <div className="wood-bg-orb orb-1" style={{
        width: 520, height: 520, left: "-8%", top: "10%",
        background: "radial-gradient(circle, rgba(16, 185, 129,0.45), rgba(16, 185, 129,0) 70%)"
      }} />
      <div className="wood-bg-orb orb-2" style={{
        width: 420, height: 420, right: "-5%", bottom: "5%",
        background: "radial-gradient(circle, rgba(2, 44, 34,0.6), rgba(2, 44, 34,0) 70%)"
      }} />
      <div className="wood-bg-orb orb-3" style={{
        width: 320, height: 320, left: "40%", top: "55%",
        background: "radial-gradient(circle, rgba(56,189,248,0.18), rgba(56,189,248,0) 70%)"
      }} />
      {variant === "blueprint" && <div className="wood-bg-blueprint" />}
      <div className="wood-bg-grain" />
      <div className="wood-bg-vignette" />
    </div>
  );
};

/* ============================================================
   StatusPill — semantic + with dot
   ============================================================ */
const STATUS_MAP = {
  novo:        { label: "Novo",        cls: "wood-badge-info",    dot: "#38BDF8" },
  pendente:    { label: "Pendente",    cls: "wood-badge-warning", dot: "#F59E0B" },
  analise:     { label: "Em análise",  cls: "wood-badge-info",    dot: "#38BDF8" },
  producao:    { label: "Em produção", cls: "wood-badge-amber",   dot: "#10B981" },
  pronto:      { label: "Pronto",      cls: "wood-badge-success", dot: "#34D399" },
  finalizado: { label: "Finalizado",   cls: "wood-badge-success", dot: "#34D399" },
  entregue:    { label: "Entregue",    cls: "wood-badge-success", dot: "#34D399" },
  atrasado:    { label: "Atrasado",    cls: "wood-badge-error",   dot: "#EF4444" },
  cancelado:   { label: "Cancelado",   cls: "wood-badge-neutral", dot: "#737373" },
  ativo:       { label: "Ativo",       cls: "wood-badge-success", dot: "#34D399" },
  inativo:     { label: "Inativo",     cls: "wood-badge-neutral", dot: "#737373" },
  trial:       { label: "Trial",       cls: "wood-badge-info",    dot: "#38BDF8" },
  suspenso:    { label: "Suspenso",    cls: "wood-badge-error",   dot: "#EF4444" },
};
const StatusPill = ({ status, pulse = false, label, dot = true }) => {
  const s = STATUS_MAP[status] || { label: label || status, cls: "wood-badge-neutral", dot: "#737373" };
  return (
    <span className={`wood-badge ${s.cls}`}>
      {dot && <span className={`wood-dot ${pulse ? "wood-dot-pulse" : ""}`} style={{ background: s.dot, color: s.dot }} />}
      {label || s.label}
    </span>
  );
};

/* ============================================================
   MotionCard wrapper — applies hover lift with framer-motion-ish CSS
   ============================================================ */
const MotionCard = ({ children, onClick, className = "", style, delay = 0, hover = true, ...rest }) => {
  return (
    <div
      onClick={onClick}
      className={`wood-card ${hover ? "wood-card-hover" : ""} ${className}`}
      style={{ animationDelay: `${delay}ms`, ...style }}
      {...rest}
    >
      {children}
    </div>
  );
};

/* ============================================================
   MetricCard — KPI
   ============================================================ */
const MetricCard = ({ icon, label, value, sub, trend, accent, delay = 0 }) => {
  const trendUp = trend && trend > 0;
  const trendDown = trend && trend < 0;
  return (
    <div className="wood-card p-5 slide-up" style={{ animationDelay: `${delay}ms` }}>
      <div className="flex items-center justify-between mb-3">
        <div style={{
          width: 36, height: 36, borderRadius: 10,
          background: accent === "amber" ? "rgba(16, 185, 129,0.16)" :
                      accent === "success" ? "rgba(52,211,153,0.14)" :
                      accent === "warning" ? "rgba(245,158,11,0.16)" :
                      accent === "info" ? "rgba(56,189,248,0.14)" :
                      "rgba(255, 255, 255,0.06)",
          color: accent === "amber" ? "#34D399" :
                 accent === "success" ? "#34D399" :
                 accent === "warning" ? "#F59E0B" :
                 accent === "info" ? "#38BDF8" : "#A3A3A3",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          border: "1px solid var(--wood-border)"
        }}>
          <Icon name={icon} size={18} />
        </div>
        {trend != null && (
          <span className={`wood-badge ${trendUp ? "wood-badge-success" : trendDown ? "wood-badge-error" : "wood-badge-neutral"}`} style={{ padding: "2px 7px" }}>
            <Icon name={trendUp ? "trend-up" : "trend-down"} size={11} />
            {Math.abs(trend)}%
          </span>
        )}
      </div>
      <div className="text-3 text-xs uppercase tracking-widest mb-2" style={{ fontWeight: 500 }}>{label}</div>
      <div className="text-3xl font-semibold tracking-tight" style={{ fontVariantNumeric: "tabular-nums" }}>{value}</div>
      {sub && <div className="text-sm text-3 mt-1">{sub}</div>}
    </div>
  );
};

/* ============================================================
   Animated number
   ============================================================ */
const useCountUp = (target, duration = 900) => {
  const [val, setVal] = useState(0);
  useEffect(() => {
    let start = null;
    let raf;
    const numTarget = Number(target) || 0;
    const tick = (t) => {
      if (!start) start = t;
      const p = Math.min((t - start) / duration, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(numTarget * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration]);
  return val;
};

/* ============================================================
   AnimatedProgress
   ============================================================ */
const AnimatedProgress = ({ value, max = 100, color, height = 6, showLabel = false, label }) => {
  const pct = Math.max(0, Math.min(100, (value / max) * 100));
  return (
    <div>
      {(showLabel || label) && (
        <div className="flex justify-between mb-2 text-xs text-3">
          <span>{label}</span><span style={{ fontVariantNumeric: "tabular-nums" }}>{Math.round(pct)}%</span>
        </div>
      )}
      <div className="wood-progress" style={{ height }}>
        <div className="wood-progress-fill" style={{ width: `${pct}%`, background: color || undefined }} />
      </div>
    </div>
  );
};

/* ============================================================
   EmptyState
   ============================================================ */
const EmptyState = ({ icon = "package", title, description, action }) => (
  <div className="wood-card p-10 text-center">
    <div style={{
      width: 64, height: 64, margin: "0 auto 16px",
      borderRadius: "50%", display: "inline-flex", alignItems: "center", justifyContent: "center",
      background: "rgba(16, 185, 129,0.08)", border: "1px solid var(--wood-border)", color: "var(--amber)"
    }}>
      <Icon name={icon} size={26} strokeWidth={1.5} />
    </div>
    <div className="text-lg font-semibold mb-1">{title}</div>
    <div className="text-3 text-sm mb-4 max-w-md mx-auto text-pretty">{description}</div>
    {action}
  </div>
);

/* ============================================================
   PremiumDrawer
   ============================================================ */
const PremiumDrawer = ({ open, onClose, title, subtitle, children, actions, width = 560 }) => {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <>
      <div className="wood-drawer-backdrop" onClick={onClose} />
      <div className="wood-drawer" style={{ width }}>
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <div>
            {subtitle && <div className="text-3 text-xs uppercase tracking-widest mb-1">{subtitle}</div>}
            <div className="text-lg font-semibold tracking-tight">{title}</div>
          </div>
          <button className="wood-btn wood-btn-ghost wood-btn-icon" onClick={onClose} aria-label="Fechar">
            <Icon name="x" size={18} />
          </button>
        </div>
        <div className="flex-1 overflow-y-auto px-6 py-5">{children}</div>
        {actions && <div className="px-6 py-4 border-t flex justify-end gap-2">{actions}</div>}
      </div>
    </>
  );
};

/* ============================================================
   Modal (confirm)
   ============================================================ */
const ConfirmModal = ({ open, onClose, onConfirm, title, description, confirmLabel = "Confirmar", cancelLabel = "Cancelar", danger = false }) => {
  if (!open) return null;
  return (
    <div className="wood-modal-backdrop" onClick={onClose}>
      <div className="wood-modal" onClick={e => e.stopPropagation()}>
        <div className="px-6 py-5">
          <div className="flex items-start gap-4 mb-2">
            <div style={{
              width: 40, height: 40, borderRadius: 12,
              background: danger ? "rgba(239,68,68,0.14)" : "rgba(16, 185, 129,0.14)",
              color: danger ? "#EF4444" : "#34D399",
              display: "inline-flex", alignItems: "center", justifyContent: "center"
            }}>
              <Icon name={danger ? "alert" : "info"} size={20} />
            </div>
            <div className="flex-1">
              <div className="text-lg font-semibold mb-1">{title}</div>
              <div className="text-3 text-sm text-pretty">{description}</div>
            </div>
          </div>
        </div>
        <div className="px-6 py-4 flex justify-end gap-2" style={{ background: "rgba(0,0,0,0.2)", borderTop: "1px solid var(--wood-border)" }}>
          <button className="wood-btn wood-btn-secondary" onClick={onClose}>{cancelLabel}</button>
          <button
            className="wood-btn wood-btn-primary"
            style={danger ? { background: "linear-gradient(180deg,#F87171,#EF4444 50%,#B91C1C)", color: "#fff" } : undefined}
            onClick={() => { onConfirm(); onClose(); }}
          >{confirmLabel}</button>
        </div>
      </div>
    </div>
  );
};

/* ============================================================
   CommandSearch (palette)
   ============================================================ */
const CommandSearch = ({ open, onClose, onNavigate }) => {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);
  useEffect(() => { if (open) setTimeout(() => inputRef.current?.focus(), 30); }, [open]);
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  if (!open) return null;

  const items = [
    { icon: "home", label: "Painel Geral", group: "Navegar", route: "dashboard" },
    { icon: "inbox", label: "Solicitações", group: "Navegar", route: "requests" },
    { icon: "plus-circle", label: "Nova Solicitação", group: "Ação rápida", route: "new-request", primary: true },
    { icon: "hammer", label: "Obras", group: "Navegar", route: "projects" },
    { icon: "users", label: "Equipes", group: "Navegar", route: "teams" },
    { icon: "package", label: "Almoxarifado", group: "Navegar", route: "inventory" },
    { icon: "truck", label: "Veículos", group: "Navegar", route: "vehicles" },
    { icon: "boxes", label: "Carga e Descarga", group: "Navegar", route: "logistics" },
    { icon: "history", label: "Histórico", group: "Navegar", route: "history" },
    { icon: "shield", label: "Painel Admin SaaS", group: "Sistema", route: "admin" },
    { icon: "settings", label: "Configurações", group: "Sistema", route: "settings" },
    { icon: "sun", label: "Alternar tema", group: "Preferências" },
  ];
  const filtered = q ? items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())) : items;
  const groups = {};
  filtered.forEach(i => { groups[i.group] = groups[i.group] || []; groups[i.group].push(i); });

  return (
    <div className="wood-modal-backdrop" onClick={onClose} style={{ alignItems: "flex-start", paddingTop: "12vh" }}>
      <div className="wood-modal" style={{ width: 640, maxWidth: "100%" }} onClick={e => e.stopPropagation()}>
        <div className="flex items-center gap-3 px-5 py-4 border-b">
          <Icon name="search" size={18} className="text-3" />
          <input
            ref={inputRef}
            className="flex-1"
            style={{ background: "transparent", border: "none", outline: "none", fontSize: 15, color: "var(--text)" }}
            placeholder="Buscar solicitações, obras, equipes ou veículos…"
            value={q}
            onChange={e => setQ(e.target.value)}
          />
          <span className="wood-kbd">esc</span>
        </div>
        <div className="overflow-y-auto" style={{ maxHeight: 420 }}>
          {Object.entries(groups).map(([group, items]) => (
            <div key={group} className="py-2">
              <div className="px-5 pt-2 pb-1 text-xs uppercase tracking-widest text-4" style={{ fontWeight: 600 }}>{group}</div>
              {items.map(i => (
                <button
                  key={i.label}
                  className="flex items-center gap-3 w-full px-5 py-2.5"
                  style={{ background: "transparent", border: "none", color: "var(--text-2)", textAlign: "left", cursor: "pointer" }}
                  onClick={() => { if (i.route && onNavigate) onNavigate(i.route); onClose(); }}
                  onMouseEnter={e => e.currentTarget.style.background = "rgba(16, 185, 129,0.06)"}
                  onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                >
                  <span style={{
                    width: 28, height: 28, borderRadius: 7,
                    background: i.primary ? "rgba(16, 185, 129,0.2)" : "rgba(255, 255, 255,0.04)",
                    border: "1px solid var(--wood-border)",
                    color: i.primary ? "var(--amber-bright)" : "var(--text-3)",
                    display: "inline-flex", alignItems: "center", justifyContent: "center"
                  }}>
                    <Icon name={i.icon} size={14} />
                  </span>
                  <span className="flex-1 text-sm">{i.label}</span>
                  <Icon name="arrow-right" size={12} className="text-4" />
                </button>
              ))}
            </div>
          ))}
        </div>
        <div className="px-5 py-3 flex items-center gap-4 text-xs text-4" style={{ borderTop: "1px solid var(--wood-border)" }}>
          <span className="flex items-center gap-1"><span className="wood-kbd">↑</span><span className="wood-kbd">↓</span> navegar</span>
          <span className="flex items-center gap-1"><span className="wood-kbd">↵</span> selecionar</span>
          <span className="flex items-center gap-1"><span className="wood-kbd">⌘</span><span className="wood-kbd">K</span> abrir</span>
        </div>
      </div>
    </div>
  );
};

/* ============================================================
   Avatar
   ============================================================ */
const Avatar = ({ name = "?", size = 32, color }) => {
  const initials = name.split(" ").filter(Boolean).slice(0, 2).map(s => s[0]).join("").toUpperCase();
  // hash to pick a gradient
  const hash = [...name].reduce((a, c) => a + c.charCodeAt(0), 0);
  const grads = [
    "linear-gradient(135deg, #065F46, #011712)",
    "linear-gradient(135deg, #047857, #022C22)",
    "linear-gradient(135deg, #6B5C46, #2A2017)",
    "linear-gradient(135deg, #5B6A8C, #2A3550)",
    "linear-gradient(135deg, #4A6B5C, #1F3326)",
    "linear-gradient(135deg, #8C4A5B, #4A1F2E)",
  ];
  return (
    <span
      className="wood-avatar"
      style={{
        width: size, height: size, fontSize: size * 0.38,
        background: color || grads[hash % grads.length]
      }}
    >{initials || "?"}</span>
  );
};

/* ============================================================
   Toolbar Pills (filter chips)
   ============================================================ */
const FilterChip = ({ active, children, onClick, count }) => (
  <button
    onClick={onClick}
    className="wood-btn"
    style={{
      background: active ? "rgba(16, 185, 129,0.16)" : "var(--wood-surface-2)",
      border: `1px solid ${active ? "rgba(16, 185, 129,0.45)" : "var(--wood-border)"}`,
      color: active ? "var(--cream)" : "var(--text-2)",
      fontWeight: active ? 600 : 500,
      padding: "6px 12px",
      borderRadius: "999px",
      fontSize: 12.5
    }}
  >
    {children}
    {count != null && (
      <span style={{
        fontSize: 10.5, padding: "1px 6px", borderRadius: 999,
        background: active ? "rgba(0,0,0,0.25)" : "rgba(255,255,255,0.05)",
        marginLeft: 2
      }}>{count}</span>
    )}
  </button>
);

/* expose */
Object.assign(window, {
  Icon, WoodLogo, AnimatedBackground, StatusPill, MotionCard, MetricCard,
  AnimatedProgress, EmptyState, PremiumDrawer, ConfirmModal, CommandSearch,
  Avatar, FilterChip, useCountUp, STATUS_MAP
});
