// Huvudapp för Nordstar.ai dashboard
const { useState, useMemo, useEffect } = React;

function Sidebar({ active, onSelect, onSignOut }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const items = [
    { id: "dashboard", icon: "home", label: "Översikt" },
    { id: "projects", icon: "sliders", label: "Projekt & initiativ" },
    { id: "strategy", icon: "trending-up", label: "Strategi" },
    { id: "finance", icon: "wallet", label: "Ekonomi" },
    { id: "members", icon: "users", label: "Medlemsvård" },
    { id: "properties", icon: "building", label: "Fastigheter" },
  ];
  return (
    <aside className="w-[232px] flex-shrink-0 bg-white border-r border-zinc-200 flex flex-col">
      <div className="h-14 flex items-center gap-2.5 px-5 border-b border-zinc-200">
        <div className="leading-tight">
          <img src="nordstar-logo.svg" alt="Nordstar.ai" style={{ width: 116 }} className="block"/>
          <div className="text-[10.5px] text-zinc-500 mt-1">Stiftelsen Nordstar sr</div>
        </div>
      </div>
      <nav className="px-3 py-3 flex-1 overflow-y-auto min-h-0">
        <div className="text-[10.5px] font-semibold text-zinc-400 uppercase tracking-wider px-2.5 mb-1.5">Arbetsyta</div>
        <ul className="space-y-0.5">
          {items.map(it => (
            <li key={it.id}>
              <button
                onClick={() => !it.disabled && onSelect(it.id)}
                disabled={it.disabled}
                title={it.disabled ? "Kommer snart" : undefined}
                className={`w-full flex items-center gap-2.5 px-2.5 h-8 rounded-md text-[13px] font-medium transition-colors ${
                  it.disabled
                    ? "text-zinc-400 cursor-not-allowed"
                    : active === it.id
                      ? "bg-zinc-100 text-zinc-900"
                      : "text-zinc-600 hover:bg-zinc-50 hover:text-zinc-900"
                }`}
              >
                <Icon name={it.icon} className="w-4 h-4" strokeWidth={1.75}/>
                <span className="flex-1 text-left">{it.label}</span>
                {it.disabled && (
                  <span className="text-[9.5px] font-medium text-zinc-400 bg-zinc-100 px-1.5 py-0.5 rounded uppercase tracking-wide">Snart</span>
                )}
                {it.count !== undefined && (
                  <span className="text-[10.5px] text-zinc-400 font-mono">{it.count}</span>
                )}
                {it.badge && (
                  <span className="px-1.5 h-4 rounded-full bg-indigo-600 text-white text-[10px] font-semibold flex items-center justify-center">{it.badge}</span>
                )}
              </button>
            </li>
          ))}
        </ul>

        <div className="text-[10px] font-medium text-zinc-400 px-2.5 mt-5 mb-1">Sparade vyer</div>
        <ul className="space-y-0.5">
          {["Ledningens översikt", "Kvartalsrapport Q1", "Renoveringsprogram"].map(v => (
            <li key={v}>
              <button className="w-full flex items-center gap-2.5 px-2.5 h-8 rounded-md text-[13px] text-zinc-600 hover:bg-zinc-50 hover:text-zinc-900">
                <Icon name="star" className="w-3.5 h-3.5 text-zinc-400" strokeWidth={1.75}/>
                <span className="truncate">{v}</span>
              </button>
            </li>
          ))}
        </ul>

        <div className="text-[10.5px] font-semibold text-zinc-400 uppercase tracking-wider px-2.5 mt-5 mb-1.5">AI Chat</div>
        <button className="w-full flex items-center gap-2.5 px-2.5 h-8 rounded-md text-[13px] font-medium text-zinc-700 hover:bg-zinc-50 hover:text-zinc-900 transition-colors mb-2">
          <Icon name="square-pen" className="w-3.5 h-3.5 text-zinc-400" strokeWidth={1.75}/>
          <span className="flex-1 text-left">Ny chat</span>
        </button>
        <div className="text-[10px] font-medium text-zinc-400 px-2.5 mb-1">Senaste chattar</div>
        <ul className="space-y-0.5">
          {["Analys av Q2-utfall", "Sammanfattning av riskrapport", "Prestandaindex – trender", "Diversifiering av intäkter"].map(c => (
            <li key={c}>
              <button className="w-full flex items-center gap-2.5 px-2.5 h-8 rounded-md text-[13px] text-zinc-600 hover:bg-zinc-50 hover:text-zinc-900">
                <Icon name="message-square" className="w-3.5 h-3.5 text-zinc-400" strokeWidth={1.75}/>
                <span className="truncate">{c}</span>
              </button>
            </li>
          ))}
        </ul>
      </nav>
      <div className="border-t border-zinc-200 p-3 relative">
        {menuOpen && (
          <>
            <div className="fixed inset-0 z-30" onClick={() => setMenuOpen(false)}/>
            <div className="absolute left-3 right-3 bottom-[calc(100%-8px)] z-40 bg-white border border-zinc-200 rounded-lg shadow-lg py-1 overflow-hidden">
              <button
                onClick={() => setMenuOpen(false)}
                className="w-full flex items-center gap-2.5 px-3 h-8 text-[13px] text-zinc-700 hover:bg-zinc-50"
              >
                <Icon name="users" className="w-3.5 h-3.5 text-zinc-500"/>
                Profil
              </button>
              <button
                onClick={() => setMenuOpen(false)}
                className="w-full flex items-center gap-2.5 px-3 h-8 text-[13px] text-zinc-700 hover:bg-zinc-50"
              >
                <Icon name="settings" className="w-3.5 h-3.5 text-zinc-500"/>
                Inställningar
              </button>
              <div className="my-1 border-t border-zinc-100"/>
              <button
                onClick={() => { setMenuOpen(false); onSignOut(); }}
                className="w-full flex items-center gap-2.5 px-3 h-8 text-[13px] text-rose-600 hover:bg-rose-50"
              >
                <Icon name="log-out" className="w-3.5 h-3.5"/>
                Logga ut
              </button>
            </div>
          </>
        )}
        <button
          onClick={() => setMenuOpen(o => !o)}
          className={`w-full flex items-center gap-2.5 px-1.5 py-1.5 rounded-md transition-colors ${menuOpen ? "bg-zinc-100" : "hover:bg-zinc-50"}`}
        >
          <div className="w-8 h-8 rounded-full bg-gradient-to-br from-slate-500 to-slate-700 flex items-center justify-center text-white text-[11px] font-semibold flex-shrink-0">AN</div>
          <div className="flex-1 min-w-0 leading-tight text-left">
            <div className="text-[12.5px] font-semibold text-zinc-900 truncate">Anna Niemelä</div>
            <div className="text-[10.5px] text-zinc-500 truncate">Förvaltningschef</div>
          </div>
          <Icon
            name="chevron-down"
            className={`w-3.5 h-3.5 text-zinc-400 transition-transform flex-shrink-0 ${menuOpen ? "rotate-180" : ""}`}
          />
        </button>
      </div>
    </aside>
  );
}

function Topbar({ onAddWidget, range, onRangeChange, title = "Dashboard", crumb = "Översikt", showControls = true, showAddWidget = true, showExport = false, showScheme = false }) {
  return (
    <header className="h-14 bg-white/80 backdrop-blur border-b border-zinc-200 flex items-center px-6 gap-3 sticky top-0 z-20">
      <div>
        <div className="flex items-center gap-1.5 text-[11.5px] text-zinc-500">
          <span>Arbetsyta</span>
          <Icon name="chevron-right" className="w-3 h-3"/>
          <span>{crumb}</span>
        </div>
        <h1 className="text-[15px] font-semibold text-zinc-900 tracking-tight">{title}</h1>
      </div>
      <div className="flex items-center gap-2 ml-auto">
        {showControls && (
          <>
            <Segmented
              options={[
                { value: "ytd", label: "YTD" },
                { value: "1y", label: "1 år" },
                { value: "5y", label: "5 år" },
              ]}
              value={range}
              onChange={onRangeChange}
            />
            <Button variant="outline" size="sm">
              <Icon name="filter" className="w-3.5 h-3.5"/>
              Filtrera
            </Button>
            <Button variant="outline" size="sm">
              <Icon name="download" className="w-3.5 h-3.5"/>
              Exportera
            </Button>
            <div className="w-px h-6 bg-zinc-200 mx-1"/>
          </>
        )}
        {showScheme && <window.SchemeToggle/>}
        {showExport && !showControls && (
          <>
            <Button variant="outline" size="sm">
              <Icon name="download" className="w-3.5 h-3.5"/>
              Exportera
            </Button>
            <div className="w-px h-6 bg-zinc-200 mx-1"/>
          </>
        )}
        <button className="relative h-9 w-9 rounded-lg border border-zinc-200 bg-white hover:bg-zinc-50 flex items-center justify-center text-zinc-600">
          <Icon name="bell" className="w-4 h-4"/>
          <span className="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-rose-500 ring-2 ring-white"/>
        </button>
        <Button onClick={onAddWidget} size="sm" className={showAddWidget ? "" : "hidden"}>
          <Icon name="plus" className="w-3.5 h-3.5"/>
          Lägg till widget
        </Button>
      </div>
    </header>
  );
}

// ============ AI Insights ============
function AIInsights() {
  const { summary, items } = window.NORDSTAR_DATA.aiInsights;
  const [active, setActive] = useState(0);
  const tonesIcon = {
    positive: { icon: "trending-up", bg: "bg-emerald-50", border: "border-emerald-100", text: "text-emerald-700", dot: "bg-emerald-500" },
    warning: { icon: "alert-circle", bg: "bg-amber-50", border: "border-amber-100", text: "text-amber-800", dot: "bg-amber-500" },
    danger: { icon: "alert-circle", bg: "bg-rose-50", border: "border-rose-100", text: "text-rose-700", dot: "bg-rose-500" },
  };
  const kindLabel = { trend: "Trend", anomaly: "Avvikelse", opportunity: "Möjlighet" };

  return (
    <Card className="overflow-hidden relative">
      {/* Subtle gradient accent */}
      <div className="absolute inset-0 pointer-events-none" style={{
        background: "radial-gradient(800px circle at 0% 0%, rgba(79,70,229,0.04), transparent 40%), radial-gradient(600px circle at 100% 0%, rgba(16,185,129,0.03), transparent 40%)",
      }}/>
      <div className="relative">
        <div className="flex items-start justify-between px-6 pt-5 pb-4 border-b border-zinc-100">
          <div className="flex items-start gap-3">
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-[15px] font-semibold text-zinc-900 tracking-tight">AI-insikter</h2>
                <Badge variant="info">Beta</Badge>
                <Badge variant="outline">Uppdaterat 09:14</Badge>
              </div>
              <p className="text-[13px] text-zinc-600 mt-1 max-w-3xl leading-relaxed">{summary}</p>
            </div>
          </div>
          <div className="flex items-center gap-1.5 flex-shrink-0">
            <Button variant="ghost" size="sm">
              <Icon name="refresh" className="w-3.5 h-3.5"/>
              Återgenerera
            </Button>
            <Button variant="ghost" size="sm">
              <Icon name="arrow-up-right" className="w-3.5 h-3.5"/>
              Visa alla
            </Button>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-px bg-zinc-100">
          {items.map((it, i) => {
            const t = tonesIcon[it.tone] || tonesIcon.warning;
            return (
              <button
                key={i}
                onClick={() => setActive(i)}
                className={`text-left p-4 bg-white hover:bg-zinc-50/70 transition-colors relative ${active === i ? "bg-zinc-50/70" : ""}`}
              >
                {active === i && <div className="absolute top-0 left-0 right-0 h-0.5 bg-indigo-600"/>}
                {it.section && (
                  <div className="text-[10px] font-semibold text-zinc-400 uppercase tracking-wider mb-2">{it.section}</div>
                )}
                <div className="flex items-center justify-between mb-2.5">
                  <Badge variant={it.tone === "positive" ? "positive" : "warning"}>
                    <span className={`w-1.5 h-1.5 rounded-full ${t.dot} mr-0.5`}/>
                    {kindLabel[it.kind]}
                  </Badge>
                  <span className={`text-[12px] font-semibold tabular-nums ${t.text}`}>{it.delta}</span>
                </div>
                <h4 className="text-[13px] font-semibold text-zinc-900 tracking-tight leading-snug mb-1.5">{it.title}</h4>
                <p className="text-[11.5px] text-zinc-600 leading-relaxed line-clamp-3">{it.body}</p>
                <div className="flex items-center gap-1.5 mt-3 text-[10.5px] text-zinc-400 font-mono">
                  <span>Konfidens</span>
                  <div className="flex-1 h-1 bg-zinc-100 rounded-full overflow-hidden">
                    <div className="h-full bg-zinc-700 rounded-full" style={{ width: `${it.confidence * 100}%` }}/>
                  </div>
                  <span>{(it.confidence * 100).toFixed(0)} %</span>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </Card>
  );
}

// ============ Add Widget Dialog ============
function AddWidgetDialog({ open, onOpenChange, current, onToggle, catalog }) {
  const items = catalog || window.NORDSTAR_DATA.widgetCatalog;
  const [q, setQ] = useState("");
  const [cat, setCat] = useState("Alla");
  const cats = ["Alla", ...Array.from(new Set(items.map(w => w.category)))];
  const activeCat = cats.includes(cat) ? cat : "Alla";
  const filtered = items.filter(w => {
    if (activeCat !== "Alla" && w.category !== activeCat) return false;
    if (q && !w.name.toLowerCase().includes(q.toLowerCase()) && !w.desc.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <div className="px-6 pt-5 pb-4 border-b border-zinc-100 flex items-center justify-between">
        <div>
          <h2 className="text-[16px] font-semibold text-zinc-900 tracking-tight">Lägg till widget</h2>
          <p className="text-[12.5px] text-zinc-500 mt-0.5">Välj från arbetsytornas bibliotek — varje widget visar var den hör hemma</p>
        </div>
        <button onClick={() => onOpenChange(false)} className="h-8 w-8 rounded-md hover:bg-zinc-100 flex items-center justify-center text-zinc-500">
          <Icon name="x" className="w-4 h-4"/>
        </button>
      </div>
      <div className="px-6 py-3 border-b border-zinc-100 flex items-center gap-3">
        <div className="flex-1 relative">
          <Icon name="search" className="w-4 h-4 text-zinc-400 absolute left-3 top-1/2 -translate-y-1/2"/>
          <input
            value={q}
            onChange={e => setQ(e.target.value)}
            placeholder="Sök widget..."
            className="w-full h-9 pl-9 pr-3 bg-zinc-50 border border-zinc-200 rounded-lg text-[13px] focus:outline-none focus:bg-white focus:border-zinc-300"
          />
        </div>
        <Segmented options={cats.map(c => ({ value: c, label: c }))} value={activeCat} onChange={setCat}/>
      </div>
      <div className="overflow-y-auto p-4 grid grid-cols-2 gap-2.5">
        {filtered.map(w => {
          const added = current.includes(w.id);
          return (
            <button
              key={w.id}
              onClick={() => onToggle(w.id)}
              className={`text-left p-3.5 rounded-lg border transition-all flex items-start gap-3 ${
                added
                  ? "border-zinc-900 bg-zinc-50/50"
                  : "border-zinc-200 bg-white hover:border-zinc-300 hover:bg-zinc-50/50"
              }`}
            >
              <div className={`w-9 h-9 rounded-md flex items-center justify-center flex-shrink-0 ${added ? "bg-zinc-900 text-white" : "bg-zinc-100 text-zinc-700"}`}>
                <Icon name={w.icon} className="w-4 h-4"/>
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <h4 className="text-[13px] font-semibold text-zinc-900 truncate">{w.name}</h4>
                  <Badge variant="outline">{w.category}</Badge>
                </div>
                <p className="text-[11.5px] text-zinc-500 mt-0.5 line-clamp-2 leading-snug">{w.desc}</p>
              </div>
              <div className={`w-5 h-5 rounded-md border-2 flex items-center justify-center flex-shrink-0 ${
                added ? "bg-zinc-900 border-zinc-900 text-white" : "border-zinc-300"
              }`}>
                {added && <Icon name="check" className="w-3 h-3" strokeWidth={3}/>}
              </div>
            </button>
          );
        })}
      </div>
      <div className="px-6 py-3 border-t border-zinc-100 flex items-center justify-between bg-zinc-50/50">
        <span className="text-[12px] text-zinc-500">{current.length} av {items.length} widgets aktiva</span>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={() => onOpenChange(false)}>Avbryt</Button>
          <Button size="sm" onClick={() => onOpenChange(false)}>Klart</Button>
        </div>
      </div>
    </Dialog>
  );
}

// ============ Mixad dashboard (Översikt) — widgets från flera arbetsytor ============
function getDashRegistry() {
  const R = window.WIDGET_REGISTRY || {};
  return {
    strategyIndex:  { ws: "strategi",    Comp: window.WStrategyIndex,      name: "Prestandaindex",       desc: "Strategiskt nyckeltal 0–100 mot mål 2035", icon: "trending-up" },
    flagship:       { ws: "projekt",     Comp: window.WProjektFlaggskepp,  name: "Flaggskeppsprojekt",   desc: "Status och framsteg för prioriterade projekt", icon: "star" },
    risk:           { ws: "projekt",     Comp: window.WProjektRisk,        name: "Aktiva risker",        desc: "Risker som kräver beslut denna period", icon: "alert-circle" },
    leverage:       { ws: "ekonomi",     Comp: window.LeverageCard,        name: "Leverage-faktor",      desc: "Extern resurs mobiliserad per egen euro", icon: "trending-up" },
    diversification:{ ws: "ekonomi",     Comp: window.DiversificationCard, name: "Diversifieringsindex", desc: "Fördelning av intäktskällor", icon: "percent" },
    sponsor:        { ws: "ekonomi",     Comp: window.SponsorCard,         name: "Sponsorintäkter",      desc: "Intäkter per partnernivå", icon: "banknote" },
    grossRent:      { ws: "fastigheter", Comp: R.grossRent,                name: "Bruttohyror",          desc: "Femårig utveckling av bruttohyror", icon: "trending-up" },
    occupancy:      { ws: "fastigheter", Comp: R.occupancy,                name: "Uthyrningsgrad",       desc: "Fördelad per fastighetstyp", icon: "key" },
    yield:          { ws: "fastigheter", Comp: R.yield,                    name: "Avkastning",           desc: "NOI-avkastning mot benchmark", icon: "percent" },
    renovations:    { ws: "fastigheter", Comp: R.renovations,              name: "Renoveringskostnader", desc: "Planerat vs oplanerat underhåll", icon: "wrench" },
    loans:          { ws: "fastigheter", Comp: R.loans,                    name: "Lånebörda",            desc: "Total lånebörda och räntenivå", icon: "banknote" },
    activity:       { ws: "fastigheter", Comp: R.activity,                 name: "Senaste aktivitet",    desc: "Händelseström från portföljen", icon: "activity" },
  };
}
const DASH_DEFAULT = ["strategyIndex", "grossRent", "leverage", "flagship", "occupancy", "diversification", "risk", "yield", "sponsor", "activity"];

// ============ Empty slot ============
function AddWidgetSlot({ onClick }) {
  return (
    <button
      onClick={onClick}
      className="rounded-xl border-2 border-dashed border-zinc-200 hover:border-zinc-400 bg-zinc-50/30 hover:bg-zinc-50 transition-colors min-h-[240px] flex flex-col items-center justify-center text-zinc-400 hover:text-zinc-700 group"
    >
      <div className="w-10 h-10 rounded-full bg-white border border-zinc-200 group-hover:border-zinc-300 flex items-center justify-center mb-2">
        <Icon name="plus" className="w-4 h-4"/>
      </div>
      <span className="text-[12.5px] font-medium">Lägg till widget</span>
      <span className="text-[11px] text-zinc-400 mt-0.5">Välj från biblioteket</span>
    </button>
  );
}

// ============ App ============
function App() {
  const [authed, setAuthed] = useState(() => {
    try { return sessionStorage.getItem("nordstar.authed") === "1"; } catch { return false; }
  });
  const signIn = () => {
    try { sessionStorage.setItem("nordstar.authed", "1"); } catch {}
    setAuthed(true);
  };
  const signOut = () => {
    try { sessionStorage.removeItem("nordstar.authed"); } catch {}
    setAuthed(false);
  };

  if (!authed) {
    return <window.LoginScreen onSignIn={signIn}/>;
  }

  return <Dashboard onSignOut={signOut}/>;
}

function Dashboard({ onSignOut }) {
  const [active, setActive] = useState("dashboard");
  const [range, setRange] = useState("5y");
  const [widgets, setWidgets] = useState(window.NORDSTAR_DATA.defaultLayout);
  const [dashWidgets, setDashWidgets] = useState(DASH_DEFAULT);
  const [dialog, setDialog] = useState(false);

  const dashReg = getDashRegistry();
  const dashCatalog = Object.entries(dashReg).map(([id, m]) => ({
    id, name: m.name, desc: m.desc, icon: m.icon,
    category: (window.WORKSPACE_META[m.ws] || {}).label || "Övrigt",
  }));

  const toggleWidget = id => setWidgets(w => w.includes(id) ? w.filter(x => x !== id) : [...w, id]);
  const removeWidget = id => setWidgets(w => w.filter(x => x !== id));
  const toggleDash = id => setDashWidgets(w => w.includes(id) ? w.filter(x => x !== id) : [...w, id]);
  const removeDash = id => setDashWidgets(w => w.filter(x => x !== id));

  const isDash = active === "dashboard";

  // KPI spark data
  const kpis = [
    {
      label: "Bruttohyror 2025",
      value: fmtEURshort(window.NORDSTAR_DATA.grossRent[4].value),
      delta: "+4,9 % jmf 2024",
      deltaTone: "positive",
      spark: window.NORDSTAR_DATA.grossRent.map(x => x.value),
      icon: "trending-up",
      accent: "#334155",
    },
    {
      label: "Uthyrningsgrad",
      value: "92,4 %",
      delta: "413/450 enheter",
      deltaTone: "default",
      spark: [89, 91, 91.5, 92, 92.4],
      icon: "key",
      accent: "#6366f1",
    },
    {
      label: "NOI-avkastning",
      value: "4,3 %",
      delta: "+0,4 pp jmf 2024",
      deltaTone: "positive",
      spark: window.NORDSTAR_DATA.yield.map(x => x.value),
      icon: "percent",
      accent: "#64748b",
    },
    {
      label: "Total lånebörda",
      value: fmtEURshort(window.NORDSTAR_DATA.loans[4].value),
      delta: "−5,3 % jmf 2024",
      deltaTone: "positive",
      spark: window.NORDSTAR_DATA.loans.map(x => x.value),
      icon: "banknote",
      accent: "#475569",
    },
  ];

  return (
    <div className="h-screen flex flex-col bg-zinc-50/60">
      <div className="flex flex-1 overflow-hidden">
        <Sidebar active={active} onSelect={setActive} onSignOut={onSignOut}/>
        <div className="flex-1 flex flex-col overflow-hidden">
          <Topbar
            onAddWidget={() => setDialog(true)}
            range={range}
            onRangeChange={setRange}
            title={
              active === "properties" ? "Fastigheter"
              : active === "projects" ? "Projekt & initiativ"
              : active === "strategy" ? "Strategi"
              : active === "finance" ? "Ekonomi"
              : active === "members" ? "Medlemsvård"
              : "Dashboard"
            }
            crumb={
              active === "properties" ? "Fastigheter"
              : active === "projects" ? "Projekt & initiativ"
              : active === "strategy" ? "Strategi"
              : active === "finance" ? "Ekonomi"
              : active === "members" ? "Medlemsvård"
              : "Översikt"
            }
            showControls={active === "properties"}
            showAddWidget={active !== "projects" && active !== "strategy" && active !== "finance" && active !== "members"}
            showExport={active === "projects" || active === "strategy" || active === "finance" || active === "members"}
            showScheme={active === "strategy" || active === "projects"}
          />
          <main className="flex-1 overflow-y-auto">
            <div className="px-6 py-5 max-w-[1600px] mx-auto space-y-5">
              {active === "projects" ? (
                <window.ProjectsView/>
              ) : active === "strategy" ? (
                <window.StrategyView/>
              ) : active === "finance" ? (
                <window.EkonomiView/>
              ) : active === "members" ? (
                <window.MedlemsvardView/>
              ) : active === "dashboard" ? (
                <>
                  {/* Greeting */}
                  <div className="flex items-end justify-between">
                    <div>
                      <h2 className="text-[22px] font-semibold text-zinc-900 tracking-tight">God morgon, Anna 👋</h2>
                    </div>
                    <div className="flex items-center gap-2 text-[11.5px] text-zinc-500">
                      <span className="flex items-center gap-1.5">
                        <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"/>
                        Data uppdaterad för 3 min sedan
                      </span>
                    </div>
                  </div>

                  {/* AI Insights */}
                  <AIInsights/>

                  {/* Widget grid header */}
                  <div className="flex items-center justify-between pt-2">
                    <div>
                      <h3 className="text-[15px] font-semibold text-zinc-900 tracking-tight">Widgets</h3>
                      <p className="text-[12px] text-zinc-500 mt-0.5">En blandning från dina arbetsytor — varje widget visar var den hör hemma. Hovra för att ta bort.</p>
                    </div>
                    <Button variant="outline" size="sm" onClick={() => setDialog(true)}>
                      <Icon name="plus" className="w-3.5 h-3.5"/>
                      Lägg till widget
                    </Button>
                  </div>

                  {/* Mixad widgets-grid */}
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 pb-12">
                    {dashWidgets.map(id => {
                      const m = dashReg[id];
                      if (!m || !m.Comp) return null;
                      const Comp = m.Comp;
                      return (
                        <window.WorkspaceContext.Provider key={id} value={{ ws: m.ws, onRemove: () => removeDash(id) }}>
                          <Comp/>
                        </window.WorkspaceContext.Provider>
                      );
                    })}
                    <AddWidgetSlot onClick={() => setDialog(true)}/>
                  </div>
                </>
              ) : (
                <>
                  {/* AI Insights */}
                  <AIInsights/>

                  {/* Widget grid header */}
                  <div className="flex items-center justify-between pt-2">
                    <div>
                      <h3 className="text-[15px] font-semibold text-zinc-900 tracking-tight">Widgets</h3>
                      <p className="text-[12px] text-zinc-500 mt-0.5">Anpassa dashboarden — hovra över en widget för att ta bort</p>
                    </div>
                    <Button variant="outline" size="sm" onClick={() => setDialog(true)}>
                      <Icon name="plus" className="w-3.5 h-3.5"/>
                      Lägg till widget
                    </Button>
                  </div>

                  {/* Widgets grid */}
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 pb-12">
                    {widgets.map(id => {
                      const Comp = window.WIDGET_REGISTRY[id];
                      if (!Comp) return null;
                      return (
                        <window.WorkspaceContext.Provider key={id} value={{ ws: null, onRemove: () => removeWidget(id) }}>
                          <Comp/>
                        </window.WorkspaceContext.Provider>
                      );
                    })}
                    <AddWidgetSlot onClick={() => setDialog(true)}/>
                  </div>
                </>
              )}
            </div>
          </main>
        </div>
      </div>
      <AddWidgetDialog
        open={dialog}
        onOpenChange={setDialog}
        current={isDash ? dashWidgets : widgets}
        onToggle={isDash ? toggleDash : toggleWidget}
        catalog={isDash ? dashCatalog : undefined}
      />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
