import fs from "node:fs";
import path from "node:path";

interface BenchResult {
  framework: string;
  model: string;
  overall: number;
  taskCompletion: number;
  efficiency: number;
  security: number;
  skills: number;
  ux: number;
}

function loadBestPerFramework(): Record<string, Record<string, number>> {
  const resultsDir = path.join(process.cwd(), "..", "data", "results");
  const data: Record<string, Record<string, number>> = {};

  try {
    if (fs.existsSync(resultsDir)) {
      const files = fs.readdirSync(resultsDir).filter((f) => f.endsWith(".json"));
      for (const file of files) {
        const raw = fs.readFileSync(path.join(resultsDir, file), "utf-8");
        const parsed = JSON.parse(raw) as Record<string, unknown>;
        if (!parsed.framework || !parsed.taskCompletion) continue;
        const fw = parsed.framework as string;
        const scores = {
          "Task Completion": parsed.taskCompletion as number,
          Efficiency: parsed.efficiency as number,
          Security: parsed.security as number,
          Skills: parsed.skills as number,
          UX: parsed.ux as number,
        };
        // Keep the best overall per framework
        if (!data[fw] || (parsed.overall as number) > (data[fw]._overall ?? 0)) {
          data[fw] = { ...scores, _overall: parsed.overall as number };
        }
      }
    }
  } catch {
    // Fall through to sample data
  }

  if (Object.keys(data).length > 0) {
    // Remove the internal _overall tracking field
    for (const fw of Object.keys(data)) {
      delete data[fw]._overall;
    }
    return data;
  }

  // Fallback sample data
  return {
    OpenClaw: { "Task Completion": 91.2, Efficiency: 82.1, Security: 88.5, Skills: 85.0, UX: 84.3 },
    IronClaw: { "Task Completion": 88.7, Efficiency: 86.3, Security: 84.2, Skills: 83.4, UX: 81.9 },
    QClaw: { "Task Completion": 85.3, Efficiency: 80.4, Security: 82.7, Skills: 81.2, UX: 82.1 },
    ZeroClaw: { "Task Completion": 83.4, Efficiency: 84.7, Security: 75.1, Skills: 78.9, UX: 77.2 },
    NullClaw: { "Task Completion": 82.0, Efficiency: 76.5, Security: 77.8, Skills: 79.1, UX: 80.5 },
    PicoClaw: { "Task Completion": 79.5, Efficiency: 74.2, Security: 78.3, Skills: 74.1, UX: 76.0 },
    NanoBot: { "Task Completion": 77.8, Efficiency: 73.1, Security: 71.5, Skills: 72.0, UX: 75.8 },
  };
}

export default function ComparePage() {
  const data = loadBestPerFramework();
  const allFrameworks = Object.keys(data);
  const frameworkA = allFrameworks[0] || "OpenClaw";
  const frameworkB = allFrameworks[1] || "IronClaw";

  const categories = Object.keys(data[allFrameworks[0]]);
  const scoresA = data[frameworkA] || data[allFrameworks[0]];
  const scoresB = data[frameworkB] || data[allFrameworks[1]];

  return (
    <>
      <header className="page-header">
        <h1>Framework Comparison</h1>
        <p>
          Side-by-side radar chart comparison between two Claw ecosystem frameworks. Use query
          params <code style={{ fontFamily: "var(--font-mono)", fontSize: "0.85rem" }}>?a=Framework1&b=Framework2</code> to
          select.
        </p>
      </header>

      <div
        style={{
          display: "flex",
          gap: "0.75rem",
          marginBottom: "1.5rem",
          flexWrap: "wrap",
          fontSize: "0.85rem",
        }}
      >
        {allFrameworks.map((fw) => (
          <a
            key={fw}
            href={`/compare?a=${encodeURIComponent(fw)}&b=${encodeURIComponent(
              frameworkB === fw ? frameworkA : frameworkB
            )}`}
            style={{
              padding: "0.35rem 0.8rem",
              borderRadius: "var(--radius)",
              border: "1px solid var(--border)",
              background:
                fw === frameworkA || fw === frameworkB
                  ? "var(--accent)"
                  : "var(--bg-card)",
              color:
                fw === frameworkA || fw === frameworkB
                  ? "#fff"
                  : "var(--text-secondary)",
              fontWeight: fw === frameworkA || fw === frameworkB ? 600 : 400,
            }}
          >
            {fw}
          </a>
        ))}
      </div>

      <div className="card">
        <div className="placeholder" style={{ flexDirection: "column", gap: "1rem" }}>
          <div>
            <strong style={{ fontSize: "1.1rem" }}>D3.js Radar Chart</strong>
          </div>
          <p style={{ maxWidth: "400px" }}>
            An interactive radar/spider chart will overlay the score profiles of{" "}
            <strong>{frameworkA}</strong> and <strong>{frameworkB}</strong> across
            all benchmark dimensions.
          </p>
        </div>
      </div>

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: "1.5rem",
          marginTop: "1.5rem",
        }}
      >
        {[
          { name: frameworkA, scores: scoresA },
          { name: frameworkB, scores: scoresB },
        ].map(({ name, scores }) => (
          <div key={name} className="card">
            <h3
              style={{
                fontSize: "1rem",
                fontWeight: 700,
                marginBottom: "1rem",
              }}
            >
              {name}
            </h3>
            <table>
              <tbody>
                {categories.map((cat) => {
                  const score = scores[cat];
                  const cls =
                    score >= 85
                      ? "score score-high"
                      : score >= 70
                        ? "score score-mid"
                        : "score score-low";
                  return (
                    <tr key={cat}>
                      <td style={{ fontWeight: 500 }}>{cat}</td>
                      <td style={{ textAlign: "right" }}>
                        <span className={cls}>{score.toFixed(1)}</span>
                      </td>
                      <td style={{ width: "40%" }}>
                        <div
                          style={{
                            height: "8px",
                            borderRadius: "4px",
                            background: "var(--bg-secondary)",
                            overflow: "hidden",
                          }}
                        >
                          <div
                            style={{
                              height: "100%",
                              width: `${score}%`,
                              borderRadius: "4px",
                              background: "var(--accent)",
                              transition: "width 0.3s",
                            }}
                          />
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        ))}
      </div>

      <div
        className="card"
        style={{ marginTop: "1.5rem" }}
      >
        <h3
          style={{
            fontSize: "0.95rem",
            fontWeight: 600,
            marginBottom: "0.75rem",
          }}
        >
          Head-to-Head
        </h3>
        <table>
          <thead>
            <tr>
              <th>Category</th>
              <th>{frameworkA}</th>
              <th>{frameworkB}</th>
              <th>Delta</th>
            </tr>
          </thead>
          <tbody>
            {categories.map((cat) => {
              const a = scoresA[cat];
              const b = scoresB[cat];
              const delta = a - b;
              return (
                <tr key={cat}>
                  <td style={{ fontWeight: 500 }}>{cat}</td>
                  <td style={{ fontFamily: "var(--font-mono)" }}>
                    {a.toFixed(1)}
                  </td>
                  <td style={{ fontFamily: "var(--font-mono)" }}>
                    {b.toFixed(1)}
                  </td>
                  <td
                    style={{
                      fontFamily: "var(--font-mono)",
                      fontWeight: 600,
                      color:
                        delta > 0
                          ? "var(--success)"
                          : delta < 0
                            ? "var(--danger)"
                            : "var(--text-secondary)",
                    }}
                  >
                    {delta > 0 ? "+" : ""}
                    {delta.toFixed(1)}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
}
