// ========================================================
//  Shared UI components
// ========================================================

const { useState, useMemo, useEffect, useRef } = React;

// ----- Formatting helpers -----
function fmtNum(n){ return Math.round(n||0).toLocaleString("sv-SE"); }
function fmtMoney(n, market){
  const cur = market === "NO" ? "NOK" : "SEK";
  return `${fmtNum(n)}\u00a0${cur}`;
}
function fmtPct(n, digits=1){ return `${(n||0).toFixed(digits).replace(".", ",")}\u00a0%`; }

// ----- KPI Card -----
function KpiCard({ label, value, sub, delta, deltaDirection, accent, suffix, big }){
  const isUp = deltaDirection === "up";
  const isDown = deltaDirection === "down";
  return (
    <div className="bg-white border border-paper-200 rounded-xl p-5 flex flex-col gap-3 relative overflow-hidden">
      <div className="flex items-center justify-between">
        <span className="eyebrow text-ink-500">{label}</span>
        {accent && <span className={`w-1.5 h-1.5 rounded-full ${accent}`}></span>}
      </div>
      <div className="flex items-baseline gap-2">
        <span className={`display num ${big ? "text-[44px]" : "text-[34px]"} leading-none text-ink-900`}>{value}</span>
        {suffix && <span className="text-ink-500 text-sm">{suffix}</span>}
      </div>
      <div className="flex items-center justify-between">
        <span className="text-xs text-ink-500">{sub}</span>
        {delta && (
          <span className={`text-xs num inline-flex items-center gap-1 px-1.5 py-0.5 rounded
            ${isUp ? "text-accent-ink bg-accent-soft" : isDown ? "text-rose-700 bg-rose-50" : "text-ink-500 bg-paper-100"}`}>
            {isUp && <Arrow dir="up"/>}
            {isDown && <Arrow dir="down"/>}
            {delta}
          </span>
        )}
      </div>
    </div>
  );
}
function Arrow({ dir }){
  const rot = dir === "up" ? "rotate(-45deg)" : "rotate(135deg)";
  return (
    <svg width="9" height="9" viewBox="0 0 10 10" style={{ transform: rot }} aria-hidden>
      <path d="M2 5h6M5 2l3 3-3 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// ----- Flag glyphs -----
function FlagSE({ size=14 }){
  return (
    <svg width={size} height={size*0.625} viewBox="0 0 16 10" className="inline-block rounded-sm overflow-hidden">
      <rect width="16" height="10" fill="#1e5fa3"/>
      <rect x="5" width="2" height="10" fill="#FFCD00"/>
      <rect y="4" width="16" height="2" fill="#FFCD00"/>
    </svg>
  );
}
function FlagNO({ size=14 }){
  return (
    <svg width={size} height={size*0.625} viewBox="0 0 16 10" className="inline-block rounded-sm overflow-hidden">
      <rect width="16" height="10" fill="#c83b3b"/>
      <rect x="4" width="2" height="10" fill="#fff"/>
      <rect y="4" width="16" height="2" fill="#fff"/>
      <rect x="4.5" width="1" height="10" fill="#16336b"/>
      <rect y="4.5" width="16" height="1" fill="#16336b"/>
    </svg>
  );
}
function FlagBoth({ size=14 }){
  return (
    <span className="inline-flex items-center gap-0.5">
      <FlagSE size={size}/>
      <FlagNO size={size}/>
    </span>
  );
}
function MarketTag({ market }){
  if(market === "SE") return <span className="inline-flex items-center gap-1 text-[11px] text-ink-600"><FlagSE size={11}/> SE</span>;
  if(market === "NO") return <span className="inline-flex items-center gap-1 text-[11px] text-ink-600"><FlagNO size={11}/> NO</span>;
  return <span className="inline-flex items-center gap-1 text-[11px] text-ink-600"><FlagBoth size={11}/> Samlad</span>;
}

// ----- Sidebar -----
const NAV = [
  { id:"oversikt",      label:"Översikt",         icon:"grid" },
  { id:"leads",         label:"Leads",            icon:"users" },
  { id:"budget",        label:"Budget & Kanaler", icon:"chart" },
  { id:"analys",        label:"Analys",           icon:"spark" },
];
const NAV_ADMIN = [
  { id:"installningar", label:"Inställningar",    icon:"gear", adminOnly:true },
  { id:"ekonomi",       label:"Privat ekonomi",   icon:"lock", adminOnly:true },
];

function NavIcon({ name }){
  const stroke = { stroke:"currentColor", strokeWidth:1.5, fill:"none", strokeLinecap:"round", strokeLinejoin:"round" };
  switch(name){
    case "grid":  return <svg width="16" height="16" viewBox="0 0 16 16" {...stroke}><rect x="2" y="2" width="5" height="5"/><rect x="9" y="2" width="5" height="5"/><rect x="2" y="9" width="5" height="5"/><rect x="9" y="9" width="5" height="5"/></svg>;
    case "users": return <svg width="16" height="16" viewBox="0 0 16 16" {...stroke}><circle cx="6" cy="6" r="2.5"/><path d="M2 13c0-2 2-3.5 4-3.5s4 1.5 4 3.5"/><circle cx="11" cy="6.5" r="2"/><path d="M10 13c0-2 1.5-3 3-3"/></svg>;
    case "chart": return <svg width="16" height="16" viewBox="0 0 16 16" {...stroke}><path d="M2 14h12"/><rect x="3" y="8" width="2" height="5"/><rect x="7" y="5" width="2" height="8"/><rect x="11" y="9" width="2" height="4"/></svg>;
    case "spark": return <svg width="16" height="16" viewBox="0 0 16 16" {...stroke}><path d="M2 11l3-4 3 2 5-6"/><circle cx="13" cy="3" r="0.8" fill="currentColor"/></svg>;
    case "gear":  return <svg width="16" height="16" viewBox="0 0 16 16" {...stroke}><circle cx="8" cy="8" r="2"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3 3l1.5 1.5M11.5 11.5L13 13M3 13l1.5-1.5M11.5 4.5L13 3"/></svg>;
    case "lock":  return <svg width="16" height="16" viewBox="0 0 16 16" {...stroke}><rect x="3" y="7" width="10" height="7" rx="1.5"/><path d="M5 7V5a3 3 0 0 1 6 0v2"/></svg>;
    default: return null;
  }
}

function Sidebar({ view, setView, market, setMarket, periodSpec, setPeriodSpec, period, currentUser, users }){
  const me = (users || ANVANDARE).find(u => u.email === currentUser) || ANVANDARE[0];
  async function logout(){
    try { await window.EASYTULL_BACKEND?.signOut(); }
    finally { window.location.reload(); }
  }
  return (
    <aside className="bg-ink-900 text-paper-100 w-[260px] shrink-0 flex flex-col h-screen sticky top-0">
      {/* Brand */}
      <div className="px-5 pt-6 pb-5 border-b border-white/5">
        <div className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-lg bg-accent flex items-center justify-center display text-paper-50 text-[18px] leading-none">e</div>
          <div className="leading-tight">
            <div className="display text-[19px] text-paper-50">Easytull</div>
            <div className="text-[10.5px] text-ink-400 tracking-wider uppercase">Marknadsdashboard</div>
          </div>
        </div>
      </div>

      {/* Market toggle */}
      <div className="px-4 pt-5 pb-4 border-b border-white/5">
        <div className="eyebrow text-ink-400 mb-2 px-1">Marknad</div>
        <div className="flex flex-col gap-1">
          <MarketBtn active={market==="SE"} onClick={()=>setMarket("SE")} flag={<FlagSE size={13}/>} label="EasyTull" sub="easytull.se"/>
          <MarketBtn active={market==="NO"} onClick={()=>setMarket("NO")} flag={<FlagNO size={13}/>} label="EasyToll" sub="easytoll.no"/>
          <MarketBtn active={market==="BOTH"} onClick={()=>setMarket("BOTH")} flag={<FlagBoth size={13}/>} label="Samlad vy" sub="SE + NO jämförelse"/>
        </div>
      </div>

      {/* Period picker */}
      <div className="px-4 pt-5 pb-4 border-b border-white/5">
        <div className="eyebrow text-ink-400 mb-2 px-1">Period</div>
        <PeriodPicker periodSpec={periodSpec} setPeriodSpec={setPeriodSpec} period={period}/>
        <p className="text-[10.5px] text-ink-400 leading-snug mt-2.5 px-1">
          Visar data för vald period. Budget jämförs mot månadsbudget om inget annat anges.
        </p>
      </div>

      {/* Nav */}
      <nav className="flex-1 px-3 pt-4 overflow-y-auto scroll-thin">
        {NAV.map(n => (
          <button
            key={n.id}
            onClick={()=>setView(n.id)}
            className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-[14px] text-left transition
              ${view===n.id ? "bg-white/[0.06] text-paper-50" : "text-ink-400 hover:text-paper-100 hover:bg-white/[0.03]"}`}
          >
            <span className={`${view===n.id ? "text-accent-soft" : "text-ink-400"}`}><NavIcon name={n.icon}/></span>
            <span>{n.label}</span>
            {view===n.id && <span className="ml-auto w-1 h-4 rounded-full bg-accent-soft/70"></span>}
          </button>
        ))}
        {me.rolltyp === "Admin" && (
          <>
            <div className="px-3 pt-5 pb-1 text-[10px] uppercase tracking-wider text-ink-500 flex items-center gap-1.5">
              <svg width="9" height="9" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="7" width="10" height="7" rx="1.5"/><path d="M5 7V5a3 3 0 0 1 6 0v2"/></svg>
              Privat
            </div>
            {NAV_ADMIN.map(n => (
              <button
                key={n.id}
                onClick={()=>setView(n.id)}
                className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-[14px] text-left transition
                  ${view===n.id ? "bg-white/[0.06] text-paper-50" : "text-ink-400 hover:text-paper-100 hover:bg-white/[0.03]"}`}
              >
                <span className={`${view===n.id ? "text-accent-soft" : "text-ink-400"}`}><NavIcon name={n.icon}/></span>
                <span>{n.label}</span>
                {view===n.id && <span className="ml-auto w-1 h-4 rounded-full bg-accent-soft/70"></span>}
              </button>
            ))}
          </>
        )}
      </nav>

      {/* Footer / user */}
      <div className="border-t border-white/5 p-4 relative">
        <div className="w-full flex items-center gap-2.5 rounded-lg p-1 -m-1">
          <div className="w-8 h-8 rounded-full bg-paper-100/10 flex items-center justify-center text-paper-50 text-sm display">{me.namn.charAt(0)}</div>
          <div className="leading-tight text-left flex-1 min-w-0">
            <div className="text-sm text-paper-50 truncate">{me.namn}</div>
            <div className="text-[11px] text-ink-400 truncate flex items-center gap-1.5">
              {me.roll}
              <RoleBadge rolltyp={me.rolltyp}/>
            </div>
          </div>
        </div>
        <button
          onClick={logout}
          className="mt-4 w-full flex items-center justify-center gap-2 rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2 text-[13px] text-ink-300 transition hover:bg-white/[0.06] hover:text-paper-50"
        >
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
            <path d="M6.5 2.5H3.5a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h3"/>
            <path d="M10 5l3 3-3 3"/>
            <path d="M13 8H6"/>
          </svg>
          Logga ut
        </button>
      </div>
    </aside>
  );
}

function PeriodPicker({ periodSpec, setPeriodSpec, period }){
  const [open, setOpen] = useState(false);
  const [customFrom, setCustomFrom] = useState(periodSpec.kind === "custom" ? periodSpec.from : period.fromIso);
  const [customTo, setCustomTo]     = useState(periodSpec.kind === "custom" ? periodSpec.to   : period.toIso);
  const ref = useRef(null);
  const months = listAvailableMonths();
  useEffect(()=>{
    function close(e){ if(ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener("mousedown", close);
    return ()=>document.removeEventListener("mousedown", close);
  },[]);

  function choose(spec){ setPeriodSpec(spec); setOpen(false); }
  function applyCustom(){
    if(customFrom && customTo){
      choose({ kind:"custom", from: customFrom, to: customTo });
    }
  }

  // Match active preset
  const activeKind = periodSpec.kind;

  return (
    <div className="relative" ref={ref}>
      <button
        onClick={()=>setOpen(o=>!o)}
        className={`w-full text-left bg-ink-800 text-paper-100 text-sm rounded-lg px-3 py-2.5 border ${open ? "border-white/20" : "border-white/5 hover:border-white/10"} flex items-center gap-2`}
      >
        <svg width="13" height="13" viewBox="0 0 14 14" className="text-ink-400 shrink-0">
          <rect x="2" y="3" width="10" height="9" rx="1.5" stroke="currentColor" strokeWidth="1.2" fill="none"/>
          <path d="M2 6h10M5 1.5v2M9 1.5v2" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/>
        </svg>
        <span className="flex-1 min-w-0 truncate">{period.shortLabel}</span>
        <svg width="10" height="10" viewBox="0 0 10 10" className="text-ink-400 shrink-0" style={{ transform: open ? "rotate(180deg)" : "" }}>
          <path d="M2 4l3 3 3-3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>
      {/* show resolved range under the picker */}
      <div className="px-1 mt-1.5 text-[11px] text-ink-400 num leading-tight">
        {period.fromIso} → {period.toIso} <span className="text-ink-500">· {period.days} dagar</span>
      </div>

      {open && (
        <div className="absolute z-30 left-0 right-0 mt-2 bg-ink-800 border border-white/10 rounded-xl shadow-2xl overflow-hidden w-[340px]">
          <div className="grid grid-cols-2 gap-px bg-white/5 p-px">
            {PERIOD_PRESETS.map(p => (
              <PickerBtn key={p.kind} active={activeKind === p.kind} onClick={()=>choose({ kind:p.kind })}>
                {p.label}
              </PickerBtn>
            ))}
            <PickerBtn active={activeKind === "custom"} onClick={()=>{}} asLabel>
              Anpassat
            </PickerBtn>
            <PickerBtn active={activeKind === "month"} onClick={()=>{}} asLabel>
              Specifik månad
            </PickerBtn>
          </div>

          {/* Specifik månad */}
          <div className="border-t border-white/5">
            <div className="px-3 pt-2.5 pb-1 text-[10px] uppercase tracking-wider text-ink-400">Specifik månad</div>
            <div className="px-2 pb-2 max-h-[160px] overflow-y-auto scroll-thin">
              {months.map(m => {
                const isActive = activeKind === "month" && periodSpec.value === m.specValue;
                return (
                  <button
                    key={m.specValue}
                    onClick={()=>choose({ kind:"month", value: m.specValue })}
                    className={`w-full text-left px-2.5 py-1.5 text-[13px] rounded-md flex items-center gap-2
                      ${isActive ? "bg-white/[0.08] text-paper-50" : "text-paper-100 hover:bg-white/[0.04]"}`}
                  >
                    <span className="flex-1">{m.label}</span>
                    {isActive && <span className="w-1.5 h-1.5 rounded-full bg-accent-soft"></span>}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Anpassat */}
          <div className="border-t border-white/5 px-3 py-3 bg-ink-900/50">
            <div className="text-[10px] uppercase tracking-wider text-ink-400 mb-2">Anpassat datumintervall</div>
            <div className="flex items-center gap-2">
              <input
                type="date"
                value={customFrom}
                onChange={e=>setCustomFrom(e.target.value)}
                className="flex-1 bg-ink-800 text-paper-100 text-[12px] rounded-md border border-white/10 px-2 py-1.5 focus:outline-none focus:border-white/30"
              />
              <span className="text-ink-400 text-xs">→</span>
              <input
                type="date"
                value={customTo}
                onChange={e=>setCustomTo(e.target.value)}
                className="flex-1 bg-ink-800 text-paper-100 text-[12px] rounded-md border border-white/10 px-2 py-1.5 focus:outline-none focus:border-white/30"
              />
            </div>
            <button
              onClick={applyCustom}
              className="mt-2 w-full text-center text-[12px] bg-accent text-paper-50 rounded-md py-1.5 hover:bg-accent-ink transition"
            >
              Använd
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function PickerBtn({ active, onClick, children, asLabel }){
  return (
    <button
      onClick={onClick}
      className={`px-3 py-2 text-[12.5px] text-left transition
        ${active ? "bg-white/[0.10] text-paper-50" : "bg-ink-800 text-ink-300 hover:bg-white/[0.04] hover:text-paper-100"}
        ${asLabel ? "cursor-default pointer-events-none opacity-70" : ""}`}
    >
      {children}
    </button>
  );
}

function RoleBadge({ rolltyp }){
  const styles = {
    "Admin":         "bg-accent/20 text-accent-soft",
    "Byrå":          "bg-white/[0.08] text-paper-300",
    "Läsbehörighet": "bg-white/[0.05] text-ink-400",
  };
  return (
    <span className={`text-[9.5px] tracking-wider uppercase px-1.5 py-[1px] rounded ${styles[rolltyp] || styles["Läsbehörighet"]}`}>{rolltyp}</span>
  );
}

function MarketBtn({ active, onClick, flag, label, sub }){
  return (
    <button
      onClick={onClick}
      className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition relative
        ${active ? "bg-white/[0.07] text-paper-50" : "text-ink-400 hover:bg-white/[0.03] hover:text-paper-100"}`}
    >
      <span>{flag}</span>
      <span className="flex-1">
        <span className="block text-[14px] leading-tight">{label}</span>
        <span className="block text-[11px] text-ink-400 leading-tight mt-0.5">{sub}</span>
      </span>
      {active && <span className="w-1.5 h-1.5 rounded-full bg-accent-soft"></span>}
    </button>
  );
}

// ----- Top bar -----
function Topbar({ title, subtitle, market, periodLabel, right }){
  return (
    <div className="flex items-end justify-between gap-6 mb-7">
      <div>
        <div className="flex items-center gap-2 mb-1.5">
          <MarketTag market={market}/>
          <span className="text-ink-400 text-xs">·</span>
          <span className="text-xs text-ink-500 num">{periodLabel}</span>
        </div>
        <h1 className="display text-[34px] leading-[1.05] text-ink-900">{title}</h1>
        {subtitle && <p className="text-ink-500 text-sm mt-1.5 max-w-xl">{subtitle}</p>}
      </div>
      {right && <div className="shrink-0">{right}</div>}
    </div>
  );
}

// ----- Tooltip for recharts -----
function ChartTooltip({ active, payload, label, market, valueFormatter }){
  if(!active || !payload || !payload.length) return null;
  return (
    <div className="bg-ink-900 text-paper-100 rounded-lg px-3 py-2 text-xs shadow-lg border border-white/5">
      <div className="text-ink-400 mb-1 num">{label}</div>
      {payload.map((p,i) => (
        <div key={i} className="flex items-center gap-2 num">
          <span className="w-2 h-2 rounded-full" style={{ background: p.color }}></span>
          <span className="text-paper-100">{p.name}:</span>
          <span className="font-medium ml-auto">{valueFormatter ? valueFormatter(p.value) : fmtNum(p.value)}</span>
        </div>
      ))}
    </div>
  );
}

// ----- Status pill / dropdown -----
const STATUS_STYLE = {
  "Konverterad":             "bg-accent-soft text-accent-ink border-accent/20",
  "Informationsförfrågan":   "bg-amber-50 text-amber-800 border-amber-200",
  "Avböjde pris":            "bg-rose-50 text-rose-800 border-rose-200",
  "Ej svarat":               "bg-paper-100 text-ink-500 border-paper-300",
  "Pågående":                "bg-sky-50 text-sky-800 border-sky-200",
};

function StatusPill({ status, onChange }){
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(()=>{
    function close(e){ if(ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener("mousedown", close);
    return ()=>document.removeEventListener("mousedown", close);
  },[]);
  return (
    <div className="relative inline-block" ref={ref}>
      <button
        onClick={(e)=>{ e.stopPropagation(); setOpen(o=>!o); }}
        className={`inline-flex items-center gap-1.5 text-[12px] px-2 py-0.5 rounded-full border ${STATUS_STYLE[status]} hover:opacity-90`}
      >
        <span className="w-1.5 h-1.5 rounded-full bg-current opacity-70"></span>
        {status}
        <svg width="9" height="9" viewBox="0 0 10 6" className="opacity-60"><path d="M1 1l4 4 4-4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round"/></svg>
      </button>
      {open && (
        <div className="absolute z-20 left-0 mt-1 bg-white border border-paper-200 rounded-lg shadow-lg overflow-hidden min-w-[200px]" onClick={e=>e.stopPropagation()}>
          {STATUSAR.map(s => (
            <button key={s}
              onClick={()=>{ onChange(s); setOpen(false); }}
              className={`w-full text-left px-3 py-2 text-[13px] hover:bg-paper-100 flex items-center gap-2 ${s===status?"bg-paper-50":""}`}>
              <span className={`w-1.5 h-1.5 rounded-full ${STATUS_STYLE[s].split(" ")[0]}`}></span>
              {s}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ----- Section card -----
function Card({ title, subtitle, right, children, className="" }){
  return (
    <section className={`bg-white border border-paper-200 rounded-xl ${className}`}>
      {(title || right) && (
        <header className="flex items-end justify-between px-5 pt-5 pb-3 gap-4">
          <div>
            {title && <h2 className="display text-[20px] text-ink-900 leading-tight">{title}</h2>}
            {subtitle && <p className="text-xs text-ink-500 mt-1">{subtitle}</p>}
          </div>
          {right}
        </header>
      )}
      <div className="px-5 pb-5 pt-1">
        {children}
      </div>
    </section>
  );
}

// ----- Empty state -----
function Empty({ children }){
  return <div className="text-sm text-ink-500 italic py-10 text-center">{children}</div>;
}

// ----- Button -----
function Btn({ children, onClick, variant="primary", size="md", className="", type="button" }){
  const base = "inline-flex items-center justify-center gap-2 rounded-lg font-medium transition";
  const sz = size==="sm" ? "text-xs px-3 py-1.5" : "text-sm px-4 py-2";
  const v = variant==="primary" ? "bg-ink-900 text-paper-50 hover:bg-ink-800"
         : variant==="accent"  ? "bg-accent text-paper-50 hover:bg-accent-ink"
         : variant==="ghost"   ? "text-ink-700 hover:bg-paper-200/60"
         : "border border-paper-300 text-ink-700 hover:bg-paper-100";
  return <button type={type} onClick={onClick} className={`${base} ${sz} ${v} ${className}`}>{children}</button>;
}

// ----- Source / Confidence badges -----
const SOURCE_STYLE = {
  "Google Ads":          { bg:"bg-[#fef3e8]", text:"text-[#9b5a16]", dot:"bg-[#e89548]" },
  "Google Organic":      { bg:"bg-[#e6efe8]", text:"text-[#2a6b3a]", dot:"bg-[#3a8a5a]" },
  "Bing Organic":        { bg:"bg-[#e8eef2]", text:"text-[#34556e]", dot:"bg-[#4f7997]" },
  "Direct / okänd":      { bg:"bg-paper-100", text:"text-ink-600",   dot:"bg-ink-400" },
  "Referral":            { bg:"bg-[#ece6f2]", text:"text-[#5b3e85]", dot:"bg-[#7d59ad]" },
  "Manuell":             { bg:"bg-[#f1ebe2]", text:"text-[#7a5a30]", dot:"bg-[#a8824a]" },
  "Okänd / kontaktsida": { bg:"bg-[#fbe9ea]", text:"text-[#94353a]", dot:"bg-[#c25a5f]" },
  "Okänd":               { bg:"bg-paper-100", text:"text-ink-500",   dot:"bg-ink-300" },
};
function SourceBadge({ source, size="md" }){
  const s = SOURCE_STYLE[source] || SOURCE_STYLE["Okänd"];
  const cls = size === "sm" ? "text-[10.5px] px-1.5 py-0.5" : "text-[11.5px] px-2 py-0.5";
  return (
    <span className={`inline-flex items-center gap-1.5 rounded-full ${cls} ${s.bg} ${s.text} whitespace-nowrap`}>
      <span className={`w-1.5 h-1.5 rounded-full ${s.dot}`}></span>{source}
    </span>
  );
}

const CONFIDENCE_STYLE = {
  "Hög":   { bg:"bg-accent-soft", text:"text-accent-ink", bars:3 },
  "Medel": { bg:"bg-amber-50",    text:"text-amber-800",  bars:2 },
  "Låg":   { bg:"bg-rose-50",     text:"text-rose-800",   bars:1 },
  "Okänd": { bg:"bg-paper-100",   text:"text-ink-500",    bars:0 },
};
function ConfidenceBadge({ level, size="md" }){
  const s = CONFIDENCE_STYLE[level] || CONFIDENCE_STYLE["Okänd"];
  const cls = size === "sm" ? "text-[10.5px] px-1.5 py-0.5 gap-1" : "text-[11.5px] px-2 py-0.5 gap-1.5";
  return (
    <span className={`inline-flex items-center rounded-full ${cls} ${s.bg} ${s.text} whitespace-nowrap`}>
      <span className="inline-flex items-end gap-[1px] h-3">
        <span className={`w-[2px] h-[5px] rounded-sm ${s.bars >= 1 ? "bg-current" : "bg-current opacity-25"}`}></span>
        <span className={`w-[2px] h-[8px] rounded-sm ${s.bars >= 2 ? "bg-current" : "bg-current opacity-25"}`}></span>
        <span className={`w-[2px] h-[11px] rounded-sm ${s.bars >= 3 ? "bg-current" : "bg-current opacity-25"}`}></span>
      </span>
      {level}
    </span>
  );
}

// expose
Object.assign(window, {
  fmtNum, fmtMoney, fmtPct,
  KpiCard, Arrow, FlagSE, FlagNO, FlagBoth, MarketTag,
  Sidebar, Topbar, ChartTooltip, StatusPill, Card, Empty, Btn,
  SourceBadge, ConfidenceBadge, SOURCE_STYLE, CONFIDENCE_STYLE,
});
