// Shared UI primitives — glass surfaces, charts, icons, badges
const { useState, useEffect, useMemo, useRef } = React;
const A = window.MOCK.ABENDI;

// ───────────── ICONS (stroke-only, no decorative SVGs) ─────────────
const Icon = ({ name, size = 18, stroke = "currentColor" }) => {
  const paths = {
    dashboard: (
      <>
        <rect x="3" y="3" width="7" height="9" rx="1.2" />
        <rect x="14" y="3" width="7" height="5" rx="1.2" />
        <rect x="14" y="12" width="7" height="9" rx="1.2" />
        <rect x="3" y="16" width="7" height="5" rx="1.2" />
      </>
    ),
    users: (
      <>
        <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="9" r="2.5" />
        <path d="M15 20c0-2.5 1.5-4.5 4-4.5" />
      </>
    ),
    teacher: (
      <>
        <path d="M3 7l9-4 9 4-9 4-9-4z" />
        <path d="M7 9.5V14c0 1.5 2.5 3 5 3s5-1.5 5-3V9.5" />
        <path d="M21 7v6" />
      </>
    ),
    classes: (
      <>
        <rect x="3" y="4" width="18" height="16" rx="1.5" />
        <path d="M3 9h18" />
        <path d="M8 4v5" />
        <path d="M16 4v5" />
      </>
    ),
    chart: (
      <>
        <path d="M4 20V10" />
        <path d="M10 20V4" />
        <path d="M16 20v-7" />
        <path d="M22 20H2" />
      </>
    ),
    session: (
      <>
        <circle cx="12" cy="12" r="9" />
        <path d="M12 7v5l3 2" />
      </>
    ),
    settings: (
      <>
        <circle cx="12" cy="12" r="3" />
        <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
      </>
    ),
    logout: (
      <>
        <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
        <path d="M16 17l5-5-5-5" />
        <path d="M21 12H9" />
      </>
    ),
    plus: (
      <>
        <path d="M12 5v14M5 12h14" />
      </>
    ),
    search: (
      <>
        <circle cx="11" cy="11" r="7" />
        <path d="m21 21-4.3-4.3" />
      </>
    ),
    upload: (
      <>
        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
        <path d="M17 8l-5-5-5 5" />
        <path d="M12 3v12" />
      </>
    ),
    download: (
      <>
        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
        <path d="M7 10l5 5 5-5" />
        <path d="M12 15V3" />
      </>
    ),
    filter: (
      <>
        <path d="M22 3H2l8 9.5V19l4 2v-8.5L22 3z" />
      </>
    ),
    chevron: (
      <>
        <path d="m9 18 6-6-6-6" />
      </>
    ),
    chevronDown: (
      <>
        <path d="m6 9 6 6 6-6" />
      </>
    ),
    check: (
      <>
        <path d="M20 6 9 17l-5-5" />
      </>
    ),
    x: (
      <>
        <path d="M18 6 6 18M6 6l12 12" />
      </>
    ),
    calendar: (
      <>
        <rect x="3" y="4" width="18" height="18" rx="1.5" />
        <path d="M16 2v4M8 2v4M3 10h18" />
      </>
    ),
    clock: (
      <>
        <circle cx="12" cy="12" r="9" />
        <path d="M12 7v5l3 2" />
      </>
    ),
    eye: (
      <>
        <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" />
      </>
    ),
    edit: (
      <>
        <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" />
      </>
    ),
    trash: (
      <>
        <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
      </>
    ),
    mail: (
      <>
        <rect x="2" y="4" width="20" height="16" rx="2" />
        <path d="m22 7-10 6L2 7" />
      </>
    ),
    lock: (
      <>
        <rect x="3" y="11" width="18" height="11" rx="2" />
        <path d="M7 11V7a5 5 0 0 1 10 0v4" />
      </>
    ),
    user: (
      <>
        <circle cx="12" cy="8" r="4" />
        <path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8" />
      </>
    ),
    alert: (
      <>
        <path d="M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
        <path d="M12 9v4M12 17h.01" />
      </>
    ),
    arrow: (
      <>
        <path d="M5 12h14M12 5l7 7-7 7" />
      </>
    ),
    arrowLeft: (
      <>
        <path d="M19 12H5M12 19l-7-7 7-7" />
      </>
    ),
    target: (
      <>
        <circle cx="12" cy="12" r="9" />
        <circle cx="12" cy="12" r="5" />
        <circle cx="12" cy="12" r="1.5" />
      </>
    ),
    layers: (
      <>
        <path d="m12 2 10 6-10 6L2 8l10-6z" />
        <path d="m2 17 10 6 10-6" />
        <path d="m2 12 10 6 10-6" />
      </>
    ),
    grid: (
      <>
        <rect x="3" y="3" width="7" height="7" />
        <rect x="14" y="3" width="7" height="7" />
        <rect x="14" y="14" width="7" height="7" />
        <rect x="3" y="14" width="7" height="7" />
      </>
    ),
    menu: (
      <>
        <path d="M3 6h18M3 12h18M3 18h18" />
      </>
    ),
    info: (
      <>
        <circle cx="12" cy="12" r="9" />
        <path d="M12 16v-4M12 8h.01" />
      </>
    ),
    sparkle: (
      <>
        <path d="M12 2v6m0 8v6M2 12h6m8 0h6M5.5 5.5l4 4m5 5 4 4M18.5 5.5l-4 4m-5 5-4 4" />
      </>
    ),
  };
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke={stroke}
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      style={{ flexShrink: 0 }}
    >
      {paths[name] || null}
    </svg>
  );
};

// ───────────── ABENDI LOGO ─────────────
// Always renders in official brand colors (cinza/verde/dourado).
// For dark backgrounds, use AbendiMarkOnDark which is a card wrapper.
const AbendiMark = ({ size = 28 }) => (
  <svg
    width={size}
    height={size * (135 / 135)}
    viewBox="0 0 135.46667 135.46667"
    style={{ flexShrink: 0 }}
  >
    <path
      d="m 52.902764,27.27278 c 1.147309,0.819507 14.493062,26.182603 14.493062,26.182603 L 34.042321,111.77898 6.7477717,111.73098 C 5.6412346,111.35279 5.0614288,110.9062 5.1712495,109.39374 Z"
      fill="#c4c4c4"
    />
    <path
      d="m 116.48619,86.907886 -68.203457,-1e-6 -14.23893,24.872035 92.850127,0.20488 c 2.31395,-0.0906 3.57779,-0.92626 2.70437,-3.27803 z"
      fill="#004e2d"
    />
    <path
      d="m 52.90053,27.271882 32.723049,59.62953 30.869411,0.01534 L 84.083362,30.698479 c 0,0 -2.81389,-3.426602 -3.74124,-3.426602 -1.04373,-1e-6 -27.441592,0 -27.441592,0 z"
      fill="#dda003"
    />
  </svg>
);

// Wordmark: solid-colored brand mark + "Abendi" text + "Inspeção Industrial" tagline.
// For use on light backgrounds (e.g. inside a white card).
const AbendiWordmark = ({ height = 26 }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
    <AbendiMark size={height * 1.05} />
    <span
      style={{
        fontFamily: '"Plus Jakarta Sans", sans-serif',
        fontWeight: 700,
        fontSize: height * 0.85,
        color: A.green,
        letterSpacing: "-0.02em",
      }}
    >
      Abendi
    </span>
    <span
      style={{
        fontFamily: '"Plus Jakarta Sans", sans-serif',
        fontWeight: 400,
        fontSize: height * 0.55,
        color: A.inkSoft,
        marginLeft: 4,
        paddingLeft: 10,
        borderLeft: "1px solid rgba(0,0,0,0.12)",
        lineHeight: 1.1,
      }}
    >
      Inspeção
      <br />
      Industrial
    </span>
  </div>
);

// Brand card — white tile holding the colored Abendi logo. Designed to sit
// on top of dark surfaces (e.g. the dark green sidebar) so the official
// brand colors stay accurate.
const AbendiBrandCard = ({ height = 22, padding = "10px 14px" }) => (
  <div
    style={{
      background: "#ffffff",
      borderRadius: 10,
      padding,
      display: "inline-flex",
      alignItems: "center",
      boxShadow: "0 1px 2px rgba(0,0,0,0.08)",
    }}
  >
    <AbendiWordmark height={height} />
  </div>
);

// ───────────── RYSAX CREDIT ─────────────
// Discreet developer credit — small logo + "Rysax" text, wrapped in a link
// to the company website. Used in sidebar/auth footer.
//   tone="color" — full brand colors (light backgrounds)
//   tone="mono"  — translucent white (dark backgrounds, like the sidebar)
const RysaxMark = ({ size = 16, tone = "color" }) => {
  const orange = tone === "mono" ? "rgba(255,255,255,0.85)" : "#ffb13d";
  const blue   = tone === "mono" ? "rgba(255,255,255,0.85)" : "#4596cd";
  const textColor = tone === "mono" ? "rgba(255,255,255,0.85)" : "#4596cd";
  return (
    <a
      href="https://rysax.com/"
      target="_blank"
      rel="noopener noreferrer"
      title="Rysax · rysax.com"
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        textDecoration: "none",
        color: textColor,
        transition: "opacity 150ms",
      }}
      onMouseEnter={(e) => (e.currentTarget.style.opacity = "0.7")}
      onMouseLeave={(e) => (e.currentTarget.style.opacity = "1")}
    >
      <svg width={size * (240/170)} height={size} viewBox="40 240 220 130" style={{ flexShrink: 0 }}>
        <path
          d="M204.38,263.45l27.62,14.47c3.87,1.86,3.86,7.37-.02,9.22l-75.39,35.81c-3.87,1.84-8.37,1.84-12.24,0l-75.29-35.91c-3.86-1.84-3.88-7.33-.04-9.2l28.44-14.35c2.86-1.39,6.2-1.38,9.04.04l10.45,5.21c1.78.89,1.78,3.42.01,4.31l-13.33,7.08c-1.46.74-1.44,2.84.04,3.54l40.63,19.43c3.87,1.85,8.37,1.86,12.25.02l40.68-19.3c1.53-.73,1.5-2.91-.05-3.59l-11.36-6.43c-1.78-.78-1.95-3.24-.29-4.26l9.05-5.58c2.96-1.82,6.65-2.02,9.78-.52Z"
          fill={blue}
        />
        <path
          d="M162.73,242.79l21.09,10.62c2.34,1.18,2.47,4.48.23,5.84l-6.35,3.85c-3.95,2.39-8.85,2.59-12.97.51l-2.44-1.23c-7.42-3.74-16.14-3.88-23.68-.39l-3.5,1.62c-3.62,1.68-7.8,1.65-11.4-.07l-7.55-3.61c-2.5-1.2-2.54-4.75-.06-6l22.13-11.15c7.71-3.88,16.8-3.88,24.5,0Z"
          fill={orange}
        />
        <path
          d="M209.8,313.17l22.96,11c3.53,1.69,3.52,6.71-.01,8.39l-76.49,36.33c-3.73,1.77-8.06,1.77-11.78,0l-76.16-36.32c-3.55-1.69-3.52-6.75.04-8.41l23.74-11.01c3.5-1.62,7.55-1.57,11.01.15l9.3,4.64c1.79.9,1.74,3.47-.09,4.3l-8.27,3.72c-1.61.72-1.64,3-.04,3.77l42.35,20.26c2.52,1.2,5.45,1.21,7.97.01l42.77-20.28c1.58-.75,1.58-3.01,0-3.75l-8.11-3.83c-1.82-.86-1.82-3.44,0-4.3l9.94-4.68c3.45-1.62,7.45-1.61,10.89.04Z"
          fill={blue}
        />
      </svg>
      <span
        style={{
          fontFamily: '"Plus Jakarta Sans", sans-serif',
          fontWeight: 700,
          fontSize: size * 0.85,
          letterSpacing: "-0.01em",
        }}
      >
        Rysax
      </span>
    </a>
  );
};

// ───────────── GLASS SURFACE ─────────────
const Glass = ({
  children,
  style,
  hover = false,
  padding = 20,
  dark = false,
  ...rest
}) => (
  <div
    style={{
      background: dark ? A.glassDark : A.glass,
      // Backdrop blur is only useful when the card is translucent.
      // Light theme uses a flat solid card — no blur needed.
      backdropFilter: dark ? "blur(22px) saturate(140%)" : undefined,
      WebkitBackdropFilter: dark ? "blur(22px) saturate(140%)" : undefined,
      border: `1px solid ${dark ? "rgba(255,255,255,0.18)" : A.glassBorder}`,
      borderRadius: 14,
      padding,
      boxShadow: dark
        ? "0 8px 32px rgba(0,40,20,0.18), inset 0 1px 0 rgba(255,255,255,0.5)"
        : "0 1px 2px rgba(0,40,20,0.04), 0 4px 14px rgba(0,40,20,0.04)",
      transition: "transform 200ms ease, box-shadow 200ms ease",
      color: dark ? "#fff" : A.ink,
      ...style,
    }}
    {...rest}
  >
    {children}
  </div>
);

// ───────────── BUTTON ─────────────
const Button = ({
  children,
  variant = "primary",
  size = "md",
  icon,
  iconRight,
  onClick,
  disabled,
  type = "button",
  style,
  fullWidth,
}) => {
  const sizes = {
    sm: { padding: "6px 12px", fontSize: 13, gap: 6, iconSize: 14 },
    md: { padding: "9px 16px", fontSize: 14, gap: 8, iconSize: 16 },
    lg: { padding: "12px 22px", fontSize: 15, gap: 8, iconSize: 18 },
  };
  const variants = {
    primary: { bg: A.green, fg: "#fff", border: A.green, hoverBg: A.greenDark },
    gold: { bg: A.gold, fg: "#1a1500", border: A.gold, hoverBg: A.goldLight },
    ghost: {
      bg: "transparent",
      fg: A.green,
      border: "rgba(0,78,45,0.25)",
      hoverBg: "rgba(0,78,45,0.08)",
    },
    glass: {
      bg: "rgba(255,255,255,0.6)",
      fg: A.green,
      border: "rgba(255,255,255,0.7)",
      hoverBg: "rgba(255,255,255,0.85)",
    },
    danger: {
      bg: "rgba(184,51,31,0.1)",
      fg: A.danger,
      border: "rgba(184,51,31,0.3)",
      hoverBg: "rgba(184,51,31,0.18)",
    },
  };
  const s = sizes[size];
  const v = variants[variant];
  const [hover, setHover] = useState(false);
  return (
    <button
      type={type}
      disabled={disabled}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        gap: s.gap,
        padding: s.padding,
        fontSize: s.fontSize,
        fontWeight: 600,
        background: hover && !disabled ? v.hoverBg : v.bg,
        color: v.fg,
        border: `1px solid ${v.border}`,
        borderRadius: 10,
        cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.5 : 1,
        fontFamily: "inherit",
        letterSpacing: "-0.005em",
        transition: "all 150ms ease",
        width: fullWidth ? "100%" : "auto",
        whiteSpace: "nowrap",
        ...style,
      }}
    >
      {icon && <Icon name={icon} size={s.iconSize} />}
      {children}
      {iconRight && <Icon name={iconRight} size={s.iconSize} />}
    </button>
  );
};

// ───────────── BADGE / PILL ─────────────
const Badge = ({ children, tone = "neutral", size = "md" }) => {
  const tones = {
    neutral: { bg: "rgba(0,0,0,0.06)", fg: A.inkSoft },
    green: { bg: "rgba(47,122,61,0.14)", fg: A.ok },
    gold: { bg: "rgba(221,160,3,0.18)", fg: "#7a5a00" },
    red: { bg: "rgba(184,51,31,0.12)", fg: A.danger },
    blue: { bg: "rgba(28,76,140,0.12)", fg: "#1c4c8c" },
    primary: { bg: "rgba(0,78,45,0.12)", fg: A.green },
  };
  const t = tones[tone];
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 5,
        padding: size === "sm" ? "2px 8px" : "3px 10px",
        fontSize: size === "sm" ? 11 : 12,
        fontWeight: 600,
        background: t.bg,
        color: t.fg,
        borderRadius: 999,
        letterSpacing: "0.01em",
      }}
    >
      {children}
    </span>
  );
};

// ───────────── INPUT ─────────────
// Auto-generates an id via React.useId() and links the <label> via htmlFor.
// Consumers can pass an explicit `id`, `name`, or `autoComplete` to override.
// If `name` isn't provided, derives one from the label so browser autofill works.
const Input = ({
  icon,
  label,
  hint,
  error,
  type = "text",
  value,
  onChange,
  placeholder,
  style,
  id: idProp,
  name,
  autoComplete,
  ...rest
}) => {
  const generatedId = React.useId();
  const id = idProp || generatedId;
  // Derive a name from the label if none given, so password managers/autofill behave.
  const derivedName = name || (typeof label === "string"
    ? label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || undefined
    : undefined);
  return (
  <div style={{ display: "flex", flexDirection: "column", gap: 6, ...style }}>
    {label && (
      <label
        htmlFor={id}
        style={{
          fontSize: 12,
          fontWeight: 600,
          color: A.inkSoft,
          letterSpacing: "0.02em",
          textTransform: "uppercase",
        }}
      >
        {label}
      </label>
    )}
    <div style={{ position: "relative" }}>
      {icon && (
        <span
          style={{
            position: "absolute",
            left: 12,
            top: "50%",
            transform: "translateY(-50%)",
            color: A.inkMute,
          }}
        >
          <Icon name={icon} size={16} />
        </span>
      )}
      <input
        id={id}
        name={derivedName}
        autoComplete={autoComplete}
        type={type}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        style={{
          width: "100%",
          padding: icon ? "10px 12px 10px 38px" : "10px 12px",
          fontSize: 14,
          fontFamily: "inherit",
          background: "#ffffff",
          border: `1px solid ${error ? A.danger : "rgba(0,0,0,0.14)"}`,
          borderRadius: 10,
          color: A.ink,
          outline: "none",
          transition: "border 150ms",
          boxSizing: "border-box",
        }}
        onFocus={(e) => (e.target.style.borderColor = A.green)}
        onBlur={(e) =>
          (e.target.style.borderColor = error ? A.danger : "rgba(0,0,0,0.12)")
        }
        {...rest}
      />
    </div>
    {hint && (
      <span style={{ fontSize: 12, color: error ? A.danger : A.inkMute }}>
        {hint}
      </span>
    )}
  </div>
  );
};

// ───────────── SEGMENTED ─────────────
// Segmented control. `tone` controls colors:
//   "light" (default): subtle on light glass cards (e.g. range selector inside an overview card).
//   "dark":            white-on-translucent for use on the dark page background (tab strips).
const Segmented = ({ value, onChange, options, tone = "light" }) => {
  const palette = tone === "dark"
    ? {
        track: "rgba(255,255,255,0.12)",
        activeBg: "#fff",
        activeFg: A.green,
        inactiveFg: "rgba(255,255,255,0.85)",
      }
    : {
        track: "rgba(0,0,0,0.05)",
        activeBg: "#fff",
        activeFg: A.green,
        inactiveFg: A.inkSoft,
      };
  return (
  <div
    style={{
      display: "inline-flex",
      background: palette.track,
      borderRadius: 10,
      padding: 3,
      gap: 2,
    }}
  >
    {options.map((o) => (
      <button
        key={o.value}
        onClick={() => onChange(o.value)}
        style={{
          padding: "6px 12px",
          fontSize: 13,
          fontWeight: 600,
          border: "none",
          cursor: "pointer",
          background: value === o.value ? palette.activeBg : "transparent",
          color: value === o.value ? palette.activeFg : palette.inactiveFg,
          borderRadius: 8,
          fontFamily: "inherit",
          boxShadow: value === o.value ? "0 1px 3px rgba(0,0,0,0.08)" : "none",
          transition: "all 120ms",
        }}
      >
        {o.label}
      </button>
    ))}
  </div>
  );
};

// ───────────── METRIC TILE ─────────────
const Metric = ({ label, value, delta, sub, accent = A.green, icon }) => (
  <div style={{ padding: "4px 0" }}>
    <div
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        marginBottom: 6,
      }}
    >
      <span
        style={{
          fontSize: 11,
          fontWeight: 600,
          color: A.inkSoft,
          letterSpacing: "0.04em",
          textTransform: "uppercase",
        }}
      >
        {label}
      </span>
      {icon && (
        <span style={{ color: accent, opacity: 0.7 }}>
          <Icon name={icon} size={14} />
        </span>
      )}
    </div>
    <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
      <span
        style={{
          fontSize: 30,
          fontWeight: 700,
          color: A.ink,
          fontFamily: '"Plus Jakarta Sans", sans-serif',
          letterSpacing: "-0.02em",
          lineHeight: 1,
        }}
      >
        {value}
      </span>
      {delta != null && (
        <span
          style={{
            fontSize: 12,
            fontWeight: 600,
            color: delta >= 0 ? A.ok : A.danger,
          }}
        >
          {delta >= 0 ? "↑" : "↓"} {Math.abs(delta)}
          {typeof delta === "number" ? "%" : ""}
        </span>
      )}
    </div>
    {sub && (
      <div style={{ fontSize: 12, color: A.inkMute, marginTop: 4 }}>{sub}</div>
    )}
  </div>
);

// ───────────── BAR CHART (simple) ─────────────
const BarChart = ({ data, height = 140, accent = A.green }) => {
  const max = Math.max(...data.map((d) => d.value));
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 6, height }}>
      {data.map((d, i) => {
        const h = (d.value / max) * (height - 24);
        return (
          <div
            key={i}
            style={{
              flex: 1,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              gap: 6,
              minWidth: 0,
            }}
          >
            <div
              style={{
                flex: 1,
                display: "flex",
                flexDirection: "column",
                justifyContent: "flex-end",
                width: "100%",
              }}
            >
              <div
                style={{
                  height: h,
                  background: `linear-gradient(180deg, ${accent}ee, ${accent}99)`,
                  borderRadius: "6px 6px 2px 2px",
                  position: "relative",
                }}
              >
                <span
                  style={{
                    position: "absolute",
                    top: -18,
                    left: "50%",
                    transform: "translateX(-50%)",
                    fontSize: 10,
                    fontWeight: 600,
                    color: A.inkSoft,
                  }}
                >
                  {d.value}
                </span>
              </div>
            </div>
            <span
              style={{
                fontSize: 10,
                color: A.inkMute,
                fontWeight: 500,
                textAlign: "center",
                whiteSpace: "nowrap",
                overflow: "hidden",
                textOverflow: "ellipsis",
                width: "100%",
              }}
            >
              {d.label}
            </span>
          </div>
        );
      })}
    </div>
  );
};

// ───────────── STACKED BAR (for defects breakdown) ─────────────
const StackedBar = ({ rows, height = 22, showLegend = true }) => {
  const colors = { found: A.ok, misId: A.warn, missed: A.danger };
  const labels = {
    found: "Identificados",
    misId: "Mal identificados",
    missed: "Não identificados",
  };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {rows.map((r, i) => {
        const total = r.total || r.found + r.misId + r.missed;
        return (
          <div
            key={i}
            style={{ display: "flex", flexDirection: "column", gap: 4 }}
          >
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "baseline",
              }}
            >
              <span style={{ fontSize: 13, fontWeight: 500, color: A.ink }}>
                {r.type}
              </span>
              <span
                style={{
                  fontSize: 12,
                  color: A.inkMute,
                  fontVariantNumeric: "tabular-nums",
                }}
              >
                <b style={{ color: A.ok }}>{r.found}</b> / {total}
                {r.misId > 0 && (
                  <>
                    {" "}
                    · <b style={{ color: A.warn }}>{r.misId} mal id.</b>
                  </>
                )}
                {r.missed > 0 && (
                  <>
                    {" "}
                    · <b style={{ color: A.danger }}>{r.missed} perdidos</b>
                  </>
                )}
              </span>
            </div>
            <div
              style={{
                display: "flex",
                height,
                borderRadius: 6,
                overflow: "hidden",
                background: "rgba(0,0,0,0.05)",
              }}
            >
              <div style={{ flex: r.found, background: colors.found }} />
              <div style={{ flex: r.misId, background: colors.misId }} />
              <div style={{ flex: r.missed, background: colors.missed }} />
            </div>
          </div>
        );
      })}
      {showLegend && (
        <div
          style={{
            display: "flex",
            gap: 14,
            marginTop: 4,
            fontSize: 11,
            color: A.inkSoft,
          }}
        >
          {Object.entries(labels).map(([k, l]) => (
            <span
              key={k}
              style={{ display: "inline-flex", alignItems: "center", gap: 6 }}
            >
              <span
                style={{
                  width: 10,
                  height: 10,
                  borderRadius: 3,
                  background: colors[k],
                }}
              />
              {l}
            </span>
          ))}
        </div>
      )}
    </div>
  );
};

// ───────────── RADIAL GAUGE ─────────────
const Radial = ({
  value,
  max = 100,
  size = 110,
  label,
  sub,
  color = A.green,
}) => {
  const r = size / 2 - 8;
  const c = 2 * Math.PI * r;
  const pct = Math.min(value / max, 1);
  return (
    <div
      style={{
        position: "relative",
        width: size,
        height: size,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
        <circle
          cx={size / 2}
          cy={size / 2}
          r={r}
          fill="none"
          stroke="rgba(0,0,0,0.07)"
          strokeWidth={8}
        />
        <circle
          cx={size / 2}
          cy={size / 2}
          r={r}
          fill="none"
          stroke={color}
          strokeWidth={8}
          strokeDasharray={c}
          strokeDashoffset={c * (1 - pct)}
          strokeLinecap="round"
        />
      </svg>
      <div style={{ position: "absolute", textAlign: "center" }}>
        <div
          style={{
            fontSize: size * 0.28,
            fontWeight: 700,
            color: A.ink,
            fontFamily: '"Plus Jakarta Sans", sans-serif',
            lineHeight: 1,
            letterSpacing: "-0.02em",
          }}
        >
          {value}
        </div>
        {sub && (
          <div style={{ fontSize: 10, color: A.inkMute, marginTop: 2 }}>
            {sub}
          </div>
        )}
      </div>
    </div>
  );
};

// ───────────── LINE CHART (sparkline / score progression) ─────────────
const LineChart = ({
  data,
  height = 120,
  accent = A.green,
  showAxes = true,
}) => {
  const w = 600;
  // Empty data → render an empty placeholder. SVG <path> with d="" would crash
  // in some browsers and trying to compose a path from zero points produces
  // strings like " L 600,h L 0,h Z" (no leading M) which throws errors.
  if (!data || data.length === 0) {
    return (
      <div
        style={{
          height, width: "100%",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 12, color: A.inkMute, fontStyle: "italic",
        }}
      >
        sem dados para exibir
      </div>
    );
  }
  const max = Math.max(...data.map((d) => d.value)) + 5;
  const min = Math.max(0, Math.min(...data.map((d) => d.value)) - 10);
  const range = max - min || 1; // avoid division by zero when all values equal
  // Single point: center it horizontally (no line to draw, just the dot).
  const xStep = data.length > 1 ? w / (data.length - 1) : 0;
  const points = data.map((d, i) => [
    data.length > 1 ? i * xStep : w / 2,
    height - ((d.value - min) / range) * (height - 30) - 15,
  ]);
  const path = points
    .map((p, i) => (i === 0 ? "M" : "L") + p[0] + "," + p[1])
    .join(" ");
  // Area fill only makes sense for ≥2 points
  const area = data.length > 1
    ? path + ` L ${w},${height} L 0,${height} Z`
    : null;
  return (
    <div style={{ position: "relative", width: "100%" }}>
      <svg
        width="100%"
        height={height}
        viewBox={`0 0 ${w} ${height}`}
        preserveAspectRatio="none"
        style={{ display: "block" }}
      >
        <defs>
          <linearGradient id="lineGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={accent} stopOpacity="0.35" />
            <stop offset="100%" stopColor={accent} stopOpacity="0" />
          </linearGradient>
        </defs>
        {showAxes &&
          [0.25, 0.5, 0.75].map((t) => (
            <line
              key={t}
              x1="0"
              y1={height * t}
              x2={w}
              y2={height * t}
              stroke="rgba(0,0,0,0.06)"
              strokeWidth="1"
              strokeDasharray="2 4"
            />
          ))}
        {area && <path d={area} fill="url(#lineGrad)" />}
        {data.length > 1 && (
          <path
            d={path}
            fill="none"
            stroke={accent}
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            vectorEffect="non-scaling-stroke"
          />
        )}
        {points.map((p, i) => (
          <circle
            key={i}
            cx={p[0]}
            cy={p[1]}
            r="3"
            fill="#fff"
            stroke={accent}
            strokeWidth="2"
          />
        ))}
      </svg>
    </div>
  );
};

// ───────────── AVATAR ─────────────
const Avatar = ({ name, size = 32, role }) => {
  const initials = name
    .split(" ")
    .filter(Boolean)
    .slice(0, 2)
    .map((p) => p[0])
    .join("")
    .toUpperCase();
  const palette =
    role === "admin"
      ? [A.gold, "#b88600"]
      : role === "teacher"
        ? [A.green, A.greenDark]
        : [A.greenSoft, A.greenLight];
  return (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: "50%",
        background: `linear-gradient(135deg, ${palette[0]}, ${palette[1]})`,
        color: "#fff",
        fontSize: size * 0.36,
        fontWeight: 700,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontFamily: '"Plus Jakarta Sans", sans-serif',
        flexShrink: 0,
        boxShadow: "inset 0 1px 0 rgba(255,255,255,0.3)",
      }}
    >
      {initials}
    </div>
  );
};

// ───────────── MODAL ─────────────
const Modal = ({ open, onClose, title, children, width = 520, footer }) => {
  if (!open) return null;
  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed",
        inset: 0,
        background: "rgba(8,26,18,0.55)",
        backdropFilter: "blur(8px)",
        WebkitBackdropFilter: "blur(8px)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 100,
        padding: 20,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: "#ffffff",
          border: "1px solid rgba(0,78,45,0.10)",
          borderRadius: 16,
          width: "100%",
          maxWidth: width,
          boxShadow: "0 24px 60px rgba(0,40,20,0.35)",
          overflow: "hidden",
          maxHeight: "90vh",
          display: "flex",
          flexDirection: "column",
        }}
      >
        <div
          style={{
            padding: "18px 24px",
            borderBottom: "1px solid rgba(0,0,0,0.08)",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <h3
            style={{
              margin: 0,
              fontSize: 17,
              fontWeight: 600,
              color: A.ink,
              fontFamily: '"Plus Jakarta Sans", sans-serif',
            }}
          >
            {title}
          </h3>
          <button
            onClick={onClose}
            style={{
              background: "none",
              border: "none",
              cursor: "pointer",
              color: A.inkMute,
              padding: 4,
              display: "flex",
            }}
          >
            <Icon name="x" size={18} />
          </button>
        </div>
        <div style={{ padding: "20px 24px", overflowY: "auto", flex: 1 }}>
          {children}
        </div>
        {footer && (
          <div
            style={{
              padding: "14px 24px",
              borderTop: "1px solid rgba(0,0,0,0.08)",
              display: "flex",
              justifyContent: "flex-end",
              gap: 10,
              background: "rgba(0,0,0,0.02)",
            }}
          >
            {footer}
          </div>
        )}
      </div>
    </div>
  );
};

// ───────────── TABLE ─────────────
const Table = ({ columns, rows, onRowClick, empty }) => (
  <div
    style={{
      borderRadius: 10,
      overflow: "hidden",
      border: "1px solid rgba(0,0,0,0.08)",
      background: "#ffffff",
    }}
  >
    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
      <thead>
        <tr style={{ background: "rgba(0,0,0,0.03)" }}>
          {columns.map((c, i) => (
            <th
              key={i}
              style={{
                padding: "11px 14px",
                textAlign: c.align || "left",
                fontSize: 11,
                fontWeight: 600,
                color: A.inkSoft,
                letterSpacing: "0.04em",
                textTransform: "uppercase",
                borderBottom: "1px solid rgba(0,0,0,0.06)",
              }}
            >
              {c.label}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {rows.length === 0 && (
          <tr>
            <td
              colSpan={columns.length}
              style={{ padding: "40px", textAlign: "center", color: A.inkMute }}
            >
              {empty || "Sem registros"}
            </td>
          </tr>
        )}
        {rows.map((r, i) => (
          <tr
            key={i}
            onClick={() => onRowClick && onRowClick(r)}
            style={{
              cursor: onRowClick ? "pointer" : "default",
              transition: "background 100ms",
            }}
            onMouseEnter={(e) =>
              (e.currentTarget.style.background = "rgba(0,78,45,0.04)")
            }
            onMouseLeave={(e) =>
              (e.currentTarget.style.background = "transparent")
            }
          >
            {columns.map((c, j) => (
              <td
                key={j}
                style={{
                  padding: "11px 14px",
                  textAlign: c.align || "left",
                  borderBottom:
                    i < rows.length - 1 ? "1px solid rgba(0,0,0,0.05)" : "none",
                  color: A.ink,
                }}
              >
                {c.render ? c.render(r) : r[c.key]}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

// ───────────── BACKGROUND PHOTO PLACEHOLDER ─────────────
// SVG-based "industrial site" placeholder — striped, monospace label
const RefineryBg = () => (
  <svg
    width="100%"
    height="100%"
    viewBox="0 0 1920 1080"
    preserveAspectRatio="xMidYMid slice"
    style={{ position: "absolute", inset: 0, zIndex: 0 }}
  >
    <defs>
      <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor="#0a3a26" />
        <stop offset="40%" stopColor="#0d4a30" />
        <stop offset="100%" stopColor="#082218" />
      </linearGradient>
      <pattern
        id="stripes"
        width="14"
        height="14"
        patternUnits="userSpaceOnUse"
        patternTransform="rotate(35)"
      >
        <rect width="14" height="14" fill="#0d4a30" />
        <rect width="7" height="14" fill="#0a3a26" />
      </pattern>
      <radialGradient id="glow" cx="50%" cy="40%" r="60%">
        <stop offset="0%" stopColor="#dda003" stopOpacity="0.18" />
        <stop offset="100%" stopColor="#dda003" stopOpacity="0" />
      </radialGradient>
    </defs>
    <rect width="1920" height="1080" fill="url(#sky)" />
    <rect width="1920" height="1080" fill="url(#glow)" />
    {/* horizon stripe band */}
    <rect
      x="0"
      y="640"
      width="1920"
      height="180"
      fill="url(#stripes)"
      opacity="0.55"
    />
    {/* simple silhouette of refinery towers — boxes/cylinders */}
    <g opacity="0.32" fill="#000">
      <rect x="180" y="540" width="80" height="240" />
      <rect x="270" y="600" width="40" height="180" />
      <rect x="320" y="560" width="60" height="220" />
      <rect x="400" y="640" width="120" height="140" />
      <rect x="540" y="500" width="50" height="280" />
      <rect x="600" y="580" width="100" height="200" />
      <rect x="720" y="530" width="60" height="250" />
      <rect x="800" y="600" width="80" height="180" />
      <rect x="900" y="480" width="40" height="300" />
      <rect x="960" y="560" width="160" height="220" />
      <rect x="1140" y="600" width="80" height="180" />
      <rect x="1240" y="540" width="50" height="240" />
      <rect x="1310" y="580" width="100" height="200" />
      <rect x="1430" y="500" width="40" height="280" />
      <rect x="1490" y="600" width="120" height="180" />
      <rect x="1630" y="560" width="60" height="220" />
      <rect x="1710" y="540" width="80" height="240" />
      {/* horizontal pipes */}
      <rect x="0" y="820" width="1920" height="6" />
      <rect x="0" y="840" width="1920" height="3" />
      <rect x="0" y="855" width="1920" height="4" />
    </g>
  </svg>
);

window.UI = {
  Icon,
  AbendiMark,
  AbendiWordmark,
  AbendiBrandCard,
  RysaxMark,
  Glass,
  Button,
  Badge,
  Input,
  Segmented,
  Metric,
  BarChart,
  StackedBar,
  Radial,
  LineChart,
  Avatar,
  Modal,
  Table,
  RefineryBg,
  A,
};
