"use client";

import { useEffect, useMemo, useState } from "react";
import { Layers, Loader2, Play, Plus, Trash2, X, AlertTriangle } from "lucide-react";
import {
  LineChart,
  Line,
  Brush,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";
import { useDiagramStore } from "@/store/diagramStore";
import { buildScenarioConfig, validateConfig } from "@/lib/configBuilder";
import type { EntropykNodeData } from "@/lib/configBuilder";
import type { Node } from "@xyflow/react";
import {
  buildSweepCases,
  defaultSweepsFromDiagram,
  discoverSweepTargets,
  extractKpis,
  getSweepWarnings,
  parseValueList,
  resolvePinTarget,
  extractAllSeries,
  runParallel,
  suggestValues,
  type MultiRunResult,
  type SweepSpec,
  type SweepTarget,
} from "@/lib/multiRun";

const GROUP_LABEL: Record<SweepTarget["group"], string> = {
  boundaries: "Conditions limites (eau / air)",
  thermal: "Échangeurs (UA…)",
  machine: "Machine (compresseur / détendeur)",
  global: "Global",
};

export default function MultiRunPanel({ onClose }: { onClose: () => void }) {
  const {
    nodes,
    edges,
    fluid,
    fluidBackend,
    solverStrategy,
    maxIterations,
    tolerance,
  } = useDiagramStore();
  const pinnedSweepPaths = useDiagramStore((s) => s.pinnedSweepPaths);

  const diagramNodes = nodes as Node<EntropykNodeData>[];
  const targets = useMemo(
    () => discoverSweepTargets(diagramNodes, fluid),
    [diagramNodes, fluid],
  );

  const [sweeps, setSweeps] = useState<SweepSpec[]>(() => {
    const initial = defaultSweepsFromDiagram(diagramNodes, fluid);
    return initial; // pins are merged by the effect below
  });

  // Merge pinned sweep paths (pushed from the properties panel) into the
  // active axis list without duplicating existing axes or dropping axes the
  // user added manually. Unresolvable pins (deleted node, non-sweepable) are
  // silently skipped — the store deliberately keeps stale pins.
  useEffect(() => {
    if (pinnedSweepPaths.length === 0) return;
    setSweeps((current) => {
      const existing = new Set(current.map((s) => s.path));
      const toAdd: SweepSpec[] = [];
      for (const path of pinnedSweepPaths) {
        if (existing.has(path)) continue;
        const t = targets.find((x) => x.path === path) ?? resolvePinTarget(path, diagramNodes);
        if (!t) continue; // unresolvable (deleted node, non-numeric) → skip
        toAdd.push({
          path: t.path,
          label: t.label,
          kind: t.kind,
          valuesText: suggestValues(t.current, t.paramKey),
        });
      }
      return toAdd.length === 0 ? current : [...current, ...toAdd];
    });
  }, [pinnedSweepPaths, targets, diagramNodes]);

  const [concurrency, setConcurrency] = useState(4);
  const [running, setRunning] = useState(false);
  const [progress, setProgress] = useState({ done: 0, total: 0 });
  const [results, setResults] = useState<MultiRunResult[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  // (Y output series selection lives in ySeriesKey below)

  const baseConfig = useMemo(
    () =>
      buildScenarioConfig(diagramNodes, edges, {
        fluid,
        fluidBackend,
        solverStrategy,
        maxIterations,
        tolerance,
      }),
    [diagramNodes, edges, fluid, fluidBackend, solverStrategy, maxIterations, tolerance],
  );

  const cases = useMemo(() => buildSweepCases(baseConfig, sweeps), [baseConfig, sweeps]);

  // Active sweep axes (those with at least one value typed in).
  const activeAxes = useMemo(
    () => sweeps.filter((s) => parseValueList(s.valuesText).length > 0),
    [sweeps],
  );

  // User-controlled X axis (which swept param is the abscissa) and Y series.
  const [xAxisPath, setXAxisPath] = useState<string | null>(null);
  const [ySeriesKey, setYSeriesKey] = useState<string | null>(null);

  // Keep xAxisPath valid when the axis list changes (deleted / added axes).
  useEffect(() => {
    if (activeAxes.length === 0) {
      if (xAxisPath !== null) setXAxisPath(null);
      return;
    }
    if (!xAxisPath || !activeAxes.some((a) => a.path === xAxisPath)) {
      setXAxisPath(activeAxes[0].path);
    }
  }, [activeAxes, xAxisPath]);

  // Every plottable output series from the first succeeded case.
  // Literature-aligned: any model output (COP, capacity, edge temps, mass flows,
  // pressures, enthalpies) can be picked as Y — not just refrigeration KPIs.
  const availableSeries = useMemo(() => {
    const firstOk = results?.find((r) => r.ok && r.result);
    return extractAllSeries(firstOk?.result);
  }, [results]);

  // Keep ySeriesKey valid: default to a non-zero COP if present, else first series.
  useEffect(() => {
    if (availableSeries.length === 0) {
      if (ySeriesKey !== null) setYSeriesKey(null);
      return;
    }
    if (!availableSeries.some((s) => s.key === ySeriesKey)) {
      const cop = availableSeries.find((s) => s.key === "perf.cop" && (s.value ?? 0) !== 0);
      setYSeriesKey((cop ?? availableSeries[0]).key);
    }
  }, [availableSeries, ySeriesKey]);

  // Chart dataset. X = chosen swept param (xAxisPath), Y = chosen output series (ySeriesKey).
  // 1 axis → single curve. 2 axes → one curve per value of the other axis.
  // 3+ axes → null (too many for readable curves; the table is the source of truth).
  const chartData = useMemo(() => {
    if (!results || results.length === 0 || !xAxisPath) return null;
    const okResults = results.filter((r) => r.ok && r.result);
    if (okResults.length === 0) return null;

    const kpiVal = (r: MultiRunResult): number | null => {
      const s = extractAllSeries(r.result).find((x) => x.key === ySeriesKey);
      return s?.value ?? null;
    };
    const xOf = (r: MultiRunResult): number | string => {
      const raw = r.case.overrides[xAxisPath];
      const n = Number(raw);
      return Number.isFinite(n) ? n : (raw as string);
    };
    const numSort = (a: number | string, b: number | string) =>
      typeof a === "number" && typeof b === "number"
        ? a - b
        : String(a).localeCompare(String(b));

    const xLabel = activeAxes.find((a) => a.path === xAxisPath)?.label ?? xAxisPath;
    const seriesAxes = activeAxes.filter((a) => a.path !== xAxisPath);

    if (seriesAxes.length === 0) {
      const rows = okResults
        .map((r) => ({ x: xOf(r), y: kpiVal(r) }))
        .sort((a, b) => numSort(a.x, b.x));
      return { mode: "single" as const, xLabel, rows };
    }

    if (seriesAxes.length === 1) {
      const sPath = seriesAxes[0].path;
      const sLabel = seriesAxes[0].label;
      const xVals: Array<number | string> = [];
      const seriesVals: string[] = [];
      const points: Array<{ x: number | string; series: string; y: number | null }> = [];
      for (const r of okResults) {
        const x = xOf(r);
        const series = String(r.case.overrides[sPath]);
        if (!xVals.some((v) => v === x)) xVals.push(x);
        if (!seriesVals.includes(series)) seriesVals.push(series);
        points.push({ x, series, y: kpiVal(r) });
      }
      xVals.sort(numSort);
      seriesVals.sort((a, b) =>
        Number.isFinite(Number(a)) && Number.isFinite(Number(b))
          ? Number(a) - Number(b)
          : a.localeCompare(b),
      );
      return { mode: "multi" as const, xLabel, sLabel, xVals, seriesVals, points };
    }

    return null;
  }, [results, activeAxes, xAxisPath, ySeriesKey]);

  // Pivoted rows for the 2-axis chart: one row per X value, one column per series value.
  // O(n) via a key-indexed map (was O(n²) with .find per cell — caused visible lag).
  const multiRows = useMemo(() => {
    if (!chartData || chartData.mode !== "multi") return null;
    const byKey = new Map<string, number | null>();
    for (const p of chartData.points) byKey.set(`${String(p.x)}|${p.series}`, p.y);
    return chartData.xVals.map((x) => {
      const row: Record<string, number | string | null> = { x };
      for (const sv of chartData.seriesVals) {
        row[sv] = byKey.get(`${String(x)}|${sv}`) ?? null;
      }
      return row;
    });
  }, [chartData]);

  const targetsByGroup = useMemo(() => {
    const map = new Map<SweepTarget["group"], SweepTarget[]>();
    for (const t of targets) {
      const list = map.get(t.group) ?? [];
      list.push(t);
      map.set(t.group, list);
    }
    return map;
  }, [targets]);

  const setAxis = (i: number, patch: Partial<SweepSpec>) => {
    setSweeps((all) => all.map((s, j) => (j === i ? { ...s, ...patch } : s)));
  };

  const pickTarget = (i: number, path: string) => {
    const t = targets.find((x) => x.path === path);
    if (!t) {
      setAxis(i, { path });
      return;
    }
    setAxis(i, {
      path: t.path,
      label: t.label,
      kind: t.kind,
      valuesText: suggestValues(t.current, t.paramKey),
    });
  };

  const addAxis = (path?: string) => {
    const t =
      (path ? targets.find((x) => x.path === path) : undefined) ??
      targets.find(
        (x) =>
          x.group === "boundaries" &&
          !sweeps.some((s) => s.path === x.path),
      ) ??
      targets.find((x) => !sweeps.some((s) => s.path === x.path)) ??
      targets[0];
    if (!t) return;
    setSweeps((s) => [
      ...s,
      {
        path: t.path,
        label: t.label,
        kind: t.kind,
        valuesText: suggestValues(t.current, t.paramKey),
      },
    ]);
  };

  const resetToWaterTemps = () => {
    setSweeps(defaultSweepsFromDiagram(diagramNodes, fluid));
    setResults(null);
    setError(null);
  };

  const onRun = async () => {
    setError(null);
    const problems = validateConfig(nodes, edges);
    if (problems.length > 0) {
      setError(problems[0]);
      return;
    }
    if (cases.length === 0) {
      setError("Aucun cas à lancer — renseigne des valeurs sur chaque axe.");
      return;
    }
    if (cases.length > 64) {
      setError(`Trop de cas (${cases.length}). Maximum 64 — réduis les listes de valeurs.`);
      return;
    }
    setRunning(true);
    setProgress({ done: 0, total: cases.length });
    setResults(null);
    try {
      const out = await runParallel(cases, {
        concurrency,
        onProgress: (done, total) => setProgress({ done, total }),
      });
      setResults(out);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setRunning(false);
    }
  };

  const boundaryCount = targets.filter((t) => t.group === "boundaries").length;

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 overscroll-contain"
      role="dialog"
      aria-modal="true"
      aria-labelledby="multirun-title"
    >
      <div className="flex max-h-[90vh] w-full max-w-3xl flex-col overflow-hidden rounded-lg border border-[var(--line)] bg-[var(--panel)] shadow-xl">
        <div className="flex items-center gap-2 border-b border-[var(--line)] px-4 py-3">
          <Layers size={16} className="text-[var(--accent)]" />
          <div className="flex-1">
            <h2 id="multirun-title" className="text-[14px] font-semibold text-[var(--ink)]">Multi-run</h2>
            <p className="text-[11px] text-[var(--ink-faint)]">
              Les variables viennent du schéma actuel (sources eau/air, UA, etc.).
              {boundaryCount > 0
                ? ` ${boundaryCount} condition(s) limite détectée(s).`
                : " Aucune source eau/air — ajoute des BrineSource pour balayer T eau."}
            </p>
          </div>
          <button type="button" className="toolish" onClick={onClose} aria-label="Fermer">
            <X size={16} />
          </button>
        </div>

        <div className="flex-1 space-y-4 overflow-y-auto px-4 py-3">
          <div className="flex flex-wrap items-center gap-2">
            <button
              type="button"
              className="rounded-md border border-[var(--line)] bg-[var(--chrome-2)] px-2.5 py-1 text-[11px] text-[var(--ink-dim)] hover:border-[var(--accent)] hover:text-[var(--accent)]"
              onClick={resetToWaterTemps}
            >
              Préremplir T eau évap + cond
            </button>
            <span className="text-[10px] text-[var(--ink-faint)]">
              Ex. : balayer <span className="mono">evap_water_in.t_set_c</span> et{" "}
              <span className="mono">cond_water_in.t_set_c</span>
            </span>
          </div>

          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <span className="eyebrow">Axes à balayer</span>
              <button
                type="button"
                className="inline-flex items-center gap-1 text-[12px] text-[var(--accent)]"
                onClick={() => addAxis()}
                disabled={targets.length === 0}
              >
                <Plus size={12} /> Ajouter un axe
              </button>
            </div>

            {targets.length === 0 && (
              <p className="rounded-md border border-dashed border-[var(--line)] p-3 text-[12px] text-[var(--warn)]">
                Schéma vide — charge un exemple ou place des composants avant le multi-run.
              </p>
            )}

            {sweeps.map((sweep, i) => {
              const selected = targets.find((t) => t.path === sweep.path);
              const warnings =
                selected && selected.paramKey
                  ? getSweepWarnings(selected, diagramNodes, baseConfig)
                  : [];
              return (
                <div key={`${sweep.path}-${i}`} className="space-y-1">
                  <div className="grid grid-cols-[minmax(0,2fr)_minmax(0,1.4fr)_auto] items-end gap-2 rounded-md border border-[var(--line)] bg-[var(--chrome)] p-2.5">
                    <label className="flex min-w-0 flex-col gap-1">
                      <span className="eyebrow">Variable du schéma</span>
                      <select
                        className="ek-select w-full"
                        value={sweep.path}
                        onChange={(e) => pickTarget(i, e.target.value)}
                      >
                        {[...targetsByGroup.entries()].map(([group, list]) => (
                          <optgroup key={group} label={GROUP_LABEL[group]}>
                            {list.map((t) => (
                              <option key={t.path} value={t.path}>
                                {t.label}
                                {t.current !== undefined ? `  [actuel: ${t.current}]` : ""}
                              </option>
                            ))}
                          </optgroup>
                        ))}
                        {!selected && (
                          <option value={sweep.path}>{sweep.path} (hors liste)</option>
                        )}
                      </select>
                      <span className="mono truncate text-[10px] text-[var(--ink-faint)]">
                        {sweep.path}
                        {selected?.current !== undefined ? ` · actuel ${selected.current}` : ""}
                      </span>
                    </label>

                    <label className="flex min-w-0 flex-col gap-1">
                      <span className="eyebrow">
                        Valeurs {selected?.unit ? `(${selected.unit})` : ""} — séparées par des virgules
                      </span>
                      <input
                        className="ek-select mono w-full"
                        value={sweep.valuesText}
                        onChange={(e) => setAxis(i, { valuesText: e.target.value })}
                        placeholder={
                          selected?.paramKey === "t_set_c"
                            ? "10, 12, 14"
                            : "val1, val2, val3"
                        }
                      />
                    </label>

                    <button
                      type="button"
                      className="mb-0.5 rounded p-1.5 text-[var(--ink-faint)] hover:bg-[var(--chrome-2)]"
                      onClick={() => setSweeps((all) => all.filter((_, j) => j !== i))}
                      disabled={sweeps.length <= 1}
                      aria-label="Retirer l’axe"
                    >
                      <Trash2 size={14} />
                    </button>
                  </div>

                  {warnings.length > 0 && (
                    <div className="space-y-0.5 px-1">
                      {warnings.map((w, k) => (
                        <div
                          key={k}
                          className="flex items-start gap-1 text-[11px] text-[var(--warn)]"
                        >
                          <AlertTriangle size={11} className="mt-px shrink-0" />
                          <span>{w}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          <div className="flex flex-wrap items-center gap-4">
            <label className="flex items-center gap-2 text-[12px] text-[var(--ink-dim)]">
              Parallélisme
              <input
                type="number"
                min={1}
                max={16}
                className="ek-select mono w-16"
                value={concurrency}
                onChange={(e) => setConcurrency(Number(e.target.value) || 1)}
              />
            </label>
            <span className="mono text-[11px] text-[var(--ink-faint)]">
              {cases.length} cas · produit cartésien des axes
            </span>
          </div>

          {error && <p className="text-[12px] text-[var(--warn)]">{error}</p>}

          {results && (
            <>
              {chartData ? (
                <div className="rounded-md border border-[var(--line)] bg-[var(--chrome)] p-3">
                  <div className="mb-2 flex flex-wrap items-center justify-between gap-2">
                    <div className="flex items-center gap-2 text-[11px] text-[var(--ink-dim)]">
                      <label className="flex items-center gap-1">
                        <span className="text-[var(--ink-faint)]">X</span>
                        <select
                          className="rounded border border-[var(--line)] bg-[var(--panel)] px-1 py-0.5 text-[11px]"
                          value={xAxisPath ?? ""}
                          onChange={(e) => setXAxisPath(e.target.value || null)}
                          disabled={activeAxes.length <= 1}
                          title={activeAxes.length <= 1 ? "Un seul axe actif" : "Choisir l'axe X"}
                        >
                          {activeAxes.map((a) => (
                            <option key={a.path} value={a.path}>
                              {a.label}
                            </option>
                          ))}
                        </select>
                      </label>
                      <span className="text-[var(--ink-faint)]">vs</span>
                      <label className="flex items-center gap-1">
                        <span className="text-[var(--ink-faint)]">Y</span>
                        <select
                          className="max-w-[260px] rounded border border-[var(--line)] bg-[var(--panel)] px-1 py-0.5 text-[11px]"
                          value={ySeriesKey ?? ""}
                          onChange={(e) => setYSeriesKey(e.target.value || null)}
                        >
                          {availableSeries.map((opt) => (
                            <option key={opt.key} value={opt.key}>
                              {opt.label}
                              {opt.unit ? ` (${opt.unit})` : ""}
                            </option>
                          ))}
                        </select>
                      </label>
                    </div>
                    {chartData.mode === "multi" && (
                      <span className="eyebrow">séries : {chartData.sLabel}</span>
                    )}
                  </div>
                  <div style={{ width: "100%", height: 240 }}>
                    <ResponsiveContainer>
                      {chartData.mode === "single" ? (
                        <LineChart data={chartData.rows} margin={{ top: 8, right: 16, bottom: 24, left: 8 }}>
                          <CartesianGrid stroke="var(--line)" strokeDasharray="3 3" />
                          <XAxis
                            dataKey="x"
                            type="number"
                            domain={["dataMin", "dataMax"]}
                            tick={{ fontSize: 11, fill: "var(--ink-faint)" }}
                            label={{ value: chartData.xLabel, position: "bottom", fontSize: 10, fill: "var(--ink-faint)" }}
                          />
                          <YAxis domain={["auto", "auto"]} tick={{ fontSize: 11, fill: "var(--ink-faint)" }} />
                          <Tooltip contentStyle={{ fontSize: 11 }} />
                          <Line
                            type="monotone"
                            dataKey="y"
                            name={
                              availableSeries.find((s) => s.key === ySeriesKey)?.label ??
                              ySeriesKey ??
                              "Y"
                            }
                            stroke="var(--accent)"
                            dot={{ r: 3 }}
                            connectNulls
                            isAnimationActive={false}
                          />
                          <Brush dataKey="x" height={18} stroke="var(--accent)" travellerWidth={8} fill="transparent" />
                        </LineChart>
                      ) : (
                        <LineChart data={multiRows ?? []} margin={{ top: 8, right: 16, bottom: 24, left: 8 }}>
                          <CartesianGrid stroke="var(--line)" strokeDasharray="3 3" />
                          <XAxis
                            dataKey="x"
                            type="number"
                            domain={["dataMin", "dataMax"]}
                            tick={{ fontSize: 11, fill: "var(--ink-faint)" }}
                            label={{ value: chartData.xLabel, position: "bottom", fontSize: 10, fill: "var(--ink-faint)" }}
                          />
                          <YAxis domain={["auto", "auto"]} tick={{ fontSize: 11, fill: "var(--ink-faint)" }} />
                          <Tooltip contentStyle={{ fontSize: 11 }} />
                          <Legend wrapperStyle={{ fontSize: 11 }} />
                          {chartData.seriesVals.map((sv, idx) => (
                            <Line
                              key={sv}
                              type="monotone"
                              dataKey={sv}
                              name={`${chartData.sLabel} = ${sv}`}
                              stroke={
                                [
                                  "var(--accent)",
                                  "#10b981",
                                  "#f59e0b",
                                  "#3b82f6",
                                  "#a855f7",
                                  "#ef4444",
                                  "#14b8a6",
                                  "#ec4899",
                                ][idx % 8]
                              }
                              dot={{ r: 3 }}
                              connectNulls
                              isAnimationActive={false}
                            />
                          ))}
                          <Brush dataKey="x" height={18} stroke="var(--accent)" travellerWidth={8} fill="transparent" />
                        </LineChart>
                      )}
                    </ResponsiveContainer>
                  </div>
                </div>
              ) : results && results.length > 0 && activeAxes.length > 2 ? (
                <p className="rounded-md border border-dashed border-[var(--line)] p-2 text-[11px] text-[var(--ink-faint)]">
                  Trop d&apos;axes balayés ({activeAxes.length}) pour un graphique lisible (max 2).
                  Consultez le tableau ci-dessous.
                </p>
              ) : null}

              <div className="overflow-x-auto rounded-md border border-[var(--line)]">
                <table className="w-full text-left text-[11px]">
                  <thead className="bg-[var(--chrome)] text-[var(--ink-faint)]">
                    <tr>
                      <th className="px-2 py-1.5 font-medium">Cas</th>
                      <th className="px-2 py-1.5 font-medium">Statut</th>
                      <th className="px-2 py-1.5 font-medium">COP</th>
                      <th className="px-2 py-1.5 font-medium">Qcool kW</th>
                      <th className="px-2 py-1.5 font-medium">Wcomp kW</th>
                      <th className="px-2 py-1.5 font-medium">ms</th>
                    </tr>
                  </thead>
                  <tbody>
                    {results.map((r) => {
                      const k = extractKpis(r.result);
                      return (
                        <tr key={r.case.id} className="border-t border-[var(--line)]">
                          <td className="max-w-[280px] px-2 py-1.5 font-medium text-[var(--ink)]">
                            {r.case.label}
                          </td>
                          <td className="px-2 py-1.5 mono">
                            {r.ok ? k.status : r.error ?? "failed"}
                          </td>
                          <td className="px-2 py-1.5 mono tabular-nums">
                            {k.cop != null ? k.cop.toFixed(3) : "—"}
                          </td>
                          <td className="px-2 py-1.5 mono tabular-nums">
                            {k.qCoolKw != null ? k.qCoolKw.toFixed(2) : "—"}
                          </td>
                          <td className="px-2 py-1.5 mono tabular-nums">
                            {k.powerKw != null ? k.powerKw.toFixed(2) : "—"}
                          </td>
                          <td className="px-2 py-1.5 mono tabular-nums">{Math.round(r.durationMs)}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </>
          )}
        </div>

        <div className="flex items-center justify-between border-t border-[var(--line)] px-4 py-3">
          <span className="mono text-[11px] text-[var(--ink-faint)]">
            {running
              ? `Calcul ${progress.done}/${progress.total}…`
              : "Chaque cas = un POST /api/simulate (moteur CLI)"}
          </span>
          <button
            type="button"
            disabled={running || nodes.length === 0}
            onClick={() => void onRun()}
            className="flex items-center gap-1.5 rounded-md bg-[var(--accent)] px-4 py-1.5 text-[13px] font-semibold text-white disabled:opacity-50"
          >
            {running ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}
            {running ? "En cours" : "Lancer tous les cas"}
          </button>
        </div>
      </div>

      <style jsx>{`
        .toolish {
          border-radius: 6px;
          padding: 6px;
          color: var(--ink-dim);
        }
        .toolish:hover {
          background: var(--chrome-2);
        }
        :global(.ek-select) {
          border: 1px solid var(--line);
          background: var(--chrome-2);
          border-radius: 6px;
          padding: 4px 8px;
          font-size: 12px;
          color: var(--ink);
        }
      `}</style>
    </div>
  );
}
