File size: 10,198 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import Link from "next/link";
import { Button, CardSkeleton, Input } from "@/shared/components";
import { CLI_TOOLS } from "@/shared/constants/cliTools";
import { EXPECTED_CODE_COUNT } from "@/shared/schemas/cliCatalog";
import { CliToolCard, CliConceptCard, CliComparisonCard } from "@/shared/components/cli";
import { useToolBatchStatuses } from "@/shared/hooks/cli/useToolBatchStatuses";
import type { CliCatalogEntry } from "@/shared/schemas/cliCatalog";

// ── Static catalogue slice ────────────────────────────────────────────────────

const CODE_TOOLS: [string, CliCatalogEntry][] = Object.entries(CLI_TOOLS).filter(
  ([, tool]) => tool.category === "code" && tool.baseUrlSupport !== "none"
) as [string, CliCatalogEntry][];

// Cardinality guard (D15) β€” non-blocking, log only
if (CODE_TOOLS.length !== EXPECTED_CODE_COUNT) {
  console.warn(
    `[CliCodePage] Expected ${EXPECTED_CODE_COUNT} code tools, found ${CODE_TOOLS.length}. ` +
      "Check F1 catalog edits."
  );
}

// ── Types ─────────────────────────────────────────────────────────────────────

type DetectionFilter = "all" | "installed" | "not_installed";
type BaseUrlFilter = "all" | "full" | "partial";

interface ProviderConnection {
  isActive?: boolean;
  [key: string]: unknown;
}

interface ProvidersResponse {
  connections?: ProviderConnection[];
}

// ── Component ─────────────────────────────────────────────────────────────────

interface CliCodePageClientProps {
  machineId: string;
}

export default function CliCodePageClient({ machineId: _machineId }: CliCodePageClientProps) {
  const t = useTranslations("cliCode");
  const tCommon = useTranslations("cliCommon");

  // ── Batch statuses ──────────────────────────────────────────────────────────
  const { statuses, loading, refetch } = useToolBatchStatuses();

  // ── Providers ───────────────────────────────────────────────────────────────
  const [hasActiveProviders, setHasActiveProviders] = useState<boolean>(false);
  const [providersLoading, setProvidersLoading] = useState<boolean>(true);

  useEffect(() => {
    let cancelled = false;
    fetch("/api/providers")
      .then<ProvidersResponse>((res) => (res.ok ? res.json() : Promise.resolve({ connections: [] })))
      .then((data) => {
        if (cancelled) return;
        const active = (data.connections ?? []).filter((c) => c.isActive !== false);
        setHasActiveProviders(active.length > 0);
      })
      .catch(() => {
        if (!cancelled) setHasActiveProviders(false);
      })
      .finally(() => {
        if (!cancelled) setProvidersLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // ── Filters ─────────────────────────────────────────────────────────────────
  const [search, setSearch] = useState<string>("");
  const [detectionFilter, setDetectionFilter] = useState<DetectionFilter>("all");
  const [baseUrlFilter, setBaseUrlFilter] = useState<BaseUrlFilter>("all");

  const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
  }, []);

  const handleDetectionChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
    setDetectionFilter(e.target.value as DetectionFilter);
  }, []);

  const handleBaseUrlChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
    setBaseUrlFilter(e.target.value as BaseUrlFilter);
  }, []);

  // ── Filtered tools ──────────────────────────────────────────────────────────
  const filteredTools = useMemo<[string, CliCatalogEntry][]>(() => {
    const q = search.trim().toLowerCase();

    return CODE_TOOLS.filter(([id, tool]) => {
      // Search filter
      if (q) {
        const haystack =
          `${tool.name} ${tool.vendor} ${tool.description}`.toLowerCase();
        if (!haystack.includes(q)) return false;
      }

      // Detection filter
      if (detectionFilter !== "all") {
        const installed = statuses?.[id]?.detection.installed ?? false;
        if (detectionFilter === "installed" && !installed) return false;
        if (detectionFilter === "not_installed" && installed) return false;
      }

      // Base URL filter
      if (baseUrlFilter !== "all") {
        if (tool.baseUrlSupport !== baseUrlFilter) return false;
      }

      return true;
    });
  }, [search, detectionFilter, baseUrlFilter, statuses]);

  // ── Render ───────────────────────────────────────────────────────────────────
  const isLoadingOverall = loading || providersLoading;

  return (
    <div className="flex flex-col gap-6">

      {/* Concept card */}

      <CliConceptCard currentType="code" />



      {/* Comparison card */}

      <CliComparisonCard currentType="code" />



      {/* Header bar */}

      <div className="flex flex-col sm:flex-row sm:items-center gap-3 flex-wrap">

        {/* Title + subtitle */}

        <div className="flex-1 min-w-0">

          <h1 className="text-lg font-semibold text-text-main leading-tight">{t("pageTitle")}</h1>

          <p className="text-sm text-text-muted mt-0.5">{t("pageSubtitle")}</p>

        </div>



        {/* Refresh button */}

        <Button

          variant="secondary"

          size="sm"

          onClick={refetch}

          icon="refresh"

          aria-label={tCommon("card.refreshDetection")}

        >

          {tCommon("card.refreshDetection")}

        </Button>

      </div>



      {/* Filter row */}

      <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center">

        <div className="flex-1 min-w-0">

          <Input

            placeholder={t("searchPlaceholder")}

            value={search}

            onChange={handleSearchChange}

            icon="search"

          />

        </div>



        {/* Detection filter */}

        <div className="flex flex-col gap-1 min-w-[150px]">

          <label className="text-[11px] text-text-muted uppercase tracking-wide">

            {t("filterDetectionLabel")}

          </label>

          <select

            value={detectionFilter}

            onChange={handleDetectionChange}

            className="h-8 px-2 text-sm rounded-lg border border-black/10 dark:border-white/10 bg-surface text-text-main focus:outline-none focus:ring-2 focus:ring-primary/30"

          >

            <option value="all">{t("detectionAll")}</option>

            <option value="installed">{t("detectionInstalled")}</option>

            <option value="not_installed">{t("detectionNotFound")}</option>

          </select>

        </div>



        {/* Base URL filter */}

        <div className="flex flex-col gap-1 min-w-[150px]">

          <label className="text-[11px] text-text-muted uppercase tracking-wide">

            {t("filterBaseUrlLabel")}

          </label>

          <select

            value={baseUrlFilter}

            onChange={handleBaseUrlChange}

            className="h-8 px-2 text-sm rounded-lg border border-black/10 dark:border-white/10 bg-surface text-text-main focus:outline-none focus:ring-2 focus:ring-primary/30"

          >

            <option value="all">{t("baseUrlAll")}</option>

            <option value="full">{t("baseUrlFull")}</option>

            <option value="partial">{t("baseUrlPartial")}</option>

          </select>

        </div>

      </div>



      {/* Empty state β€” no active providers */}

      {!providersLoading && !hasActiveProviders && (

        <div className="rounded-lg border border-amber-500/40 bg-amber-500/5 p-4 flex items-start gap-3">

          <span className="material-symbols-outlined text-amber-500 flex-shrink-0">warning</span>

          <div className="flex-1 min-w-0">

            <p className="text-sm font-medium text-amber-600 dark:text-amber-400">

              {tCommon("detail.noActiveProviders")}

            </p>

            <p className="text-xs text-text-muted mt-0.5">

              {tCommon("detail.noActiveProvidersDesc")}

            </p>

            <Link

              href="/dashboard/providers"

              className="inline-flex items-center gap-1 mt-2 text-xs text-primary font-medium hover:underline"

            >

              {tCommon("detail.openProviders")}

            </Link>

          </div>

        </div>

      )}



      {/* Grid */}

      {isLoadingOverall ? (

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">

          {Array.from({ length: 6 }).map((_, i) => (

            <CardSkeleton key={i} />

          ))}

        </div>

      ) : (

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">

          {filteredTools.map(([id, tool]) => (

            <CliToolCard

              key={id}

              tool={tool}

              batchStatus={statuses?.[id] ?? null}

              detailHref={`/dashboard/cli-code/${id}`}

              hasActiveProviders={hasActiveProviders}

            />

          ))}

        </div>

      )}

    </div>
  );
}