// Aggregate views: API Keys overview, Metrics, Skills library, Billing

function KeysView({ instances, onOpenInstance }) {
  const openaiCount = instances.filter(i => i.apiProvider === "openai").length;
  const anthropicCount = instances.filter(i => i.apiProvider === "anthropic").length;
  return (
    <div className="content full">
      <div className="page-head">
        <div>
          <h1 className="page-title">API keys</h1>
          <p className="page-sub">Per-instance BYO keys · {instances.length} instances · {openaiCount} OpenAI · {anthropicCount} Anthropic</p>
        </div>
      </div>

      <div className="grid-3 mb-22">
        <MetricCard label="OpenAI keys" value={openaiCount} sparkColor="var(--brand)" spark={[4,5,5,6,6,7,7,7,8]}/>
        <MetricCard label="Anthropic keys" value={anthropicCount} sparkColor="var(--amber)" spark={[2,2,3,3,4,4,4,5,5]}/>
        <MetricCard label="Keys nearing quota" value="2" delta={null} sparkColor="var(--rose)" spark={[0,0,1,1,1,2,2,2,2]}/>
      </div>

      <div className="panel">
        <div className="panel-head">
          <h3>Keys by instance</h3>
          <div className="right row gap-6">
            <button className="btn sm"><Icon name="filter" size={13}/> Filter</button>
            <button className="btn sm primary"><Icon name="plus" size={13}/> Rotate all</button>
          </div>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>Instance</th>
              <th>Provider</th>
              <th>Key</th>
              <th>Status</th>
              <th className="num">Month usage</th>
              <th className="num">Last used</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {instances.map((inst) => {
              const sample = inst.apiProvider === "openai"
                ? "sk-proj-" + inst.id.replace(/-/g,"").slice(0, 6) + "•••••••••••"
                : "sk-ant-api03-" + inst.id.replace(/-/g,"").slice(0, 6) + "•••••••";
              const usage = inst.cost;
              const pct = Math.min(95, Math.round(usage / 75 * 100));
              const warn = pct > 85;
              return (
                <tr key={inst.id} style={{ cursor: "pointer" }} onClick={() => onOpenInstance(inst.id)}>
                  <td>
                    <div className="row gap-6">
                      <InstanceLogo inst={inst} size={22}/>
                      <span style={{ fontWeight: 500 }}>{inst.name}</span>
                    </div>
                  </td>
                  <td><span className="pill" style={{ color: inst.apiProvider === "openai" ? "var(--brand)" : "var(--amber)" }}><span className="dot"/>{inst.apiProvider === "openai" ? "OpenAI" : "Anthropic"}</span></td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{sample}</td>
                  <td>{warn ? <span className="pill error"><span className="dot"/>Quota 92%</span> : <span className="pill active"><span className="dot"/>Healthy</span>}</td>
                  <td className="num">{fmtEur(usage)}</td>
                  <td className="num dim">{Math.floor(Math.random() * 59) + 1}m ago</td>
                  <td style={{ textAlign: "right" }}>
                    <div className="row gap-6" style={{ justifyContent: "flex-end" }}>
                      <button className="btn sm ghost" onClick={(e)=>e.stopPropagation()}><Icon name="refresh" size={12}/></button>
                      <button className="btn sm ghost" onClick={(e)=>e.stopPropagation()}><Icon name="copy" size={12}/></button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function MetricsView({ instances }) {
  const totalIn = instances.reduce((a,i)=>a+i.tokensIn,0);
  const totalOut = instances.reduce((a,i)=>a+i.tokensOut,0);
  const totalCost = instances.reduce((a,i)=>a+i.cost,0);
  const topByCost = [...instances].sort((a,b)=>b.cost-a.cost).slice(0,6);
  const topBySkills = window.APP_DATA.SKILLS.map((s) => ({
    skill: s,
    count: instances.filter(i=>i.skills.includes(s)).length,
    invocations: Math.floor(Math.random() * 4000) + 200,
  })).sort((a,b)=>b.invocations-a.invocations);

  const days = Array.from({ length: 30 }, (_, i) => i);
  const seriesIn = days.map((d) => 300_000 + Math.sin(d / 3) * 60_000 + Math.random() * 40_000 + d * 4_000);
  const seriesOut = days.map((d) => 80_000 + Math.cos(d / 4) * 18_000 + Math.random() * 12_000 + d * 1_400);
  const dayLabels = days.map((d) => {
    const dt = new Date(2026, 2, 22 + d);
    return `${dt.getDate()}.${dt.getMonth() + 1}`;
  });

  return (
    <div className="content full">
      <div className="page-head">
        <div>
          <h1 className="page-title">Metrics</h1>
          <p className="page-sub">Token usage, cost, skill breakdown across all instances</p>
        </div>
        <div className="row gap-6">
          <div className="segmented" style={{ gridTemplateColumns: "repeat(4, 1fr)", width: 240 }}>
            {["24h","7d","30d","90d"].map((r,i) => (
              <div key={r} className={"seg " + (r === "30d" ? "on" : "")}>{r}</div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid-4 mb-22">
        <MetricCard label="Input tokens" value={(totalIn / 1_000_000).toFixed(2)} unit="M" delta={24.6} spark={[22,28,30,26,35,42,48,52,56,64,70,72]}/>
        <MetricCard label="Output tokens" value={(totalOut / 1_000_000).toFixed(2)} unit="M" delta={31.1} sparkColor="var(--violet)" spark={[10,14,16,15,19,22,25,28,30,33,36,38]}/>
        <MetricCard label="Total cost" value={"€" + totalCost.toFixed(0)} delta={18.8} sparkColor="var(--amber)" spark={[40,55,70,82,95,110,120,142,180,230,290,358]}/>
        <MetricCard label="Cost per 1M tok" value="€0.118" delta={-2.1} sparkColor="var(--blue)" spark={[13,13,12,12,12,12,11,12,12,11,11,11]}/>
      </div>

      <div className="panel mb-22">
        <div className="panel-head">
          <h3>Token consumption</h3>
          <span className="sub">· 30d, all instances · input + output</span>
        </div>
        <div className="panel-body">
          <StackedArea seriesA={seriesIn} seriesB={seriesOut} labels={dayLabels} height={260}/>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 22 }}>
        <div className="panel">
          <div className="panel-head"><h3>Top instances by cost</h3><span className="sub">· this month</span></div>
          <div className="panel-body col" style={{ gap: 10 }}>
            {topByCost.map((inst) => {
              const pct = (inst.cost / topByCost[0].cost) * 100;
              return (
                <div key={inst.id}>
                  <div className="row" style={{ justifyContent: "space-between", marginBottom: 6 }}>
                    <div className="row gap-6">
                      <InstanceLogo inst={inst} size={18}/>
                      <span style={{ fontWeight: 500, fontSize: 12.5 }}>{inst.name}</span>
                    </div>
                    <span className="mono" style={{ fontWeight: 600 }}>{fmtEur(inst.cost)}</span>
                  </div>
                  <div className="bar"><span style={{ width: pct + "%" }}/></div>
                </div>
              );
            })}
          </div>
        </div>
        <div className="panel">
          <div className="panel-head"><h3>Skills usage</h3><span className="sub">· invocations, 30d</span></div>
          <div className="panel-body">
            <Bars
              data={topBySkills.slice(0,10).map(s=>s.invocations)}
              labels={topBySkills.slice(0,10).map(s=>s.skill.replace("oprt-",""))}
              height={200}
              color="var(--violet)"
            />
          </div>
        </div>
      </div>

      <div className="panel">
        <div className="panel-head"><h3>Cost breakdown</h3><span className="sub">· by instance</span></div>
        <table className="table">
          <thead>
            <tr>
              <th>Instance</th>
              <th>Provider</th>
              <th className="num">Input</th>
              <th className="num">Output</th>
              <th className="num">Messages</th>
              <th className="num">Cost</th>
              <th className="num">€ / 1k msgs</th>
            </tr>
          </thead>
          <tbody>
            {instances.map((inst) => (
              <tr key={inst.id}>
                <td>
                  <div className="row gap-6">
                    <InstanceLogo inst={inst} size={22}/>
                    <span style={{ fontWeight: 500 }}>{inst.name}</span>
                  </div>
                </td>
                <td className="dim" style={{ textTransform: "capitalize" }}>{inst.apiProvider}</td>
                <td className="num">{fmtNum(inst.tokensIn)}</td>
                <td className="num">{fmtNum(inst.tokensOut)}</td>
                <td className="num">{fmtNum(inst.messages)}</td>
                <td className="num">{fmtEur(inst.cost)}</td>
                <td className="num dim">{fmtEur(inst.cost / Math.max(1, inst.messages) * 1000)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function SkillsView({ instances }) {
  const allSkills = window.APP_DATA.SKILLS;
  const byCategory = {
    "Google": ["oprt-gmail", "oprt-calendar", "oprt-google-docs", "oprt-google-sheets", "oprt-google-drive"],
    "Microsoft": ["oprt-microsoft-auth", "oprt-outlook", "oprt-outlook-cal", "oprt-onedrive", "oprt-sharepoint", "oprt-teams"],
    "CRM & Workspace": ["oprt-hubspot", "oprt-notion", "oprt-connect"],
    "Customer lifecycle": ["oprt-onboarding", "oprt-transcripts", "oprt-security"],
    "Finance": ["oprt-qonto"],
  };
  return (
    <div className="content full">
      <div className="page-head">
        <div>
          <h1 className="page-title">Skills library</h1>
          <p className="page-sub">{allSkills.length} installable skills · assign to any instance from the launch form or detail page</p>
        </div>
        <button className="btn primary"><Icon name="plus" size={14}/> New skill</button>
      </div>

      {Object.entries(byCategory).map(([cat, skills]) => (
        <div key={cat} className="panel mb-22">
          <div className="panel-head">
            <h3>{cat}</h3>
            <span className="sub">· {skills.length} skills</span>
          </div>
          <div className="panel-body" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
            {skills.map((s) => {
              const count = instances.filter(i => i.skills.includes(s)).length;
              const pct = Math.round((count / instances.length) * 100);
              const inv = Math.floor(Math.random() * 4800) + 120;
              return (
                <div key={s} style={{
                  border: "1px solid var(--border)", borderRadius: 8, padding: 12,
                  background: "var(--panel-2)", display: "flex", flexDirection: "column", gap: 8,
                }}>
                  <div className="row" style={{ justifyContent: "space-between" }}>
                    <span className="mono" style={{ fontWeight: 600, fontSize: 12.5 }}>{s}</span>
                    <span className="pill active"><span className="dot"/>v1.4</span>
                  </div>
                  <div className="dim" style={{ fontSize: 11.5 }}>
                    {s.includes("gmail") ? "Read, search, draft & send email threads." :
                     s.includes("calendar") ? "Schedule, move and cancel events." :
                     s.includes("hubspot") ? "Sync contacts, deals, pipelines." :
                     s.includes("notion") ? "Read/write pages, databases, tasks." :
                     s.includes("docs") ? "Compose and edit documents." :
                     s.includes("sheets") ? "Query, update, append rows." :
                     s.includes("drive") ? "Browse, search, upload files." :
                     s.includes("outlook") ? "Microsoft 365 email." :
                     s.includes("teams") ? "Send messages, read channels." :
                     s.includes("qonto") ? "Read transactions, tag invoices." :
                     s.includes("onboarding") ? "Guided first-run flow for new users." :
                     s.includes("transcripts") ? "Generate and store call transcripts." :
                     s.includes("security") ? "PII redaction, audit logging." :
                     "Integration skill for connected workflows."}
                  </div>
                  <div>
                    <div className="row" style={{ justifyContent: "space-between", marginBottom: 4 }}>
                      <span className="dim" style={{ fontSize: 11 }}>Used by {count}/{instances.length} instances</span>
                      <span className="mono" style={{ fontSize: 11 }}>{inv} inv / 30d</span>
                    </div>
                    <div className="bar"><span style={{ width: pct + "%" }}/></div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

function BillingView({ instances }) {
  const total = instances.reduce((a,i)=>a+i.cost,0);
  const margin = instances.reduce((a,i)=> a + (i.plan === "Trial" ? 0 : i.plan === "Starter" ? 49 : i.plan === "Growth" ? 149 : 499), 0);
  return (
    <div className="content full">
      <div className="page-head">
        <div>
          <h1 className="page-title">Billing</h1>
          <p className="page-sub">Customer invoices, subscriptions and model cost pass-through</p>
        </div>
        <button className="btn"><Icon name="arrow-up-right" size={14}/> Export CSV</button>
      </div>

      <div className="grid-4 mb-22">
        <MetricCard label="MRR" value={"€" + margin.toFixed(0)} delta={12.4} spark={[600,700,820,900,1020,1180,1340,1500,1680,1820]}/>
        <MetricCard label="Model cost MTD" value={"€" + total.toFixed(0)} delta={18.8} sparkColor="var(--amber)" spark={[40,55,70,82,95,110,120,142,180,230,290,358]}/>
        <MetricCard label="Gross margin" value={((margin - total) / Math.max(margin,1) * 100).toFixed(1)} unit="%" delta={1.2} sparkColor="var(--violet)"/>
        <MetricCard label="Outstanding invoices" value="2" sparkColor="var(--rose)" spark={[0,0,1,1,1,2,2,2]}/>
      </div>

      <div className="panel mb-22">
        <div className="panel-head"><h3>Customer accounts</h3></div>
        <table className="table">
          <thead><tr>
            <th>Customer</th>
            <th>Plan</th>
            <th>Status</th>
            <th className="num">Plan fee</th>
            <th className="num">Model cost MTD</th>
            <th className="num">Next invoice</th>
            <th></th>
          </tr></thead>
          <tbody>
            {instances.map((inst) => {
              const fee = inst.plan === "Trial" ? 0 : inst.plan === "Starter" ? 49 : inst.plan === "Growth" ? 149 : 499;
              return (
                <tr key={inst.id}>
                  <td>
                    <div className="row gap-6">
                      <InstanceLogo inst={inst} size={22}/>
                      <div>
                        <div style={{ fontWeight: 500 }}>{inst.name}</div>
                        <div className="dim mono" style={{ fontSize: 11 }}>{inst.email}</div>
                      </div>
                    </div>
                  </td>
                  <td>{inst.plan}</td>
                  <td><StatusPill status={inst.status}/></td>
                  <td className="num">€{fee.toFixed(2)}</td>
                  <td className="num">{fmtEur(inst.cost)}</td>
                  <td className="num mono">2026-05-01</td>
                  <td style={{ textAlign: "right" }}><button className="btn sm ghost">Invoice</button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="panel">
        <div className="panel-head"><h3>Recent invoices</h3></div>
        <table className="table">
          <thead><tr><th>#</th><th>Customer</th><th className="num">Amount</th><th>Date</th><th>Status</th></tr></thead>
          <tbody>
            {[
              { n: "INV-2941", c: "Kranich Legal", a: 648.60, d: "2026-04-01", s: "Paid" },
              { n: "INV-2940", c: "Heiztec AG", a: 231.14, d: "2026-04-01", s: "Paid" },
              { n: "INV-2939", c: "Mustermann GmbH", a: 197.72, d: "2026-04-01", s: "Paid" },
              { n: "INV-2938", c: "Nordflow Logistics", a: 185.40, d: "2026-04-01", s: "Overdue" },
              { n: "INV-2937", c: "Sonnenhof Hotels", a: 173.90, d: "2026-04-01", s: "Paid" },
              { n: "INV-2936", c: "Arktis Manufactur", a: 190.80, d: "2026-04-01", s: "Open" },
            ].map((r) => (
              <tr key={r.n}>
                <td className="mono">{r.n}</td>
                <td>{r.c}</td>
                <td className="num">€{r.a.toFixed(2)}</td>
                <td className="mono dim">{r.d}</td>
                <td>{r.s === "Paid" ? <span className="pill active"><span className="dot"/>Paid</span>
                   : r.s === "Overdue" ? <span className="pill error"><span className="dot"/>Overdue</span>
                   : <span className="pill trial"><span className="dot"/>Open</span>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.KeysView = KeysView;
window.MetricsView = MetricsView;
window.SkillsView = SkillsView;
window.BillingView = BillingView;
