// Team page — workspace-level team analytics with cost-centre allocation

function Team(){
  const [tab, setTab] = useState("overview");   // overview | costcentres | activity
  const total = 351.75;
  const requests = 6735;
  const budget = 500;
  const utilisation = total/budget;
  const trajectory = (total/PERIOD.daysElapsed) * PERIOD.daysTotal;

  return (
    <div data-screen-label="05 Team" style={{ padding:"24px 28px 40px", maxWidth:1380, margin:"0 auto", display:"flex", flexDirection:"column", gap:20 }}>
      {/* Header */}
      <header style={{ display:"flex", alignItems:"flex-end", justifyContent:"space-between", gap:16 }}>
        <div>
          <div style={{ fontSize:11, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600, marginBottom:6 }}>Workspace</div>
          <h1 style={{ margin:0, fontSize:28, fontWeight:600, letterSpacing:-0.5, color:"var(--fg-0)" }}>Team</h1>
          <div style={{ color:"var(--fg-2)", fontSize:13, marginTop:5 }}>Per-developer spend & activity · roll up by team, manager, or project</div>
        </div>
        <div style={{ display:"flex", gap:8 }}>
          <PeriodSwitcher/>
          <button style={btnSecondary()}><Icon name="user" size={13}/> Invite member</button>
          <button style={btnPrimary()}><Icon name="plus" size={14}/> New team</button>
        </div>
      </header>

      {/* Teams empty/intro state — important because workspace has 0 teams */}
      <TeamsEmptyState/>

      {/* KPI strip */}
      <div className="card" style={{ padding:0, display:"grid", gridTemplateColumns:"1.3fr 1fr 1fr 1.2fr", overflow:"hidden" }}>
        <BudgetKPI total={total} budget={budget} utilisation={utilisation} trajectory={trajectory}/>
        <TeamKPI label="Requests"        value={requests.toLocaleString()} sub={`${Math.round(requests/PERIOD.daysElapsed)}/day avg`} icon="activity" delta={0.521} border/>
        <TeamKPI label="Members active"  value="2" sub="of 2 invited" icon="user" border subnote="0 pending invites"/>
        <TopSpenderKPI border/>
      </div>

      {/* Tabs */}
      <div style={{ display:"flex", alignItems:"center", borderBottom:"1px solid var(--line-1)", marginTop:-4 }}>
        {[
          { id:"overview",    label:"Overview" },
          { id:"costcentres", label:"Cost centres",    badge:"new" },
          { id:"activity",    label:"Activity log",    count:12 },
        ].map(t => {
          const active = tab === t.id;
          return (
            <button key={t.id} onClick={()=>setTab(t.id)} style={{
              appearance:"none", background:"transparent", border:"none",
              padding:"10px 14px",
              fontSize:13, fontWeight: active?500:400,
              color: active?"var(--fg-0)":"var(--fg-2)",
              borderBottom: active?"2px solid var(--accent)":"2px solid transparent",
              marginBottom:-1, cursor:"pointer",
              display:"inline-flex", alignItems:"center", gap:8,
            }}>
              {t.label}
              {t.count != null && <span className="mono" style={{ fontSize:10.5, color:"var(--fg-3)" }}>{t.count}</span>}
              {t.badge && <span className="badge badge--accent" style={{ fontSize:9.5, padding:"1px 6px" }}>{t.badge}</span>}
            </button>
          );
        })}
      </div>

      {tab === "overview" && <TeamOverviewTab/>}
      {tab === "costcentres" && <CostCentresTab total={total}/>}
      {tab === "activity" && <ActivityLogTab/>}
    </div>
  );
}

// ── Empty-state banner — when no teams exist ─────────────
function TeamsEmptyState(){
  const [dismissed, setDismissed] = useState(false);
  if (dismissed) return null;
  return (
    <div className="card" style={{
      padding:"18px 22px",
      borderColor:"var(--accent-line)",
      background:"linear-gradient(135deg, rgba(91,80,238,0.05), transparent 70%)",
      display:"flex", alignItems:"center", gap:18,
    }}>
      <div style={{ width:42, height:42, borderRadius:10, background:"#fff", color:"var(--accent)", display:"flex", alignItems:"center", justifyContent:"center", border:"1px solid var(--accent-line)" }}>
        <Icon name="layers" size={18}/>
      </div>
      <div style={{ flex:1 }}>
        <div style={{ fontSize:13, fontWeight:600, color:"var(--fg-0)" }}>You don't have any teams yet</div>
        <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:3, lineHeight:1.5 }}>
          Group projects and members into teams to allocate budgets and roll up cost reports. Useful when you have ≥3 active client engagements or want billable-vs-internal separation.
        </div>
      </div>
      <button style={btnSecondary()}>Learn more</button>
      <button style={btnPrimary()}><Icon name="plus" size={13}/> Create first team</button>
      <button onClick={()=>setDismissed(true)} style={{ background:"none", border:"none", color:"var(--fg-3)", padding:6, cursor:"pointer" }}><Icon name="check" size={14}/></button>
    </div>
  );
}

// ── KPI variants ─────────────────────────────────────────
function BudgetKPI({ total, budget, utilisation, trajectory }){
  const dayPct = PERIOD.daysElapsed/PERIOD.daysTotal;
  const onTrack = trajectory <= budget * 1.05;
  return (
    <div style={{ padding:"18px 22px", borderRight:"1px solid var(--line-1)" }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:8 }}>
        <span style={{ display:"inline-flex", alignItems:"center", gap:7, fontSize:10.5, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600 }}>
          <Icon name="wallet" size={12.5} stroke="var(--fg-3)"/>Spend vs budget
        </span>
        <span className="badge badge--ghost" style={{ fontSize:10 }}>Monthly</span>
      </div>
      <div style={{ display:"flex", alignItems:"baseline", gap:10 }}>
        <Money value={total} size="lg"/>
        <span style={{ fontSize:13, color:"var(--fg-2)" }} className="mono">/ £{budget.toFixed(0)}</span>
        <span className={onTrack ? "badge badge--pos" : "badge badge--warn"} style={{ fontSize:10 }}>{onTrack ? "on track" : "over pace"}</span>
      </div>
      {/* Budget bar with day-progress overlay */}
      <div style={{ marginTop:11, position:"relative" }}>
        <div style={{ position:"relative", height:9, background:"var(--bg-3)", borderRadius:99, overflow:"hidden" }}>
          <div style={{ position:"absolute", left:0, top:0, bottom:0, width:Math.min(100,utilisation*100)+"%", background:"linear-gradient(90deg, var(--accent), var(--accent-2))", borderRadius:99 }}/>
          {/* Day progress marker */}
          <div style={{ position:"absolute", left:(dayPct*100)+"%", top:-3, bottom:-3, width:2, background:"var(--fg-0)" }}/>
        </div>
        <div style={{ display:"flex", justifyContent:"space-between", marginTop:5, fontSize:10.5, color:"var(--fg-3)" }}>
          <span className="mono">{(utilisation*100).toFixed(1)}% used</span>
          <span>day <span className="mono" style={{ color:"var(--fg-1)" }}>{PERIOD.daysElapsed}</span> of {PERIOD.daysTotal} · pace <span className="mono" style={{ color: onTrack?"var(--pos)":"var(--warn)" }}>{fmtGBP(trajectory)}</span></span>
        </div>
      </div>
    </div>
  );
}

function TeamKPI({ label, value, sub, icon, delta, border, subnote }){
  return (
    <div style={{ padding:"18px 22px", borderRight:"1px solid var(--line-1)" }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:8 }}>
        <span style={{ display:"inline-flex", alignItems:"center", gap:7, fontSize:10.5, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600 }}>
          <Icon name={icon} size={12.5} stroke="var(--fg-3)"/>{label}
        </span>
      </div>
      <div style={{ display:"flex", alignItems:"baseline", gap:8 }}>
        <span className="mono" style={{ fontSize:22, fontWeight:600, color:"var(--fg-0)", letterSpacing:-0.3 }}>{value}</span>
        {delta != null && <Delta pct={delta}/>}
      </div>
      <div style={{ fontSize:11, color:"var(--fg-2)", marginTop:5 }}>{sub}</div>
      {subnote && <div style={{ fontSize:10.5, color:"var(--fg-3)", marginTop:3 }}>{subnote}</div>}
    </div>
  );
}

function TopSpenderKPI({ border }){
  return (
    <div style={{ padding:"18px 22px" }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:8 }}>
        <span style={{ display:"inline-flex", alignItems:"center", gap:7, fontSize:10.5, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600 }}>
          <Icon name="starOn" size={12.5} stroke="var(--accent)"/>Top spender
        </span>
      </div>
      <div style={{ display:"flex", alignItems:"center", gap:10 }}>
        <Avatar seed="vk" name="Alex Pemberton" size={32}/>
        <div style={{ display:"flex", flexDirection:"column" }}>
          <span style={{ fontSize:13.5, fontWeight:500, color:"var(--fg-0)" }}>Alex Pemberton</span>
          <span style={{ fontSize:10.5, color:"var(--fg-3)" }} className="mono">alex@meridianstudio.io</span>
        </div>
      </div>
      <div style={{ marginTop:8, display:"flex", alignItems:"baseline", gap:8 }}>
        <span className="mono" style={{ fontSize:15, fontWeight:600, color:"var(--fg-0)" }}>£244.53</span>
        <span style={{ fontSize:11, color:"var(--fg-2)" }}>· 88% of total</span>
      </div>
    </div>
  );
}

// ── Tab: Overview ────────────────────────────────────────
function TeamOverviewTab(){
  return (
    <>
      <div style={{ display:"grid", gridTemplateColumns:"minmax(0, 1fr) 380px", gap:18 }}>
        {/* Left main */}
        <div style={{ display:"flex", flexDirection:"column", gap:18 }}>
          <SpendByMemberChart/>
          <SpendByProjectCard/>
          <RecentActivityCard/>
        </div>
        {/* Right sidebar */}
        <aside style={{ display:"flex", flexDirection:"column", gap:14 }}>
          <ContributorsCard/>
          <ModelMixCard/>
          <TeamHealthCard/>
        </aside>
      </div>
    </>
  );
}

// Spend by member — stacked area, one band per active member
function SpendByMemberChart(){
  const ref = useRef(null);
  const w = useWidth(ref);
  const h = 220;
  const padL = 50, padR = 18, padT = 14, padB = 30;
  const innerW = Math.max(100, w - padL - padR);
  const innerH = h - padT - padB;
  const n = DAILY.length;

  // Two members: split daily total
  const data = DAILY.map((d,i) => ({
    d: d.d,
    vk: d.cost * 0.88,
    sm: d.cost * 0.12,
    total: d.cost,
  }));
  const members = [
    { id:"vk", name:"Alex Pemberton", color:"var(--accent)" },
    { id:"sm", name:"Jamie Lowe",     color:"var(--p-google)" },
  ];

  const max = Math.max(...data.map(d=>d.total))*1.18;
  const x = i => (i/(n-1))*innerW;
  const y = v => innerH - (v/max)*innerH;

  function stackPath(idx){
    const upper = data.map((d,i) => {
      const top = members.slice(0,idx+1).reduce((s,M)=>s+(d[M.id]||0),0);
      return [x(i), y(top)];
    });
    const lower = data.map((d,i) => {
      const bot = members.slice(0,idx).reduce((s,M)=>s+(d[M.id]||0),0);
      return [x(i), y(bot)];
    }).reverse();
    const all = [...upper, ...lower];
    return "M" + all.map(([px,py])=>`${px.toFixed(1)},${py.toFixed(1)}`).join(" L") + " Z";
  }

  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(t => ({ v: t*max, y: y(t*max) }));

  return (
    <section className="card" style={{ padding:"20px 22px" }}>
      <SectionHeader
        title="Spend by member"
        subtitle="Daily stacked spend · last 11 days"
        action={
          <div style={{ display:"flex", gap:12 }}>
            {members.map(M => (
              <span key={M.id} style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:11.5, color:"var(--fg-2)" }}>
                <span style={{ width:9, height:9, borderRadius:2, background:M.color }}/>{M.name}
              </span>
            ))}
          </div>
        }
      />
      <div ref={ref} style={{ position:"relative", width:"100%", height:h }}>
        <svg width={w} height={h}>
          {yTicks.map((t,i) => (
            <g key={i}>
              <line x1={padL} x2={padL+innerW} y1={padT+t.y} y2={padT+t.y} stroke="var(--line-1)" strokeDasharray={i===0?"":"2 4"}/>
              <text x={padL-10} y={padT+t.y+3} textAnchor="end" fontSize="10" fontFamily="var(--font-mono)" fill="var(--fg-3)">£{t.v.toFixed(t.v<1?2:0)}</text>
            </g>
          ))}
          <g transform={`translate(${padL},${padT})`}>
            {members.map((M, i) => (
              <path key={M.id} d={stackPath(i)} fill={M.color} fillOpacity="0.85" stroke={M.color} strokeWidth="0.5"/>
            ))}
          </g>
          {DAILY.map((d,i) => (i===0 || i===n-1 || i%2===0) && (
            <text key={i} x={padL+x(i)} y={h-10} textAnchor="middle" fontSize="10" fontFamily="var(--font-mono)" fill="var(--fg-3)">{d.d} May</text>
          ))}
        </svg>
      </div>
    </section>
  );
}

function SpendByProjectCard(){
  const total = PROJECTS.reduce((s,p)=>s+p.spend,0);
  const top = [...PROJECTS].sort((a,b)=>b.spend-a.spend).slice(0,6);
  const max = top[0].spend;
  return (
    <section className="card" style={{ padding:"20px 22px" }}>
      <SectionHeader
        title="Spend by project"
        subtitle="Top 6 projects · share of period"
        action={<button style={btnSubtle()}>View all <Icon name="arrow" size={11}/></button>}
      />
      <div style={{ display:"flex", flexDirection:"column", gap:11 }}>
        {top.map(p => {
          const series = makeSeries(p.spend, 11, p.shape);
          return (
            <div key={p.slug} style={{ display:"grid", gridTemplateColumns:"160px 1fr 70px 60px 80px", gap:14, alignItems:"center" }}>
              <div style={{ display:"flex", alignItems:"center", gap:8, minWidth:0 }}>
                <span style={{ width:8, height:8, borderRadius:2, background: PROVIDERS[MODELS[p.primaryModel].provider].color, flexShrink:0 }}/>
                <span style={{ fontSize:13, fontWeight:500, color:"var(--fg-0)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{p.name}</span>
              </div>
              <div className="bar-track" style={{ height:7 }}>
                <div className="bar-fill" style={{ width: (p.spend/max*100)+"%", height:"100%" }}/>
              </div>
              <span className="mono" style={{ fontSize:12, color:"var(--fg-0)", fontWeight:500, textAlign:"right" }}>{fmtGBP(p.spend)}</span>
              <span className="mono" style={{ fontSize:11, color:"var(--fg-2)", textAlign:"right" }}>{(p.spend/total*100).toFixed(0)}%</span>
              <Sparkline data={series} w={70} h={16} color="var(--accent)" fill={false}/>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function RecentActivityCard(){
  const acts = [
    { icon:"user",      tone:"pos",    actor:"Sam Chen",      verb:"joined the workspace as", target:"Editor",        ago:"2h ago" },
    { icon:"folder",    tone:"accent", actor:"Jamie Lowe",      verb:"created project",          target:"Proposal Writer", ago:"Yesterday" },
    { icon:"sparkles",  tone:"accent", actor:"Optimisation",     verb:"applied to",               target:"contract-ai",   detail:"saved £12.40 / mo", ago:"2 days ago" },
    { icon:"download",  tone:"neutral",actor:"Alex Pemberton",  verb:"generated report",         target:"April 2026 Monthly summary", ago:"2 days ago" },
    { icon:"alert",     tone:"warn",   actor:"Budget alert",     verb:"threshold reached on",     target:"contract-ai", detail:"85% of £25 limit", ago:"3 days ago" },
    { icon:"ext",       tone:"warn",   actor:"finance@acme.co",  verb:"downloaded shared report", target:"Q1 2026 — Client invoice", ago:"4 days ago" },
  ];
  const tones = {
    pos:    { fg:"var(--pos)",    bg:"var(--pos-soft)",    line:"rgba(15,138,79,0.22)" },
    accent: { fg:"var(--accent)", bg:"var(--accent-soft)", line:"var(--accent-line)" },
    warn:   { fg:"var(--warn)",   bg:"var(--warn-soft)",   line:"rgba(185,113,13,0.22)" },
    neutral:{ fg:"var(--fg-2)",   bg:"var(--bg-3)",        line:"var(--line-1)" },
  };
  return (
    <section className="card" style={{ padding:0, overflow:"hidden" }}>
      <div style={{ padding:"16px 22px", borderBottom:"1px solid var(--line-1)", display:"flex", alignItems:"center", justifyContent:"space-between" }}>
        <div>
          <h2 style={{ margin:0, fontSize:14, fontWeight:600 }}>Recent team activity</h2>
          <div style={{ fontSize:11.5, color:"var(--fg-2)", marginTop:3 }}>Cross-member events · last 7 days</div>
        </div>
        <button style={btnGhost()}>Full audit log <Icon name="arrow" size={11}/></button>
      </div>
      <div>
        {acts.map((a,i) => {
          const t = tones[a.tone];
          return (
            <div key={i} style={{ padding:"12px 22px", borderBottom: i<acts.length-1?"1px solid var(--line-1)":"none", display:"flex", alignItems:"center", gap:12 }}>
              <div style={{ width:28, height:28, borderRadius:8, background:t.bg, color:t.fg, display:"flex", alignItems:"center", justifyContent:"center", border:"1px solid "+t.line, flexShrink:0 }}>
                <Icon name={a.icon} size={13}/>
              </div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:12.5, color:"var(--fg-1)" }}>
                  <span style={{ color:"var(--fg-0)", fontWeight:500 }}>{a.actor}</span>{" "}
                  {a.verb}{" "}
                  <span style={{ color:"var(--fg-0)", fontWeight:500 }}>{a.target}</span>
                </div>
                {a.detail && <div style={{ fontSize:11, color:"var(--fg-3)", marginTop:2 }}>{a.detail}</div>}
              </div>
              <span className="mono" style={{ fontSize:11, color:"var(--fg-3)" }}>{a.ago}</span>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function ContributorsCard(){
  const members = [
    { id:"vk", name:"Alex Pemberton", email:"alex@meridianstudio.io", spend:244.53, requests:5980, share:0.88, role:"Owner" },
    { id:"sm", name:"Jamie Lowe",      email:"jamie@meridianstudio.io",   spend:33.35,  requests:755,  share:0.12, role:"Editor" },
  ];
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:12 }}>
        <h3 style={{ margin:0, fontSize:12.5, fontWeight:600 }}>Top contributors</h3>
        <span style={{ fontSize:10.5, color:"var(--fg-3)" }}>2 of 2</span>
      </div>
      <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
        {members.map((m,i) => (
          <div key={m.id}>
            <div style={{ display:"flex", alignItems:"center", gap:10 }}>
              <div style={{ position:"relative" }}>
                <Avatar seed={m.id} name={m.name} size={30}/>
                {i===0 && <span style={{ position:"absolute", bottom:-3, right:-3, width:14, height:14, borderRadius:"50%", background:"var(--accent)", color:"#fff", fontSize:8, fontWeight:700, display:"flex", alignItems:"center", justifyContent:"center", border:"2px solid #fff" }}>1</span>}
              </div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:12.5, fontWeight:500, color:"var(--fg-0)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{m.name}</div>
                <div style={{ fontSize:10.5, color:"var(--fg-3)" }}>{m.role}</div>
              </div>
              <div style={{ textAlign:"right" }}>
                <div className="mono" style={{ fontSize:12.5, color:"var(--fg-0)", fontWeight:600 }}>{fmtGBP(m.spend)}</div>
                <div className="mono" style={{ fontSize:10, color:"var(--fg-3)" }}>{m.requests.toLocaleString()} req</div>
              </div>
            </div>
            <div style={{ marginTop:6, display:"flex", alignItems:"center", gap:7 }}>
              <div className="bar-track" style={{ flex:1, height:4 }}>
                <div className="bar-fill" style={{ width:(m.share*100)+"%", height:"100%" }}/>
              </div>
              <span className="mono" style={{ fontSize:10, color:"var(--fg-3)", minWidth:32, textAlign:"right" }}>{(m.share*100).toFixed(0)}%</span>
            </div>
          </div>
        ))}
      </div>
      <div style={{ marginTop:14, paddingTop:12, borderTop:"1px solid var(--line-1)" }}>
        <button style={{ ...btnGhost(), width:"100%", justifyContent:"center" }}>View all members <Icon name="arrow" size={11}/></button>
      </div>
    </div>
  );
}

function ModelMixCard(){
  const mix = [
    { model:"claude-opus-4-7",   share:0.99,  cost:348.20 },
    { model:"claude-haiku-4-5",  share:0.003, cost:0.97 },
    { model:"claude-sonnet-4-6", share:0.007, cost:2.55 },
    { model:"gemini-2-flash",    share:0.00009, cost:0.03 },
  ];
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <h3 style={{ margin:"0 0 10px", fontSize:12.5, fontWeight:600 }}>Team model mix</h3>
      {/* Stacked horizontal bar */}
      <div style={{ display:"flex", height:10, borderRadius:99, overflow:"hidden", background:"var(--bg-3)", marginBottom:10 }}>
        {mix.map(m => {
          const meta = MODELS[m.model];
          return <div key={m.model} style={{ width:Math.max(1, m.share*100)+"%", background:PROVIDERS[meta.provider].color, opacity:0.75+m.share*0.25 }}/>;
        })}
      </div>
      <div style={{ display:"flex", flexDirection:"column", gap:7 }}>
        {mix.map(m => {
          const meta = MODELS[m.model];
          return (
            <div key={m.model} style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", fontSize:11.5 }}>
              <span style={{ display:"inline-flex", alignItems:"center", gap:6 }}>
                <span style={{ width:6, height:6, borderRadius:2, background:PROVIDERS[meta.provider].color }}/>
                <span className="mono" style={{ color:"var(--fg-1)" }}>{meta.short}</span>
              </span>
              <span style={{ display:"inline-flex", gap:8 }}>
                <span className="mono" style={{ color:"var(--fg-0)" }}>£{m.cost.toFixed(2)}</span>
                <span className="mono" style={{ color:"var(--fg-3)", minWidth:36, textAlign:"right" }}>{(m.share*100).toFixed(m.share<0.01?2:1)}%</span>
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function TeamHealthCard(){
  const checks = [
    { ok:true,  label:"All members assigned to projects" },
    { ok:false, label:"525 requests unattributed",         hint:"Tag with .haltonrc" },
    { ok:true,  label:"No exceeded budgets",               hint:"5% headroom" },
    { ok:false, label:"1 cost centre missing manager",     hint:"Assign in Settings" },
  ];
  const okCount = checks.filter(c => c.ok).length;
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:10 }}>
        <h3 style={{ margin:0, fontSize:12.5, fontWeight:600 }}>Team health</h3>
        <span className="mono" style={{ fontSize:11, color: okCount===checks.length ? "var(--pos)" : "var(--warn)" }}>{okCount}/{checks.length}</span>
      </div>
      <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
        {checks.map((c,i) => (
          <div key={i} style={{ display:"flex", alignItems:"flex-start", gap:8 }}>
            <div style={{ width:14, height:14, borderRadius:"50%", background: c.ok?"var(--pos-soft)":"var(--warn-soft)", color: c.ok?"var(--pos)":"var(--warn)", display:"flex", alignItems:"center", justifyContent:"center", marginTop:2, flexShrink:0 }}>
              <Icon name={c.ok?"check":"alert"} size={9}/>
            </div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:11.5, color:"var(--fg-0)" }}>{c.label}</div>
              {c.hint && <div style={{ fontSize:10.5, color:"var(--fg-3)", marginTop:1 }}>{c.hint}</div>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Tab: Cost centres ────────────────────────────────────
function CostCentresTab({ total }){
  const centres = [
    { id:"internal", name:"Internal ops",      budget:200, spend:147.65, projects:["code-reviewer","contract-ai","invoice-assistant","meeting-notes","research-agent"], manager:"Alex", color:"var(--accent)" },
    { id:"clients",  name:"Client work",       budget:200, spend:5.96,   projects:["foxgrove-studio","arcline-systems","research-agent"], manager:"Alex", color:"var(--p-anthropic)" },
    { id:"misc",     name:"Misc / unattributed", budget:100, spend:120.60,projects:["misc","unattributed","mac:com.docker.docker"], manager:"unassigned", color:"var(--warn)" },
  ];
  const totalBudget = centres.reduce((s,c)=>s+c.budget,0);
  return (
    <div style={{ display:"flex", flexDirection:"column", gap:18 }}>
      {/* Stacked allocation bar */}
      <section className="card" style={{ padding:"20px 22px" }}>
        <SectionHeader
          title="Budget allocation"
          subtitle={`Total budget £${totalBudget} · spend £${total.toFixed(2)}`}
          action={<button style={btnSecondary()}><Icon name="plus" size={13}/> New cost centre</button>}
        />
        <div style={{ display:"flex", height:36, borderRadius:8, overflow:"hidden", border:"1px solid var(--line-1)" }}>
          {centres.map(c => (
            <div key={c.id} style={{ flex: c.budget, background: c.color, opacity:0.85, display:"flex", alignItems:"center", justifyContent:"center", color:"#fff", fontSize:11, fontWeight:500, position:"relative" }}>
              <span>{c.name}</span>
              <span className="mono" style={{ position:"absolute", right:8, top:2, fontSize:9.5, opacity:0.85 }}>£{c.budget}</span>
            </div>
          ))}
        </div>

        <div style={{ marginTop:18, display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap:14 }}>
          {centres.map(c => {
            const util = c.spend / c.budget;
            const over = util > 1;
            return (
              <div key={c.id} className="card" style={{ padding:"14px 16px", border:"1px solid var(--line-1)", borderRadius:8, background:"#fff" }}>
                <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:8 }}>
                  <span style={{ display:"inline-flex", alignItems:"center", gap:7, fontSize:12.5, fontWeight:500 }}>
                    <span style={{ width:9, height:9, borderRadius:3, background:c.color }}/>{c.name}
                  </span>
                  <span className={over ? "badge badge--neg" : util > 0.85 ? "badge badge--warn" : "badge badge--pos"} style={{ fontSize:10 }}>
                    {over ? "over" : util > 0.85 ? "watch" : "ok"}
                  </span>
                </div>
                <div style={{ display:"flex", alignItems:"baseline", gap:6, marginBottom:6 }}>
                  <Money value={c.spend} size="sm"/>
                  <span style={{ fontSize:11, color:"var(--fg-2)" }} className="mono">/ £{c.budget}</span>
                </div>
                <div className="bar-track" style={{ height:5 }}>
                  <div style={{ position:"absolute", left:0, top:0, bottom:0, width: Math.min(100, util*100)+"%", background: over ? "var(--neg)" : util > 0.85 ? "var(--warn)" : "var(--pos)", borderRadius:99 }}/>
                </div>
                <div style={{ marginTop:8, fontSize:10.5, color:"var(--fg-3)", display:"flex", justifyContent:"space-between" }}>
                  <span>{c.projects.length} project{c.projects.length!==1?"s":""}</span>
                  <span>manager: <span style={{ color:"var(--fg-2)" }}>{c.manager}</span></span>
                </div>
              </div>
            );
          })}
        </div>
      </section>

      {/* Allocation table */}
      <section className="card" style={{ padding:0, overflow:"hidden" }}>
        <div style={{ padding:"16px 22px", borderBottom:"1px solid var(--line-1)" }}>
          <h2 style={{ margin:0, fontSize:14, fontWeight:600 }}>Cost centres</h2>
          <div style={{ fontSize:11.5, color:"var(--fg-2)", marginTop:3 }}>Allocate projects to budgets and managers</div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ paddingLeft:22 }}>Centre</th>
              <th>Projects</th>
              <th>Manager</th>
              <th className="right">Budget</th>
              <th className="right">Spend</th>
              <th className="right">Utilisation</th>
              <th style={{ paddingRight:22 }}>Status</th>
            </tr>
          </thead>
          <tbody>
            {centres.map(c => {
              const util = c.spend / c.budget;
              const over = util > 1;
              return (
                <tr key={c.id} className="clickable">
                  <td style={{ paddingLeft:22 }}>
                    <div style={{ display:"flex", alignItems:"center", gap:9 }}>
                      <span style={{ width:9, height:9, borderRadius:3, background:c.color, flexShrink:0 }}/>
                      <span style={{ fontWeight:500, color:"var(--fg-0)" }}>{c.name}</span>
                    </div>
                  </td>
                  <td><span className="mono" style={{ fontSize:11.5, color:"var(--fg-2)" }}>{c.projects.length}</span></td>
                  <td>{c.manager==="unassigned" ? <span style={{ color:"var(--warn)", fontSize:12 }}>Unassigned</span> : <span style={{ color:"var(--fg-0)", fontSize:12 }}>{c.manager}</span>}</td>
                  <td className="right mono" style={{ color:"var(--fg-0)" }}>£{c.budget}</td>
                  <td className="right"><Money value={c.spend} size="sm"/></td>
                  <td className="right">
                    <div style={{ display:"inline-flex", alignItems:"center", gap:8 }}>
                      <div style={{ width:60, height:5, background:"var(--bg-3)", borderRadius:99, position:"relative", overflow:"hidden" }}>
                        <div style={{ position:"absolute", left:0, top:0, bottom:0, width:Math.min(100,util*100)+"%", background: over?"var(--neg)":util>0.85?"var(--warn)":"var(--pos)" }}/>
                      </div>
                      <span className="mono" style={{ fontSize:11.5, color:over?"var(--neg)":util>0.85?"var(--warn)":"var(--fg-0)" }}>{(util*100).toFixed(0)}%</span>
                    </div>
                  </td>
                  <td style={{ paddingRight:22 }}>
                    <span className={over ? "badge badge--neg" : util > 0.85 ? "badge badge--warn" : "badge badge--pos"} style={{ fontSize:10 }}>
                      {over ? "over budget" : util > 0.85 ? "approaching limit" : "healthy"}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </section>

      {/* Alerts */}
      <div className="card" style={{ padding:"14px 18px", borderColor:"rgba(185,113,13,0.22)", background:"linear-gradient(180deg, var(--warn-soft), transparent 50%)", display:"flex", gap:14, alignItems:"flex-start" }}>
        <div style={{ width:32, height:32, borderRadius:8, background:"#fff", color:"var(--warn)", border:"1px solid rgba(185,113,13,0.22)", display:"flex", alignItems:"center", justifyContent:"center" }}>
          <Icon name="alert" size={15}/>
        </div>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:13, fontWeight:600, color:"var(--fg-0)" }}>Misc / unattributed exceeded its budget</div>
          <div style={{ fontSize:12, color:"var(--fg-2)", marginTop:3 }}>£120.60 of £100 (120%). 525 unattributed requests this period. Tag them with .haltonrc, then reassign to the right cost centre.</div>
        </div>
        <button style={btnSecondary()}>Reassign projects</button>
      </div>
    </div>
  );
}

// ── Tab: Activity log ────────────────────────────────────
function ActivityLogTab(){
  const events = [
    { ts:"15 May 14:32", actor:"Sam Chen",     action:"member.join",         scope:"workspace",  detail:"Joined as Editor", ip:"82.34.x.x" },
    { ts:"14 May 11:08", actor:"Jamie Lowe",     action:"project.create",      scope:"Proposal Writer",  detail:"created project", ip:"81.18.x.x" },
    { ts:"13 May 09:21", actor:"system",          action:"optimisation.apply",  scope:"contract-ai", detail:"swap 70% of Opus → Sonnet; saved £12.40 / mo", ip:"—" },
    { ts:"13 May 09:18", actor:"Alex Pemberton", action:"report.generate",     scope:"workspace",  detail:"April 2026 Monthly summary · PDF", ip:"81.18.x.x" },
    { ts:"12 May 16:44", actor:"system",          action:"budget.alert",        scope:"contract-ai", detail:"reached 85% of £25 limit", ip:"—" },
    { ts:"11 May 10:02", actor:"finance@acme.co", action:"report.download",     scope:"Q1 2026 — Client invoice", detail:"via shared link", ip:"73.92.x.x", ext:true },
    { ts:"10 May 13:15", actor:"Alex Pemberton", action:"project.archive",     scope:"thornhill-cms", detail:"engagement complete", ip:"81.18.x.x" },
  ];
  return (
    <section className="card" style={{ padding:0, overflow:"hidden" }}>
      <div style={{ padding:"14px 22px", borderBottom:"1px solid var(--line-1)", display:"flex", alignItems:"center", gap:10 }}>
        <input placeholder="Filter actor, action, scope…" style={{ flex:1, height:32, padding:"0 12px", border:"1px solid var(--line-2)", borderRadius:8, background:"#fff", fontSize:12.5, outline:"none" }}/>
        <select style={{ height:32, padding:"0 10px", border:"1px solid var(--line-2)", borderRadius:8, background:"#fff", fontSize:12.5 }}>
          <option>All actions</option>
          <option>member.*</option>
          <option>project.*</option>
          <option>report.*</option>
          <option>budget.*</option>
        </select>
        <button style={btnGhost()}><Icon name="download" size={13}/> Export</button>
      </div>
      <table className="tbl">
        <thead>
          <tr>
            <th style={{ paddingLeft:22 }}>Time</th>
            <th>Actor</th>
            <th>Action</th>
            <th>Scope</th>
            <th>Detail</th>
            <th style={{ paddingRight:22 }}>IP</th>
          </tr>
        </thead>
        <tbody>
          {events.map((e,i) => (
            <tr key={i}>
              <td className="mono" style={{ paddingLeft:22, fontSize:11.5, color:"var(--fg-2)" }}>{e.ts}</td>
              <td>
                <div style={{ display:"flex", alignItems:"center", gap:7 }}>
                  {e.actor === "system" ? (
                    <span style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:12, color:"var(--fg-2)" }}><Icon name="sparkles" size={11}/> system</span>
                  ) : e.ext ? (
                    <span style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:12, color:"var(--warn)" }}><Icon name="ext" size={11}/> {e.actor}</span>
                  ) : (
                    <><Avatar seed={e.actor} name={e.actor} size={20}/><span style={{ fontSize:12, color:"var(--fg-0)" }}>{e.actor}</span></>
                  )}
                </div>
              </td>
              <td><span className="mono" style={{ fontSize:11.5, color:"var(--fg-1)", padding:"1px 7px", background:"var(--bg-3)", borderRadius:5 }}>{e.action}</span></td>
              <td className="mono" style={{ fontSize:12, color:"var(--fg-1)" }}>{e.scope}</td>
              <td style={{ fontSize:12, color:"var(--fg-2)" }}>{e.detail}</td>
              <td className="mono" style={{ paddingRight:22, fontSize:11, color:"var(--fg-3)" }}>{e.ip}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  );
}

// ── Avatar ─────────────────────────────────────────────
function Avatar({ seed, name, size=28 }){
  // Deterministic gradient based on seed
  const hue = (seed||"").split("").reduce((s,c)=>s+c.charCodeAt(0),0) % 360;
  const initials = (name||"?").split(" ").map(s=>s[0]).slice(0,2).join("").toUpperCase();
  return (
    <span style={{
      width:size, height:size,
      borderRadius:"50%",
      background:`linear-gradient(135deg, hsl(${hue} 70% 55%), hsl(${(hue+45)%360} 65% 45%))`,
      color:"#fff",
      fontSize:size*0.4, fontWeight:600,
      display:"inline-flex", alignItems:"center", justifyContent:"center",
      flexShrink:0,
      boxShadow:"0 1px 2px rgba(20,16,8,0.10), inset 0 1px 0 rgba(255,255,255,0.20)",
    }}>{initials}</span>
  );
}

Object.assign(window, { Team, Avatar });
