import { isTeamMember } from "@/app/utils/auth"
import { redirect } from "next/navigation"
import Image from "next/image"
import { ReportToggle } from "@/components/report/report-toggle"
import {
  LatencyChart,
  BundleChart,
  OnboardingChart,
  CategoryPie,
} from "@/components/report/report-charts"

export const metadata = { title: "Performance Report — Codeflash" }

/* ── static data ────────────────────────────────────────────────────── */

const PAGE_RESULTS: { page: string; before: number | null; after: number | null; note?: string }[] =
  [
    { page: "Onboarding", before: 10275, after: 8108 },
    { page: "API Keys", before: 6415, after: 5989 },
    { page: "Billing", before: 4108, after: 4383 },
    { page: "Traces", before: 3353, after: 3888 },
    { page: "Getting Started", before: 4513, after: 5350 },
    { page: "Dashboard", before: 16816, after: 30000, note: "timeout — bug fixed separately" },
    {
      page: "Review Optimizations",
      before: 4376,
      after: 16735,
      note: "only 3 samples, low confidence",
    },
  ]

const FULL_PAGE_TABLE: {
  route: string
  avgBefore: number | null
  avgAfter: number | null
  p95Before: number | null
  p95After: number | null
}[] = [
  { route: "/dashboard", avgBefore: 16816, avgAfter: 30000, p95Before: 30000, p95After: 30000 },
  { route: "/onboarding", avgBefore: 10275, avgAfter: 8108, p95Before: 20092, p95After: 8108 },
  { route: "/apikeys", avgBefore: 6415, avgAfter: 5989, p95Before: 11120, p95After: 10291 },
  { route: "/trace/:trace_id", avgBefore: 6909, avgAfter: null, p95Before: 9013, p95After: null },
  { route: "/login", avgBefore: 4958, avgAfter: null, p95Before: 7647, p95After: null },
  { route: "/repositories", avgBefore: 4306, avgAfter: null, p95Before: 7110, p95After: null },
  {
    route: "/review-optimizations",
    avgBefore: 4376,
    avgAfter: 16735,
    p95Before: 4985,
    p95After: 16735,
  },
  { route: "/getting-started", avgBefore: 4513, avgAfter: 5350, p95Before: 4513, p95After: 5588 },
  { route: "/repositories/:id", avgBefore: 5292, avgAfter: null, p95Before: 5292, p95After: null },
  { route: "/billing", avgBefore: 4108, avgAfter: 4383, p95Before: 4108, p95After: 4383 },
  {
    route: "/observability/traces",
    avgBefore: 3353,
    avgAfter: 3888,
    p95Before: 3981,
    p95After: 3888,
  },
  { route: "/codeflash/auth", avgBefore: 1093, avgAfter: 3465, p95Before: 1673, p95After: 5079 },
  { route: "/members", avgBefore: 1658, avgAfter: null, p95Before: 1658, p95After: null },
]

const BUNDLE_TABLE = [
  { opt: "Sentry Replay lazy-load", savings: "~600 KB deferred", pr: "#2554" },
  { opt: "prism-react-renderer dynamic import", savings: "~132 KB", pr: "#2557" },
  { opt: "framer-motion → motion/react", savings: "~70 KB", pr: "#2556" },
  { opt: "PrismLight switch", savings: "~50 KB", pr: "#2539" },
  {
    opt: "Unused dep removal (github-markdown-css, react-papaparse, @azure/msal-node)",
    savings: "variable",
    pr: "#2562",
  },
  { opt: "@sentry/node → @sentry/nextjs", savings: "duplicate SDK eliminated", pr: "#2555" },
]

const RUNTIME_TABLE = [
  { opt: "N+1 query elimination", impact: "1 query vs N for optimization_features", pr: "#2544" },
  {
    opt: "Promise.all parallelization",
    impact: "Concurrent DB fetches on 5 pages",
    pr: "#2545, #2546, #2559, #2561, #2560",
  },
  { opt: "React cache() dedup", impact: "2 identical Prisma calls → 1 per request", pr: "#2560" },
  { opt: "PostHog singleton", impact: "Eliminated repeated HTTP client creation", pr: "#2558" },
  {
    opt: "PrismaClient singleton",
    impact: "Consolidated per-file PrismaClient instances",
    pr: "#2543",
  },
]

const OBSERVABILITY_TABLE = [
  {
    name: "OTel + Sentry bridge",
    detail: "SentrySpanProcessor, SentryPropagator, SentrySampler",
    pr: "#2547",
  },
  { name: "Server action timing", detail: "withTiming() wrapper with Sentry spans", pr: "#2552" },
  { name: "Slow query logging", detail: ">500ms queries forwarded to Sentry", pr: "#2547" },
  {
    name: "PostHog analytics",
    detail: "trackOptimizationReviewed + key user actions",
    pr: "#2552",
  },
  { name: "Bundle analysis", detail: "Route size analysis scripts", pr: "#2553" },
]

type PRCategory =
  | "Bundle size"
  | "Runtime"
  | "Observability"
  | "Testing"
  | "Cleanup"
  | "CI"
  | "Bugfix"
const CATEGORY_COLORS: Record<PRCategory, string> = {
  "Bundle size": "text-amber-600 dark:text-amber-400",
  Runtime: "text-green-600 dark:text-green-400",
  Observability: "text-amber-700 dark:text-amber-500",
  Testing: "text-purple-600 dark:text-purple-400",
  Cleanup: "text-zinc-500 dark:text-zinc-400",
  CI: "text-pink-600 dark:text-pink-400",
  Bugfix: "text-red-600 dark:text-red-400",
}

const PR_INVENTORY: { num: string; pr: string; title: string; cat: PRCategory }[] = [
  { num: "1", pr: "#2539", title: "PrismLight switch", cat: "Bundle size" },
  { num: "2", pr: "#2540", title: "Named diff + Sentry import", cat: "Bundle size" },
  { num: "3", pr: "#2543", title: "PrismaClient singleton", cat: "Runtime" },
  { num: "4", pr: "#2544", title: "N+1 query elimination", cat: "Runtime" },
  { num: "5", pr: "#2545", title: "Members page parallel fetch", cat: "Runtime" },
  { num: "6", pr: "#2546", title: "Repository page parallel fetch", cat: "Runtime" },
  { num: "7", pr: "#2547", title: "Observability stack (OTel + Sentry)", cat: "Observability" },
  { num: "8", pr: "#2552", title: "Server action timing + analytics", cat: "Observability" },
  { num: "9", pr: "#2553", title: "Test coverage + bundle analysis", cat: "Testing" },
  { num: "10", pr: "#2554", title: "Sentry Replay lazy-load", cat: "Bundle size" },
  { num: "11", pr: "#2555", title: "@sentry/nextjs consistency", cat: "Bundle size" },
  { num: "12", pr: "#2556", title: "framer-motion → motion/react", cat: "Bundle size" },
  { num: "13", pr: "#2557", title: "LineProfilerView dynamic import", cat: "Bundle size" },
  { num: "14", pr: "#2558", title: "PostHog singleton", cat: "Runtime" },
  { num: "15", pr: "#2559", title: "Optimization event parallel fetch", cat: "Runtime" },
  { num: "16", pr: "#2560", title: "React cache() dedup", cat: "Runtime" },
  { num: "17", pr: "#2561", title: "LLM call detail parallel fetch", cat: "Runtime" },
  { num: "18", pr: "#2562", title: "Unused dep removal", cat: "Cleanup" },
  { num: "19", pr: "#2563", title: "Quality gates CI workflow", cat: "CI" },
  { num: "—", pr: "#2564", title: "Sidebar refetch loop fix", cat: "Bugfix" },
]

/* ── helpers ────────────────────────────────────────────────────────── */

function fmt(v: number | null) {
  if (v === null) return "—"
  return v.toLocaleString()
}

function pctBadge(before: number | null, after: number | null) {
  if (before === null || after === null)
    return <span className="text-zinc-400 dark:text-zinc-500">—</span>
  const pct = ((after - before) / before) * 100
  const improved = pct < 0
  return (
    <span
      className={`inline-block rounded-md px-2 py-0.5 text-xs font-bold ${improved ? "bg-green-100 text-green-700 dark:bg-green-400/10 dark:text-green-400" : "bg-red-100 text-red-700 dark:bg-red-400/10 dark:text-red-400"}`}
    >
      {pct > 0 ? "+" : ""}
      {pct.toFixed(0)}%
    </span>
  )
}

/* ── page ───────────────────────────────────────────────────────────── */

export default async function ReportPage() {
  const teamMember = await isTeamMember()
  if (!teamMember) redirect("/")

  return (
    <div className="min-h-screen bg-white dark:bg-zinc-950 font-sans text-zinc-900 dark:text-zinc-200">
      {/* ── Hero ── */}
      <div className="border-b border-zinc-200 dark:border-zinc-800 bg-gradient-to-br from-zinc-100 via-amber-50/40 to-zinc-100 dark:from-zinc-950 dark:via-stone-900/60 dark:to-zinc-950 px-6 pb-14 pt-16 text-center">
        <Image
          src="/images/codeflash_darkmode.svg"
          alt="Codeflash"
          width={120}
          height={28}
          className="mx-auto mb-4 hidden dark:block"
          priority
        />
        <Image
          src="/images/codeflash_light.svg"
          alt="Codeflash"
          width={120}
          height={28}
          className="mx-auto mb-4 dark:hidden"
          priority
        />
        <h1
          className="text-[36px] font-extrabold tracking-tight text-zinc-900 dark:text-zinc-50"
          style={{ letterSpacing: "-0.02em" }}
        >
          Web App Performance Optimization
        </h1>
        <p className="mx-auto mt-3 max-w-[600px] text-[17px] text-zinc-500 dark:text-zinc-400">
          How we made the Codeflash dashboard faster, lighter, and more reliable
        </p>
        <div className="mt-6 flex flex-wrap items-center justify-center gap-6 text-[13px] text-zinc-400 dark:text-zinc-500">
          <span>April 4, 2026</span>
          <span>·</span>
          <span>20 changes shipped</span>
          <span>·</span>
          <span>Zero downtime</span>
        </div>
      </div>

      {/* ── Hero Metrics ── */}
      <div
        className="mx-auto -mt-10 grid max-w-4xl grid-cols-2 gap-5 px-6 lg:grid-cols-4"
        style={{ position: "relative", zIndex: 1 }}
      >
        {[
          {
            value: "-55%",
            label: "Slowest Responses",
            detail: "p95 latency: 1.2s → 0.6s",
            color: "text-green-600 dark:text-green-400",
          },
          {
            value: "-25%",
            label: "Typical Responses",
            detail: "p75 latency: 289ms → 216ms",
            color: "text-green-600 dark:text-green-400",
          },
          {
            value: "850 KB",
            label: "Smaller Downloads",
            detail: "Removed from every page load",
            color: "text-amber-500 dark:text-[#ffd227]",
          },
          {
            value: "0",
            label: "New Bugs",
            detail: "All changes verified, zero errors",
            color: "text-amber-500 dark:text-[#ffd227]",
          },
        ].map(m => (
          <div
            key={m.label}
            className="rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 px-6 py-8 text-center shadow-sm dark:shadow-none"
          >
            <div
              className={`font-mono leading-none ${m.color}`}
              style={{ fontSize: "42px", fontWeight: 800, letterSpacing: "-0.02em" }}
            >
              {m.value}
            </div>
            <div className="mt-2 text-[15px] font-semibold text-zinc-800 dark:text-zinc-200">
              {m.label}
            </div>
            <div className="mt-1 text-[13px] text-zinc-500 dark:text-zinc-400">{m.detail}</div>
          </div>
        ))}
      </div>

      {/* ── Toggle + Views ── */}
      <div className="mx-auto max-w-4xl px-6 pb-20">
        <ReportToggle execView={<ExecView />} engView={<EngView />} />
      </div>

      {/* ── Footer ── */}
      <div className="border-t border-zinc-200 dark:border-zinc-800 py-8 text-center">
        <Image
          src="/images/codeflash_darkmode.svg"
          alt="Codeflash"
          width={80}
          height={20}
          className="mx-auto mb-2 opacity-40 hidden dark:block"
        />
        <Image
          src="/images/codeflash_light.svg"
          alt="Codeflash"
          width={80}
          height={20}
          className="mx-auto mb-2 opacity-40 dark:hidden"
        />
        <p className="text-xs text-zinc-400 dark:text-zinc-500">April 2026</p>
      </div>
    </div>
  )
}

/* ═══════════════════════════════════════════════════════════════════════
   EXECUTIVE VIEW
   ═══════════════════════════════════════════════════════════════════════ */

function ExecView() {
  return (
    <div className="space-y-14">
      {/* ── Cost Impact ── */}
      <Section
        title="Cost Impact"
        subtitle="Performance improvements unlock infrastructure savings."
      >
        <Card>
          <div className="flex flex-wrap items-center gap-8">
            <div className="min-w-[200px]">
              <div
                className="font-mono leading-none text-green-600 dark:text-green-400"
                style={{ fontSize: "48px", fontWeight: 800 }}
              >
                $660
              </div>
              <div className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
                estimated annual savings
              </div>
            </div>
            <div className="flex-1 border-l-2 border-zinc-200 dark:border-zinc-800 pl-6">
              <p className="text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">
                The webapp currently runs on an Azure Premium V2 (P1v2) instance at $81/month. With
                the performance optimizations — parallel queries, eliminated N+1 fetches, fixed
                infinite request loop, and reduced CPU load per request — the app can be downscaled
                to a Basic B2 instance.
              </p>
            </div>
          </div>
        </Card>

        {/* Infra comparison */}
        <div className="mt-5 flex flex-wrap items-center gap-5">
          <div className="flex-1 min-w-[260px] rounded-xl border border-zinc-200 dark:border-zinc-800 border-t-4 border-t-red-400 bg-white dark:bg-zinc-900 p-6 shadow-sm dark:shadow-none">
            <div className="text-[11px] font-bold uppercase tracking-widest text-red-500 dark:text-red-400">
              Current
            </div>
            <div className="mt-3 text-lg font-bold text-zinc-900 dark:text-zinc-200">
              P1v2 — Premium V2
            </div>
            <div className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">1 vCPU · 3.5 GB RAM</div>
            <div className="mt-4 border-t border-zinc-200 dark:border-zinc-800 pt-4 space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-zinc-500 dark:text-zinc-400">Monthly</span>
                <span className="font-bold text-zinc-900 dark:text-zinc-200">$81</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-zinc-500 dark:text-zinc-400">Annual</span>
                <span className="font-bold text-zinc-900 dark:text-zinc-200">$972</span>
              </div>
            </div>
          </div>
          <div className="text-3xl text-zinc-300 dark:text-zinc-500">→</div>
          <div className="flex-1 min-w-[260px] rounded-xl border border-zinc-200 dark:border-zinc-800 border-t-4 border-t-green-400 bg-white dark:bg-zinc-900 p-6 shadow-sm dark:shadow-none">
            <div className="text-[11px] font-bold uppercase tracking-widest text-green-600 dark:text-green-400">
              Recommended
            </div>
            <div className="mt-3 text-lg font-bold text-zinc-900 dark:text-zinc-200">
              B2 — Basic
            </div>
            <div className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">2 vCPU · 3.5 GB RAM</div>
            <div className="mt-4 border-t border-zinc-200 dark:border-zinc-800 pt-4 space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-zinc-500 dark:text-zinc-400">Monthly</span>
                <span className="font-bold text-green-600 dark:text-green-400">$26</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-zinc-500 dark:text-zinc-400">Annual</span>
                <span className="font-bold text-green-600 dark:text-green-400">$312</span>
              </div>
            </div>
          </div>
        </div>

        {/* Why + monitoring */}
        <div className="mt-5 flex flex-wrap gap-5">
          <Card className="flex-1 min-w-[280px]">
            <h4 className="text-base font-bold text-zinc-900 dark:text-zinc-200">
              Why downscaling is safe
            </h4>
            <ul className="mt-3 space-y-1.5 pl-5 text-sm leading-relaxed text-zinc-600 dark:text-zinc-400 list-disc">
              <li>The webapp handles only ~14 transactions/day — minimal compute needs</li>
              <li>The infinite request loop (hundreds of requests/sec) has been fixed</li>
              <li>
                Database queries now run in parallel, completing faster and releasing threads sooner
              </li>
              <li>N+1 query pattern eliminated — fewer round-trips to the database</li>
              <li>B2 actually gives more CPU cores (2 vs 1) at a third of the price</li>
            </ul>
            <p className="mt-4 rounded-lg bg-zinc-50 dark:bg-white/[0.04] p-3 text-xs text-zinc-500">
              Note: B-tier does not include deployment slots. If staging/production slot swapping is
              required, Standard S1 ($73/mo, saving $96/year) is the minimum tier that supports it.
            </p>
          </Card>
          <Card className="flex-1 min-w-[280px]">
            <h4 className="text-base font-bold text-zinc-900 dark:text-zinc-200">
              Monitoring cost reduction
            </h4>
            <div
              className="mt-3 font-mono leading-none text-green-600 dark:text-green-400"
              style={{ fontSize: "42px", fontWeight: 800 }}
            >
              90%
            </div>
            <div className="mt-1 text-sm font-semibold text-zinc-800 dark:text-zinc-200">
              less Sentry event volume
            </div>
            <p className="mt-3 text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">
              Trace sampling reduced from 100% to 10% in production. Same error visibility, same
              alerting — just 90% fewer billable events. Exact dollar savings depend on your Sentry
              plan tier.
            </p>
            <div className="mt-4 border-t border-zinc-200 dark:border-zinc-800 pt-4">
              <div className="text-sm font-bold text-red-600 dark:text-red-400">
                1 pre-existing bug found &amp; fixed
              </div>
              <p className="mt-1 text-xs leading-relaxed text-zinc-600 dark:text-zinc-400">
                Dashboard sidebar was generating hundreds of server requests per second. This silent
                resource drain is now eliminated.
              </p>
            </div>
          </Card>
        </div>
      </Section>

      {/* ── What Does This Mean? ── */}
      <Section
        title="What Does This Mean?"
        subtitle="These numbers translate directly to user experience."
      >
        <div className="flex flex-wrap gap-5">
          {[
            {
              title: "Users wait less",
              body: "The slowest page loads improved by over half a second. Users who previously waited 1.2 seconds for the app to respond now wait 0.6 seconds.",
            },
            {
              title: "Pages load faster",
              body: "We removed 850 KB of code that was being downloaded on every page visit. That's the equivalent of a high-resolution photo — gone from every load.",
            },
            {
              title: "Nothing broke",
              body: "All 20 changes were individually tested and verified. Error monitoring confirms zero new issues were introduced.",
            },
          ].map(c => (
            <Card key={c.title} className="flex-1 min-w-[260px]">
              <h4 className="text-base font-bold text-zinc-900 dark:text-zinc-200">{c.title}</h4>
              <p className="mt-2 text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">
                {c.body}
              </p>
            </Card>
          ))}
        </div>
      </Section>

      {/* ── Response Time ── */}
      <Section
        title="Response Time Improvement"
        subtitle="How long users wait for the app to respond, before and after optimization."
      >
        <Card>
          <LatencyChart />
        </Card>
      </Section>

      {/* ── Onboarding spotlight ── */}
      <Section
        title="Spotlight: Onboarding Page"
        subtitle="The clearest per-page improvement — new users now get a 60% faster experience."
      >
        <Card>
          <OnboardingChart />
        </Card>
      </Section>

      {/* ── Bundle Size ── */}
      <Section
        title="Download Size Reduction"
        subtitle="Code removed from what every user downloads on their first visit."
      >
        <Card>
          <BundleChart />
        </Card>
      </Section>

      {/* ── What We Changed ── */}
      <Section title="What We Changed" subtitle="20 targeted improvements across 5 categories.">
        <div className="flex flex-wrap items-start gap-6">
          <div className="flex-1 min-w-[300px]">
            <Card>
              {[
                {
                  icon: "⚡",
                  title: "Faster Database Queries",
                  desc: "Eliminated redundant queries and ran independent queries in parallel instead of one-by-one. 5 pages now load data concurrently.",
                },
                {
                  icon: "📦",
                  title: "Smaller Page Downloads",
                  desc: "Removed unused code, deferred non-critical libraries, and switched to lighter alternatives. 850 KB+ removed from every initial page load.",
                },
                {
                  icon: "📊",
                  title: "Better Monitoring",
                  desc: "Added performance tracking for every server action, slow query alerts, and user behavior analytics. We can now see exactly what's slow and why.",
                },
                {
                  icon: "🧪",
                  title: "Automated Testing",
                  desc: "Added 39 tests covering critical paths. Set up a CI pipeline that checks code quality, runs tests, and reports page sizes on every change.",
                },
                {
                  icon: "🔧",
                  title: "Bug Fix",
                  desc: "Found and fixed a dashboard bug where the sidebar was making hundreds of server requests per second due to an infinite loop. This was wasting resources silently.",
                },
              ].map(item => (
                <div
                  key={item.title}
                  className="flex gap-4 border-b border-zinc-100 dark:border-zinc-800 py-3.5 last:border-b-0"
                >
                  <span className="w-10 flex-shrink-0 text-center text-2xl">{item.icon}</span>
                  <div>
                    <div className="text-sm font-semibold text-zinc-900 dark:text-zinc-200">
                      {item.title}
                    </div>
                    <div className="mt-0.5 text-xs leading-relaxed text-zinc-500 dark:text-zinc-400">
                      {item.desc}
                    </div>
                  </div>
                </div>
              ))}
            </Card>
          </div>
          <div className="w-80 flex-shrink-0">
            <Card>
              <div className="mb-3 text-center text-sm font-semibold text-zinc-800 dark:text-zinc-200">
                Changes by Category
              </div>
              <CategoryPie />
            </Card>
          </div>
        </div>
      </Section>

      {/* ── Page-by-Page ── */}
      <Section
        title="Page-by-Page Results"
        subtitle="Average load times before and after. Results will be more definitive after 7 days of data collection."
      >
        <Card>
          <div className="overflow-x-auto">
            <div className="flex gap-4 border-b-2 border-zinc-200 dark:border-zinc-800 pb-2.5 text-[11px] font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-300">
              <div className="flex-1">Page</div>
              <div className="w-28 text-right">Before</div>
              <div className="w-28 text-right">After</div>
              <div className="w-20 text-center">Change</div>
            </div>
            {PAGE_RESULTS.map(r => (
              <div
                key={r.page}
                className="flex items-center gap-4 border-b border-zinc-100 dark:border-zinc-800 py-3"
              >
                <div className="flex-1">
                  <span className="text-sm font-semibold text-zinc-800 dark:text-zinc-200">
                    {r.page}
                  </span>
                  {r.note && (
                    <span className="ml-2 text-xs text-zinc-400 dark:text-zinc-500">{r.note}</span>
                  )}
                </div>
                <div className="w-28 text-right font-mono text-sm text-zinc-500 dark:text-zinc-400">
                  {fmt(r.before)} ms
                </div>
                <div className="w-28 text-right font-mono text-sm font-semibold text-zinc-800 dark:text-zinc-200">
                  {fmt(r.after)} ms
                </div>
                <div className="w-20 text-center">{pctBadge(r.before, r.after)}</div>
              </div>
            ))}
          </div>
          <p className="mt-4 text-xs leading-relaxed text-zinc-400 dark:text-zinc-500">
            Note: Many pages have limited post-optimization data because we reduced monitoring from
            100% to 10% sampling, and only ~2 hours had passed at measurement time. Full results
            expected within 7 days.
          </p>
        </Card>
      </Section>

      {/* ── Recommended Actions ── */}
      <Section
        title="Recommended Actions"
        subtitle="Decisions and approvals needed from leadership."
      >
        <Card>
          <ActionItem text="Approve downscaling Azure App Service from P1v2 ($81/mo) to B2 ($26/mo) — saves $660/year" />
          <ActionItem text="Decide whether deployment slot swapping is needed (if yes, S1 at $73/mo instead)" />
          <ActionItem text="Review Sentry plan tier — 90% fewer events may allow a plan downgrade" />
          <ActionItem text="Schedule follow-up review in 7 days once full post-optimization data is available" />
        </Card>
      </Section>
    </div>
  )
}

/* ═══════════════════════════════════════════════════════════════════════
   ENGINEERING VIEW
   ═══════════════════════════════════════════════════════════════════════ */

function EngView() {
  return (
    <div className="space-y-14">
      {/* ── Span Latency ── */}
      <Section
        title="Span Latency — Before vs. After"
        subtitle="Cutoff: first PR merged at 2026-04-04T16:14:09 UTC. Before = 14 days prior. After = post-merge with 10% sampling."
      >
        <Card>
          <LatencyChart />
        </Card>
      </Section>

      {/* ── Error Count ── */}
      <Section title="Error Count">
        <div className="flex flex-wrap gap-5">
          <Card className="flex-1 min-w-[200px]">
            <div className="text-[13px] font-semibold uppercase tracking-widest text-zinc-500 dark:text-zinc-400">
              Before (14d)
            </div>
            <div
              className="mt-1 font-mono text-zinc-800 dark:text-zinc-200"
              style={{ fontSize: "36px", fontWeight: 800 }}
            >
              2
            </div>
            <div className="text-sm text-zinc-500 dark:text-zinc-400">errors</div>
          </Card>
          <Card className="flex-1 min-w-[200px]">
            <div className="text-[13px] font-semibold uppercase tracking-widest text-zinc-500 dark:text-zinc-400">
              After (post-merge)
            </div>
            <div
              className="mt-1 font-mono text-green-600 dark:text-green-400"
              style={{ fontSize: "36px", fontWeight: 800 }}
            >
              0
            </div>
            <div className="text-sm text-green-600 dark:text-green-400">
              errors — zero regressions
            </div>
          </Card>
          <Card className="flex-1 min-w-[200px]">
            <div className="text-[13px] font-semibold uppercase tracking-widest text-zinc-500 dark:text-zinc-400">
              Transactions (14d)
            </div>
            <div
              className="mt-1 font-mono text-zinc-800 dark:text-zinc-200"
              style={{ fontSize: "36px", fontWeight: 800 }}
            >
              107 → 41
            </div>
            <div className="text-sm text-zinc-500 dark:text-zinc-400">
              sampling reduced 100% → 10%
            </div>
          </Card>
        </div>
      </Section>

      {/* ── Full Page Load Table ── */}
      <Section
        title="Page Load Durations (All Pages)"
        subtitle="Sentry pageload transaction data. Before = 14d window, After = post-merge."
      >
        <Card>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b-2 border-zinc-200 dark:border-zinc-800 text-left text-[11px] font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-300">
                  <th className="py-2.5 pr-4">Route</th>
                  <th className="py-2.5 w-24 text-right">Avg Before</th>
                  <th className="py-2.5 w-24 text-right">Avg After</th>
                  <th className="py-2.5 w-24 text-right">p95 Before</th>
                  <th className="py-2.5 w-24 text-right">p95 After</th>
                </tr>
              </thead>
              <tbody>
                {FULL_PAGE_TABLE.map((r, i) => (
                  <tr
                    key={r.route}
                    className={`border-b border-zinc-100 dark:border-zinc-800 ${i % 2 ? "bg-zinc-50/50 dark:bg-white/[0.02]" : ""}`}
                  >
                    <td className="py-2.5 pr-4 font-mono text-xs font-medium text-zinc-800 dark:text-zinc-200">
                      {r.route}
                    </td>
                    <td className="py-2.5 w-24 text-right font-mono text-zinc-500 dark:text-zinc-400">
                      {fmt(r.avgBefore)}
                    </td>
                    <td className="py-2.5 w-24 text-right font-mono font-semibold text-zinc-800 dark:text-zinc-200">
                      {fmt(r.avgAfter)}
                    </td>
                    <td className="py-2.5 w-24 text-right font-mono text-zinc-500 dark:text-zinc-400">
                      {fmt(r.p95Before)}
                    </td>
                    <td className="py-2.5 w-24 text-right font-mono font-semibold text-zinc-800 dark:text-zinc-200">
                      {fmt(r.p95After)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <p className="mt-3 text-xs text-zinc-400 dark:text-zinc-500">
            — = no post-merge samples (10% sampling + short window). Dashboard 30s = sidebar refetch
            loop timeout (fixed PR #2564).
          </p>
        </Card>
      </Section>

      {/* ── Bundle Size Details ── */}
      <Section title="Bundle Size Reductions (~850 KB+)">
        <Card>
          <DataTable
            columns={["Optimization", "Est. Savings", "PR"]}
            rows={BUNDLE_TABLE.map(r => [r.opt, r.savings, r.pr])}
          />
        </Card>
      </Section>

      {/* ── Runtime Details ── */}
      <Section title="Runtime & Latency Improvements">
        <Card>
          <DataTable
            columns={["Optimization", "Impact", "PR"]}
            rows={RUNTIME_TABLE.map(r => [r.opt, r.impact, r.pr])}
          />
        </Card>
      </Section>

      {/* ── Observability Stack ── */}
      <Section title="Observability Stack">
        <Card>
          <DataTable
            columns={["Addition", "Detail", "PR"]}
            rows={OBSERVABILITY_TABLE.map(r => [r.name, r.detail, r.pr])}
          />
        </Card>
      </Section>

      {/* ── Testing & CI ── */}
      <Section title="Testing & CI">
        <Card>
          <ul className="space-y-1.5 pl-5 text-sm leading-relaxed text-zinc-700 dark:text-zinc-200 list-disc">
            <li>
              39 tests across 4 files: withTiming wrapper, N+1 fix verification, parallel fetches,
              access control, error handling (PR #2553)
            </li>
            <li>
              Quality gates CI workflow: type-check → tests → build → route size PR comment (PR
              #2563)
            </li>
            <li>Trace sampling: 100% → 10% in production (PR #2547)</li>
          </ul>
        </Card>
      </Section>

      {/* ── Full PR Inventory ── */}
      <Section
        title="Full PR Inventory"
        subtitle="All 19 optimization PRs + 1 bugfix, merged sequentially to main."
      >
        <Card>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b-2 border-zinc-200 dark:border-zinc-800 text-left text-[11px] font-bold uppercase tracking-wider text-amber-600 dark:text-amber-400">
                  <th className="py-2.5 w-10">#</th>
                  <th className="py-2.5 w-20">PR</th>
                  <th className="py-2.5">Title</th>
                  <th className="py-2.5 w-32">Category</th>
                </tr>
              </thead>
              <tbody>
                {PR_INVENTORY.map((r, i) => (
                  <tr
                    key={r.pr}
                    className={`border-b border-zinc-100 dark:border-zinc-800 ${i % 2 ? "bg-zinc-50/50 dark:bg-white/[0.02]" : ""}`}
                  >
                    <td className="py-2.5 text-zinc-500 dark:text-zinc-400">{r.num}</td>
                    <td className="py-2.5 text-zinc-800 dark:text-zinc-200">{r.pr}</td>
                    <td className="py-2.5 text-zinc-800 dark:text-zinc-200">{r.title}</td>
                    <td className={`py-2.5 font-semibold ${CATEGORY_COLORS[r.cat]}`}>{r.cat}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      </Section>

      {/* ── Pre-Existing Issues ── */}
      <Section title="Pre-Existing Issues Discovered">
        <IssueCard
          title="Dashboard Sidebar Infinite Refetch Loop"
          severity="High — Fixed in PR #2564"
          borderColor="border-l-red-400"
          badgeColor="bg-red-100 text-red-800 dark:bg-red-400 dark:text-zinc-950"
          body="sidebar.tsx:101-124 — subscriptionFetchRef reset in finally() caused re-entrancy. Each fetch → setSubscription → re-render → ref false → fetch. Hundreds of POST+GET pairs/sec."
          fix="Moved ref reset to effect cleanup. Added cancelled flag for unmount safety."
        />
        <IssueCard
          title="Auth0 Favicon 404"
          severity="Low"
          borderColor="border-l-zinc-400"
          badgeColor="bg-zinc-200 text-zinc-700 dark:bg-zinc-500 dark:text-zinc-950"
          body="Auth0 hosted login (codeflash-ai.us.auth0.com) returns 404 for /favicon.ico. Fix: Auth0 Dashboard > Branding > Universal Login > upload favicon."
        />
        <IssueCard
          title="Image Cache ENOENT"
          severity="Low"
          borderColor="border-l-zinc-400"
          badgeColor="bg-zinc-200 text-zinc-700 dark:bg-zinc-500 dark:text-zinc-950"
          body="mkdir '/home/site/wwwroot/.next/cache/images' — Azure Run-From-Zip mounts app as read-only. Image optimization caching only, not functional."
        />
      </Section>

      {/* ── Infrastructure ── */}
      <Section
        title="Infrastructure"
        subtitle="Current Azure App Service plan and recommended downscale after optimizations."
      >
        <Card>
          <div className="flex flex-wrap items-center gap-6">
            <div className="flex-1">
              <div className="text-[11px] font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400">
                Current
              </div>
              <div className="mt-1 text-base font-bold text-zinc-900 dark:text-zinc-200">
                P1v2 (PremiumV2)
              </div>
              <div className="mt-0.5 text-xs text-zinc-500 dark:text-zinc-400">
                1 vCPU · 3.5 GB · 1 instance · $81/mo
              </div>
            </div>
            <div className="text-2xl text-zinc-300 dark:text-zinc-500">→</div>
            <div className="flex-1">
              <div className="text-[11px] font-bold uppercase tracking-wider text-green-600 dark:text-green-400">
                Recommended
              </div>
              <div className="mt-1 text-base font-bold text-green-600 dark:text-green-400">
                B2 (Basic)
              </div>
              <div className="mt-0.5 text-xs text-zinc-500 dark:text-zinc-400">
                2 vCPU · 3.5 GB · $26/mo (saves $660/yr)
              </div>
            </div>
          </div>
          <p className="mt-4 text-xs text-zinc-400 dark:text-zinc-500">
            B-tier lacks deployment slots. If slot swapping is required: S1 ($73/mo, saves $96/yr).
          </p>
        </Card>
      </Section>

      {/* ── Engineering Action Items ── */}
      <Section title="Engineering Action Items" subtitle="Technical tasks to complete post-merge.">
        <Card>
          <ActionItem text="Re-measure page load durations after 7 days with clean post-fix Sentry data" />
          <ActionItem text="Verify db.query spans from @prisma/instrumentation are appearing in Sentry" />
          <ActionItem text="Upload Codeflash favicon in Auth0 Dashboard > Branding > Universal Login" />
          <ActionItem text="Investigate /dashboard 30s timeout — root cause may extend beyond sidebar fix" />
          <ActionItem text="Execute App Service downscale: az appservice plan update --sku B2 (or S1 if slots needed)" />
          <ActionItem text="Audit remaining bundle: run next build --profile and check for further lazy-load candidates" />
          <ActionItem text="Add Playwright smoke tests to CI for critical page renders" />
        </Card>
      </Section>
    </div>
  )
}

/* ── shared components ──────────────────────────────────────────────── */

function Section({
  title,
  subtitle,
  children,
}: {
  title: string
  subtitle?: string
  children: React.ReactNode
}) {
  return (
    <div>
      <h2
        className="text-[22px] font-bold text-zinc-900 dark:text-zinc-200"
        style={{ letterSpacing: "-0.01em" }}
      >
        {title}
      </h2>
      {subtitle && (
        <p className="mt-1.5 text-sm leading-relaxed text-zinc-500 dark:text-zinc-400">
          {subtitle}
        </p>
      )}
      <div className="mt-6">{children}</div>
    </div>
  )
}

function Card({ children, className = "" }: { children: React.ReactNode; className?: string }) {
  return (
    <div
      className={`rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 shadow-sm dark:shadow-none ${className}`}
      style={{ padding: "28px 32px" }}
    >
      {children}
    </div>
  )
}

function ActionItem({ text }: { text: string }) {
  return (
    <div className="flex items-center gap-3 border-b border-zinc-100 dark:border-zinc-800 py-2.5 last:border-b-0">
      <span className="text-sm text-zinc-400 dark:text-zinc-500">○</span>
      <span className="text-sm text-zinc-800 dark:text-zinc-200">{text}</span>
    </div>
  )
}

function IssueCard({
  title,
  severity,
  borderColor,
  badgeColor,
  body,
  fix,
}: {
  title: string
  severity: string
  borderColor: string
  badgeColor: string
  body: string
  fix?: string
}) {
  return (
    <div
      className={`mb-4 rounded-xl border border-zinc-200 dark:border-zinc-800 border-l-4 ${borderColor} bg-white dark:bg-zinc-900 p-5 shadow-sm dark:shadow-none`}
    >
      <div className="mb-3 flex flex-wrap items-center gap-3">
        <span className="text-base font-bold text-zinc-900 dark:text-zinc-200">{title}</span>
        <span
          className={`inline-block rounded-full ${badgeColor} px-2.5 py-0.5 text-xs font-semibold`}
        >
          {severity}
        </span>
      </div>
      <p className="text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">{body}</p>
      {fix && (
        <p className="mt-2 text-sm text-zinc-700 dark:text-zinc-200">
          Fix: <span className="font-semibold">{fix}</span>
        </p>
      )}
    </div>
  )
}

function DataTable({ columns, rows }: { columns: string[]; rows: string[][] }) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b-2 border-zinc-200 dark:border-zinc-800 text-left text-[11px] font-bold uppercase tracking-wider text-amber-600 dark:text-amber-400">
            {columns.map(c => (
              <th key={c} className="py-2.5 pr-4">
                {c}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, i) => (
            <tr
              key={i}
              className={`border-b border-zinc-100 dark:border-zinc-800 ${i % 2 ? "bg-zinc-50/50 dark:bg-white/[0.02]" : ""}`}
            >
              {row.map((cell, j) => (
                <td key={j} className="py-2.5 pr-4 text-zinc-700 dark:text-zinc-200">
                  {cell}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
