// Shadcn-stil primitiver — minimal recreation
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

// Kontext för dashboard-läge: bär widgetens arbetsyta + remove-funktion
const WorkspaceContext = React.createContext(null);

// ---------- Färgschema-store (Strategi: slate ↔ trafikljus) ----------
// Global, prenumererbar store så att toggeln i topbaren kan styra
// färgsättningen i Strategi-vyn och BSC utan prop-drilling.
window.NS_SCHEME = window.NS_SCHEME || (function () {
  let current = "slate";
  try { current = localStorage.getItem("ns_scheme") || "slate"; } catch (e) {}
  const subs = new Set();
  return {
    get current() { return current; },
    set(v) {
      if (v === current) return;
      current = v;
      try { localStorage.setItem("ns_scheme", v); } catch (e) {}
      subs.forEach(f => f());
    },
    sub(f) { subs.add(f); return () => subs.delete(f); },
  };
})();

// Tier-färger per schema. "slate" matchar den befintliga paletten exakt;
// "ryg" = röd/gul/grön i mellannyans (~400) för fyllningar, mörkare för text.
window.NS_TIERS = {
  slate: {
    high: { fill: "#1e293b", text: "#1e293b" }, // slate-800
    mid:  { fill: "#64748b", text: "#475569" }, // slate-500 / slate-600
    low:  { fill: "#cbd5e1", text: "#94a3b8" }, // slate-300 / slate-400
  },
  ryg: {
    high: { fill: "#4ade80", text: "#16a34a" }, // green-400 / green-600
    mid:  { fill: "#fbbf24", text: "#d97706" }, // amber-400 / amber-600
    low:  { fill: "#f87171", text: "#dc2626" }, // red-400 / red-600
  },
};

// Hook: prenumererar på store och triggar re-render vid schemabyte.
function useNsScheme() {
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => window.NS_SCHEME.sub(force), []);
  return window.NS_SCHEME.current;
}
window.useNsScheme = useNsScheme;

// Hjälpare: hex-färg för en tier ("high" | "mid" | "low") i aktivt schema.
window.nsTierHex = function (tier, prop = "fill") {
  return window.NS_TIERS[window.NS_SCHEME.current][tier][prop];
};

// Arbetsyte-metadata för pills
const WORKSPACE_META = {
  fastigheter: { label: "Fastigheter", icon: "building" },
  ekonomi:     { label: "Ekonomi", icon: "wallet" },
  strategi:    { label: "Strategi", icon: "trending-up" },
  projekt:     { label: "Projekt", icon: "sliders" },
};

function WorkspacePill({ ws }) {
  const meta = WORKSPACE_META[ws];
  if (!meta) return null;
  return (
    <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md text-[10px] font-medium border border-zinc-200 bg-zinc-50/80 text-zinc-500 whitespace-nowrap">
      <Icon name={meta.icon} className="w-3 h-3" strokeWidth={2}/>
      {meta.label}
    </span>
  );
}

// ---------- Card ----------
function Card({ className = "", children, ...rest }) {
  return (
    <div
      className={`bg-white rounded-xl border border-zinc-200/80 shadow-[0_1px_2px_0_rgba(15,23,42,0.04)] ${className}`}
      {...rest}
    >
      {children}
    </div>
  );
}
function CardHeader({ className = "", children }) {
  return <div className={`flex items-start justify-between px-5 pt-4 pb-2 ${className}`}>{children}</div>;
}
function CardTitle({ className = "", children }) {
  return <h3 className={`text-[13px] font-semibold text-zinc-900 tracking-tight ${className}`}>{children}</h3>;
}
function CardDescription({ className = "", children }) {
  return <p className={`text-[12px] text-zinc-500 mt-0.5 ${className}`}>{children}</p>;
}
function CardContent({ className = "", children }) {
  return <div className={`px-5 pb-5 ${className}`}>{children}</div>;
}

// ---------- Badge ----------
function Badge({ variant = "default", className = "", children }) {
  const variants = {
    default: "bg-zinc-100 text-zinc-700 border-zinc-200",
    outline: "bg-white text-zinc-700 border-zinc-200",
    positive: "bg-emerald-50 text-emerald-700 border-emerald-100",
    warning: "bg-amber-50 text-amber-800 border-amber-100",
    danger: "bg-rose-50 text-rose-700 border-rose-100",
    info: "bg-indigo-50 text-indigo-700 border-indigo-100",
    slate: "bg-slate-100 text-slate-700 border-slate-200",
    dark: "bg-zinc-900 text-zinc-50 border-zinc-900",
  };
  return (
    <span
      className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md text-[10.5px] font-medium border whitespace-nowrap ${variants[variant]} ${className}`}
    >
      {children}
    </span>
  );
}

// ---------- Button ----------
function Button({ variant = "default", size = "default", className = "", children, ...props }) {
  const variants = {
    default: "bg-zinc-900 text-white hover:bg-zinc-800 border-zinc-900",
    outline: "bg-white text-zinc-900 hover:bg-zinc-50 border-zinc-200",
    ghost: "bg-transparent text-zinc-700 hover:bg-zinc-100 border-transparent",
    secondary: "bg-zinc-100 text-zinc-900 hover:bg-zinc-200 border-zinc-100",
  };
  const sizes = {
    default: "h-9 px-3.5 text-[13px]",
    sm: "h-8 px-3 text-[12.5px]",
    icon: "h-9 w-9",
  };
  return (
    <button
      className={`inline-flex items-center justify-center gap-1.5 rounded-lg border font-medium transition-colors ${variants[variant]} ${sizes[size]} ${className}`}
      {...props}
    >
      {children}
    </button>
  );
}

// ---------- Tabs (segmented) ----------
function Segmented({ options, value, onChange, className = "" }) {
  return (
    <div className={`inline-flex items-center bg-zinc-100 rounded-lg p-0.5 ${className}`}>
      {options.map(o => (
        <button
          key={o.value}
          onClick={() => onChange(o.value)}
          className={`px-2.5 h-7 text-[12px] font-medium rounded-md transition-all ${
            value === o.value
              ? "bg-white text-zinc-900 shadow-[0_1px_2px_0_rgba(15,23,42,0.06)]"
              : "text-zinc-500 hover:text-zinc-700"
          }`}
        >
          {o.label}
        </button>
      ))}
    </div>
  );
}

// ---------- Dialog ----------
function Dialog({ open, onOpenChange, children }) {
  useEffect(() => {
    if (!open) return;
    const onEsc = e => e.key === "Escape" && onOpenChange(false);
    window.addEventListener("keydown", onEsc);
    return () => window.removeEventListener("keydown", onEsc);
  }, [open, onOpenChange]);
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div
        className="absolute inset-0 bg-zinc-900/40 backdrop-blur-[2px]"
        onClick={() => onOpenChange(false)}
      />
      <div className="relative bg-white rounded-2xl border border-zinc-200 shadow-2xl w-[720px] max-w-[95vw] max-h-[85vh] overflow-hidden flex flex-col">
        {children}
      </div>
    </div>
  );
}

// ---------- Icon (inline SVGs, lucide-stil) ----------
function Icon({ name, className = "w-4 h-4", strokeWidth = 1.75 }) {
  const paths = {
    "trending-up": <><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></>,
    "trending-down": <><polyline points="22 17 13.5 8.5 8.5 13.5 2 7"/><polyline points="16 17 22 17 22 11"/></>,
    "wrench": <path d="M14.7 6.3a4 4 0 0 0 5.4 5.4l-9.7 9.7a2.1 2.1 0 0 1-3-3l9.7-9.7a4 4 0 0 0 5.4 5.4"/>,
    "percent": <><line x1="19" y1="5" x2="5" y2="19"/><circle cx="6.5" cy="6.5" r="2.5"/><circle cx="17.5" cy="17.5" r="2.5"/></>,
    "banknote": <><rect x="2" y="6" width="20" height="12" rx="2"/><circle cx="12" cy="12" r="2.5"/><path d="M6 12h.01M18 12h.01"/></>,
    "key": <><circle cx="7.5" cy="15.5" r="3.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/></>,
    "calendar": <><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></>,
    "calendar-days": <><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/><path d="M8 14h.01M12 14h.01M16 14h.01M8 18h.01M12 18h.01M16 18h.01"/></>,
    "log-out": <><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></>,
    "file-plus": <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="12" y1="12" x2="12" y2="18"/><line x1="9" y1="15" x2="15" y2="15"/></>,
    "activity": <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>,
    "zap": <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>,
    "alert-circle": <><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></>,
    "clock": <><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></>,
    "users": <><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></>,
    "sparkles": <><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/><circle cx="12" cy="12" r="3.5"/></>,
    "search": <><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></>,
    "plus": <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
    "x": <><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></>,
    "more": <><circle cx="5" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/></>,
    "home": <><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></>,
    "building": <><rect x="4" y="2" width="16" height="20" rx="2"/><path d="M9 22v-4h6v4M8 6h.01M16 6h.01M8 10h.01M16 10h.01M8 14h.01M16 14h.01"/></>,
    "wallet": <><path d="M21 12V7a2 2 0 0 0-2-2H5a2 2 0 0 0 0 4h16v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h3v-4z"/></>,
    "file-text": <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></>,
    "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 0 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 0 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 0 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 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h0a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h0a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v0a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></>,
    "bell": <><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></>,
    "chevron-down": <polyline points="6 9 12 15 18 9"/>,
    "chevron-right": <polyline points="9 18 15 12 9 6"/>,
    "arrow-up-right": <><line x1="7" y1="17" x2="17" y2="7"/><polyline points="7 7 17 7 17 17"/></>,
    "arrow-right": <><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></>,
    "grip": <><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"/></>,
    "sliders": <><line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/></>,
    "refresh": <><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></>,
    "filter": <polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>,
    "download": <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></>,
    "star": <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>,
    "info": <><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></>,
    "check": <polyline points="20 6 9 17 4 12"/>,
    "minus": <line x1="5" y1="12" x2="19" y2="12"/>,
    "message-square": <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>,
    "square-pen": <><path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4Z"/></>,
  };
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={strokeWidth}
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
      aria-hidden="true"
    >
      {paths[name] || null}
    </svg>
  );
}

// ---------- Sparkline ----------
function Sparkline({ data, color = "#0f172a", height = 28, width = 84, fill = true }) {
  const min = Math.min(...data);
  const max = Math.max(...data);
  const range = max - min || 1;
  const points = data.map((v, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - ((v - min) / range) * (height - 4) - 2;
    return [x, y];
  });
  const path = points.map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(2)},${p[1].toFixed(2)}`).join(" ");
  const area = `${path} L${width},${height} L0,${height} Z`;
  return (
    <svg width={width} height={height} className="overflow-visible">
      {fill && <path d={area} fill={color} opacity="0.08"/>}
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx={points[points.length - 1][0]} cy={points[points.length - 1][1]} r="2" fill={color}/>
    </svg>
  );
}

// ---------- Formatters ----------
const fmtEUR = (v, decimals = 0) => new Intl.NumberFormat("sv-FI", {
  style: "currency", currency: "EUR", maximumFractionDigits: decimals, minimumFractionDigits: decimals,
}).format(v);
const fmtEURshort = v => {
  if (Math.abs(v) >= 1_000_000) return `${(v / 1_000_000).toFixed(2)} M €`;
  if (Math.abs(v) >= 1_000) return `${(v / 1_000).toFixed(0)} k €`;
  return `${v} €`;
};
const fmtPct = (v, d = 1) => `${v.toFixed(d)} %`;
const fmtNum = v => new Intl.NumberFormat("sv-FI").format(v);

// Tooltip för Recharts
function ChartTooltip({ active, payload, label, formatter = fmtEURshort, suffix = "" }) {
  if (!active || !payload || !payload.length) return null;
  return (
    <div className="bg-white border border-zinc-200 rounded-lg shadow-lg px-3 py-2 text-[12px]">
      <div className="text-zinc-500 font-medium mb-1">{label}</div>
      {payload.map((p, i) => (
        <div key={i} className="flex items-center gap-2">
          <span className="w-2 h-2 rounded-sm" style={{ background: p.color || p.fill }}/>
          <span className="text-zinc-600">{p.name}</span>
          <span className="font-mono text-zinc-900 ml-auto">
            {typeof p.value === "number" ? formatter(p.value) : p.value}{suffix}
          </span>
        </div>
      ))}
    </div>
  );
}

// ---------- Färgschema-toggle (Strategi) ----------
function SchemeToggle() {
  const scheme = window.useNsScheme();
  const opts = [
    { value: "slate", label: "Slate", dots: ["#1e293b", "#64748b", "#cbd5e1"] },
    { value: "ryg", label: "Trafikljus", dots: ["#f87171", "#fbbf24", "#4ade80"] },
  ];
  return (
    <div className="inline-flex items-center gap-2">
      <span className="text-[11px] text-zinc-400 font-medium hidden lg:inline">Färgschema</span>
      <div className="inline-flex items-center bg-zinc-100 rounded-lg p-0.5" role="radiogroup" aria-label="Färgschema">
        {opts.map(o => (
          <button
            key={o.value}
            role="radio"
            aria-checked={scheme === o.value}
            onClick={() => window.NS_SCHEME.set(o.value)}
            className={`inline-flex items-center gap-1.5 px-2.5 h-7 text-[12px] font-medium rounded-md transition-all ${
              scheme === o.value
                ? "bg-white text-zinc-900 shadow-[0_1px_2px_0_rgba(15,23,42,0.06)]"
                : "text-zinc-500 hover:text-zinc-700"
            }`}
          >
            <span className="flex items-center gap-0.5">
              {o.dots.map((d, i) => (
                <span key={i} className="w-1.5 h-1.5 rounded-full" style={{ background: d }}/>
              ))}
            </span>
            {o.label}
          </button>
        ))}
      </div>
    </div>
  );
}
window.SchemeToggle = SchemeToggle;

Object.assign(window, {
  Card, CardHeader, CardTitle, CardDescription, CardContent,
  Badge, Button, Segmented, Dialog, Icon, Sparkline,
  ChartTooltip, fmtEUR, fmtEURshort, fmtPct, fmtNum,
  WorkspaceContext, WorkspacePill, WORKSPACE_META,
});
