/* eslint-disable */
// Shared primitives and tiny utilities used across the Alamelu workspace.

const { useState, useEffect, useRef, useCallback, useMemo, useLayoutEffect, Fragment } = React;

/* ---------- icons (hand-tuned monoline, 1.5px stroke, currentColor) ---------- */
function Icon({ d, size = 16, stroke = 1.5, fill = "none", style, viewBox = "0 0 24 24", children }) {
  return (
    <svg
      width={size} height={size} viewBox={viewBox}
      fill={fill} stroke="currentColor" strokeWidth={stroke}
      strokeLinecap="round" strokeLinejoin="round"
      style={{ flex: "none", ...style }}
      aria-hidden="true"
    >
      {d ? <path d={d} /> : children}
    </svg>
  );
}

const I = {
  Chat:      (p) => <Icon {...p}>{<path d="M4 6.5A2.5 2.5 0 0 1 6.5 4h11A2.5 2.5 0 0 1 20 6.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4 3v-3H6.5A2.5 2.5 0 0 1 4 14.5v-8Z"/>}</Icon>,
  File:      (p) => <Icon {...p}>{<><path d="M7 3h7l4 4v13a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Z"/><path d="M14 3v4h4"/></>}</Icon>,
  Activity:  (p) => <Icon {...p} d="M3 12h3l3-7 4 14 3-7h5" />,
  Wallet:    (p) => <Icon {...p}>{<><path d="M3 7a2 2 0 0 1 2-2h13a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"/><path d="M16 13h2"/><path d="M3 9h18"/></>}</Icon>,
  Routes:    (p) => <Icon {...p}>{<><circle cx="6" cy="6" r="2"/><circle cx="18" cy="18" r="2"/><path d="M6 8v4a4 4 0 0 0 4 4h4a4 4 0 0 1 4 4"/></>}</Icon>,
  Dashboard: (p) => <Icon {...p}>{<><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="3" y="15" width="7" height="6" rx="1.5"/><rect x="14" y="11" width="7" height="10" rx="1.5"/></>}</Icon>,
  Markets:   (p) => <Icon {...p} d="M3 17l5-6 4 4 7-9" />,
  Briefcase: (p) => <Icon {...p}>{<><rect x="3" y="7" width="18" height="13" rx="2"/><path d="M9 7V5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/></>}</Icon>,
  Orders:    (p) => <Icon {...p}>{<><rect x="4" y="3" width="14" height="18" rx="2"/><path d="M8 8h6M8 12h6M8 16h4"/></>}</Icon>,
  Bell:      (p) => <Icon {...p}>{<><path d="M6 9a6 6 0 1 1 12 0c0 4 1.5 5 2 6H4c.5-1 2-2 2-6Z"/><path d="M10 19a2 2 0 0 0 4 0"/></>}</Icon>,
  Strategy:  (p) => <Icon {...p}>{<><circle cx="12" cy="6" r="2.5"/><circle cx="5" cy="18" r="2.5"/><circle cx="19" cy="18" r="2.5"/><path d="M12 8.5v3M10 13l-4 3M14 13l4 3"/></>}</Icon>,
  Send:      (p) => <Icon {...p} d="M4 12l16-8-6 16-2-7-8-1Z" />,
  Plus:      (p) => <Icon {...p} d="M12 5v14M5 12h14" />,
  Refresh:   (p) => <Icon {...p}>{<><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 4v5h-5"/></>}</Icon>,
  Search:    (p) => <Icon {...p}>{<><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></>}</Icon>,
  Sparkles:  (p) => <Icon {...p}>{<><path d="M12 4v4M12 16v4M4 12h4M16 12h4"/><path d="M7 7l2 2M15 15l2 2M7 17l2-2M15 9l2-2"/></>}</Icon>,
  Eye:       (p) => <Icon {...p}>{<><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></>}</Icon>,
  Edit:      (p) => <Icon {...p} d="M4 20h4l10-10-4-4L4 16v4Z" />,
  Save:      (p) => <Icon {...p}>{<><path d="M5 3h11l3 3v14a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Z"/><path d="M8 3v5h7V3M8 21v-6h8v6"/></>}</Icon>,
  Lock:      (p) => <Icon {...p}>{<><rect x="4" y="10" width="16" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></>}</Icon>,
  Warn:      (p) => <Icon {...p}>{<><path d="M12 3l10 18H2L12 3Z"/><path d="M12 10v5M12 18v.5"/></>}</Icon>,
  Dot:       (p) => <Icon {...p} fill="currentColor" stroke="none"><circle cx="12" cy="12" r="4"/></Icon>,
  Drag:      (p) => <Icon {...p}>{<><circle cx="9" cy="6" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="9" cy="18" r="1"/><circle cx="15" cy="6" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="18" r="1"/></>}</Icon>,
  Trash:     (p) => <Icon {...p}>{<><path d="M4 7h16M9 7V4h6v3M6 7l1 14h10l1-14"/></>}</Icon>,
  Settings:  (p) => <Icon {...p}>{<><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1A2 2 0 1 1 4.3 17l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1A2 2 0 1 1 7 4.3l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></>}</Icon>,
  Clock:     (p) => <Icon {...p}>{<><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>}</Icon>,
  Check:     (p) => <Icon {...p} d="M5 12l5 5L20 7" />,
  X:         (p) => <Icon {...p} d="M6 6l12 12M18 6L6 18" />,
  Up:        (p) => <Icon {...p} d="M6 15l6-6 6 6" />,
  Down:      (p) => <Icon {...p} d="M6 9l6 6 6-6" />,
};

/* ---------- atoms ---------- */
function Pill({ tone = "neutral", children, soft = true, style }) {
  const map = {
    good:    { fg: "var(--good)",    bg: "var(--good-soft)"   },
    warn:    { fg: "var(--warn)",    bg: "var(--warn-soft)"   },
    bad:     { fg: "var(--bad)",     bg: "var(--bad-soft)"    },
    info:    { fg: "var(--info)",    bg: "var(--info-soft)"   },
    accent:  { fg: "var(--accent)",  bg: "var(--accent-soft)" },
    neutral: { fg: "var(--text-2)",  bg: "oklch(0.30 0.025 245 / 0.5)" },
  };
  const t = map[tone] || map.neutral;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "2px 8px",
      fontSize: 11, fontWeight: 600,
      letterSpacing: 0.02 + "em",
      color: t.fg,
      background: soft ? t.bg : "transparent",
      border: soft ? "none" : `1px solid ${t.fg}`,
      borderRadius: 999,
      lineHeight: 1.6,
      whiteSpace: "nowrap",
      ...style,
    }}>{children}</span>
  );
}

function StatusDot({ tone = "good", size = 8, pulse = true }) {
  const colorMap = {
    good: "var(--good)", warn: "var(--warn)", bad: "var(--bad)",
    info: "var(--info)", accent: "var(--accent)", muted: "var(--text-3)"
  };
  return (
    <span style={{
      width: size, height: size, borderRadius: 999,
      background: colorMap[tone],
      boxShadow: pulse ? `0 0 0 0 ${colorMap[tone]}` : "none",
      animation: pulse ? "pulse-dot 2.4s ease-in-out infinite" : "none",
      color: colorMap[tone],
      flex: "none",
    }}/>
  );
}

function Card({ title, subtitle, right, padding = 18, children, style, bodyStyle, headerStyle }) {
  return (
    <section style={{
      background: "var(--bg-1)",
      borderRadius: "var(--r-lg)",
      boxShadow: "var(--shadow-1)",
      ...style,
    }}>
      {(title || right) && (
        <header style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          gap: 12,
          padding: `${padding}px ${padding}px ${subtitle ? 4 : padding}px`,
          ...headerStyle
        }}>
          <div style={{ minWidth: 0 }}>
            {title && <h3 style={{
              margin: 0, fontSize: 15, fontWeight: 600,
              color: "var(--text-1)", letterSpacing: "-0.01em"
            }}>{title}</h3>}
            {subtitle && <p style={{
              margin: "2px 0 0", fontSize: 12.5, color: "var(--text-3)",
            }}>{subtitle}</p>}
          </div>
          {right && <div style={{ display: "flex", gap: 8, alignItems: "center" }}>{right}</div>}
        </header>
      )}
      <div style={{ padding: title ? `12px ${padding}px ${padding}px` : padding, ...bodyStyle }}>
        {children}
      </div>
    </section>
  );
}

function IconButton({ children, onClick, title, active, style }) {
  return (
    <button
      onClick={onClick}
      title={title}
      style={{
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        width: 30, height: 30,
        background: active ? "var(--bg-3)" : "transparent",
        color: active ? "var(--text-1)" : "var(--text-3)",
        border: "1px solid " + (active ? "var(--border-m)" : "transparent"),
        borderRadius: "var(--r-sm)",
        transition: "all 120ms ease",
        ...style,
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.background = "var(--bg-2)";
        e.currentTarget.style.color = "var(--text-1)";
      }}
      onMouseLeave={(e) => {
        if (!active) {
          e.currentTarget.style.background = "transparent";
          e.currentTarget.style.color = "var(--text-3)";
        }
      }}
    >{children}</button>
  );
}

function Btn({ kind = "ghost", size = "md", icon, children, onClick, disabled, style }) {
  const base = {
    display: "inline-flex", alignItems: "center", gap: 8,
    fontWeight: 600,
    border: "1px solid transparent",
    borderRadius: "var(--r-sm)",
    transition: "all 140ms ease",
    whiteSpace: "nowrap",
  };
  const sizes = {
    sm: { fontSize: 12, padding: "5px 10px" },
    md: { fontSize: 13, padding: "7px 12px" },
    lg: { fontSize: 14, padding: "9px 16px" },
  };
  const kinds = {
    primary: {
      background: "var(--accent)",
      color: "oklch(0.18 0.04 170)",
      boxShadow: "0 1px 0 0 oklch(1 0 0 / 0.2) inset, 0 6px 14px -8px var(--accent)",
    },
    ghost: {
      background: "transparent",
      color: "var(--text-2)",
      border: "1px solid var(--border-m)",
    },
    subtle: {
      background: "var(--bg-2)",
      color: "var(--text-1)",
      border: "1px solid var(--border-s)",
    },
    danger: {
      background: "var(--bad-soft)",
      color: "var(--bad)",
      border: "1px solid oklch(0.700 0.200 25 / 0.4)",
    },
  };
  return (
    <button onClick={onClick} disabled={disabled}
      style={{ ...base, ...sizes[size], ...kinds[kind], opacity: disabled ? 0.5 : 1, ...style }}
      onMouseEnter={(e) => {
        if (kind === "ghost") e.currentTarget.style.background = "var(--bg-2)";
        if (kind === "subtle") e.currentTarget.style.background = "var(--bg-3)";
        if (kind === "primary") e.currentTarget.style.filter = "brightness(1.08)";
      }}
      onMouseLeave={(e) => {
        if (kind === "ghost") e.currentTarget.style.background = "transparent";
        if (kind === "subtle") e.currentTarget.style.background = "var(--bg-2)";
        if (kind === "primary") e.currentTarget.style.filter = "none";
      }}
    >
      {icon}{children}
    </button>
  );
}

/* ---------- sparkline ---------- */
function Sparkline({ data, color = "var(--accent)", height = 36, width = "100%", fill = true, animate = true }) {
  const ref = useRef(null);
  const [w, setW] = useState(0);
  useLayoutEffect(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver(([e]) => setW(e.contentRect.width));
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);
  const min = Math.min(...data);
  const max = Math.max(...data);
  const span = max - min || 1;
  const W = w || 200;
  const H = height;
  const pad = 2;
  const step = (W - pad * 2) / (data.length - 1);
  const pts = data.map((v, i) => [pad + i * step, H - pad - ((v - min) / span) * (H - pad * 2)]);
  const path = pts.map((p, i) => (i === 0 ? "M" : "L") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  const area = path + ` L ${pts[pts.length-1][0].toFixed(1)} ${H} L ${pts[0][0].toFixed(1)} ${H} Z`;
  const gradId = useMemo(() => "spg-" + Math.random().toString(36).slice(2,9), []);
  return (
    <div ref={ref} style={{ width, height }}>
      {w > 0 && (
        <svg width={W} height={H} style={{ display: "block", overflow: "visible" }}>
          <defs>
            <linearGradient id={gradId} x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%"  stopColor={color} stopOpacity="0.32" />
              <stop offset="100%" stopColor={color} stopOpacity="0" />
            </linearGradient>
          </defs>
          {fill && <path d={area} fill={`url(#${gradId})`} />}
          <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"
            style={animate ? {
              strokeDasharray: 600, strokeDashoffset: 600,
              animation: "draw 1.4s cubic-bezier(.2,.7,.2,1) forwards"
            } : undefined}
          />
          <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.5" fill={color} />
        </svg>
      )}
      <style>{`@keyframes draw { to { stroke-dashoffset: 0; } }`}</style>
    </div>
  );
}

/* ---------- formatting helpers ---------- */
function fmtMoney(n, frac = 2) {
  return n.toLocaleString("en-US", { minimumFractionDigits: frac, maximumFractionDigits: frac });
}
function fmtSigned(n, frac = 2) {
  const sign = n > 0 ? "+" : n < 0 ? "−" : "";
  return sign + Math.abs(n).toLocaleString("en-US", { minimumFractionDigits: frac, maximumFractionDigits: frac });
}
function now() {
  const d = new Date();
  return d.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false }) +
    ":" + String(d.getSeconds()).padStart(2, "0");
}

Object.assign(window, {
  React, ReactDOM, I, Icon, Pill, StatusDot, Card, IconButton, Btn, Sparkline,
  fmtMoney, fmtSigned, now,
});
