"use client";

import { Badge } from "@solana/design-system/badge";
import { Braces, Clock3, Copy, Loader2, Play, Sparkles } from "lucide-react";
import type { ComponentProps, ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { MessageKey, TranslationValues } from "@/i18n/messages";
import { useTranslations } from "@/i18n/provider";
import { useDashboardUrlState } from "@/lib/dashboard-url-state";
import { normalizeApiKeyInput } from "@/lib/playground-api-keys";
import { setNestedValue } from "@/lib/set-nested-value";
import { HighlightedCode, type HighlightLanguage } from "@/lib/shiki-code";
import { cn } from "@/lib/utils";

export type ApiPlaygroundMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";

export interface ApiPlaygroundFieldOption {
  label: string;
  value: string;
}

export interface ApiPlaygroundFieldConfig {
  key: string;
  label: string;
  placeholder?: string;
  description?: string;
  defaultValue?: string;
  kind?: "text" | "select" | "textarea";
  options?: ApiPlaygroundFieldOption[];
  required?: boolean;
  valueType?: "string" | "boolean" | "number" | "string_array" | "json";
}

export interface ApiPlaygroundEndpointConfig {
  id: string;
  title: string;
  method: ApiPlaygroundMethod;
  path: string;
  pathFields: ApiPlaygroundFieldConfig[];
  bodyFields: ApiPlaygroundFieldConfig[];
  expectedResponse: unknown;
}

export interface ApiPlaygroundMessage {
  text: string;
  tone?: "critical" | "neutral";
}

interface ExecutionResult {
  ok: boolean;
  status: number;
  statusText: string;
  durationMs: number;
  authMode: "api_key" | "session";
  body: unknown;
}

interface ApiPlaygroundShellProps {
  apiBaseUrl?: string | null;
  apiKeySelector?: ReactNode;
  apiKeyValue: string;
  defaultEndpointId?: string;
  endpoints: ApiPlaygroundEndpointConfig[];
  leftMessages?: ApiPlaygroundMessage[];
  requiresApiKey?: boolean;
  productName: string;
  rightMessages?: ApiPlaygroundMessage[];
}

function getDefaultApiBaseUrl(): string {
  const base = process.env.NEXT_PUBLIC_SDP_API_BASE_URL ?? process.env.NEXT_PUBLIC_API_BASE_URL;
  return (base ?? "").replace(/\/$/, "");
}

function prettyJson(value: unknown): string {
  return JSON.stringify(value, null, 2);
}

function buildInitialFieldValues(
  endpoint: ApiPlaygroundEndpointConfig,
  preselect?: Record<string, string>
): Record<string, string> {
  return [...endpoint.pathFields, ...endpoint.bodyFields].reduce<Record<string, string>>(
    (values, field) => {
      // A URL-provided preselection (e.g. ?tokenId=…) wins over the field's
      // default, but only when it's usable: any value for a text field, or a
      // valid option for a select field. Otherwise fall back to the default.
      const desired = preselect?.[field.key];
      const isUsable =
        desired != null &&
        desired !== "" &&
        (field.kind !== "select" || (field.options ?? []).some((o) => o.value === desired));
      values[field.key] = isUsable ? desired : (field.defaultValue ?? "");
      return values;
    },
    {}
  );
}

function hasRequestBody(method: ApiPlaygroundMethod): boolean {
  return method !== "GET";
}

function serializeFieldValue(field: ApiPlaygroundFieldConfig, rawValue: string): unknown {
  if (field.valueType === "boolean") {
    return rawValue === "true";
  }

  if (field.valueType === "number") {
    return Number(rawValue);
  }

  if (field.valueType === "string_array") {
    return rawValue
      .split(",")
      .map((entry) => entry.trim())
      .filter(Boolean);
  }

  if (field.valueType === "json") {
    return JSON.parse(rawValue) as unknown;
  }

  return rawValue;
}

interface RequestBodyResult {
  body: unknown | null;
  invalidJsonField: string | null;
}

function buildRequestBody(
  fields: ApiPlaygroundFieldConfig[],
  values: Record<string, string>
): RequestBodyResult {
  if (fields.length === 0) {
    return { body: null, invalidJsonField: null };
  }

  const payload: Record<string, unknown> = {};

  for (const field of fields) {
    const rawValue = values[field.key] ?? "";
    if (!rawValue.trim()) {
      continue;
    }

    try {
      const value = serializeFieldValue(field, rawValue);
      if (field.key === "$body") {
        return { body: value, invalidJsonField: null };
      }
      setNestedValue(payload, field.key, value);
    } catch {
      return { body: null, invalidJsonField: field.label };
    }
  }

  return {
    body: Object.keys(payload).length > 0 ? payload : null,
    invalidJsonField: null,
  };
}

function resolvePath(
  endpoint: ApiPlaygroundEndpointConfig,
  values: Record<string, string>
): string {
  const [pathname, query = ""] = endpoint.path.split("?", 2);
  const fieldsByKey = new Map(endpoint.pathFields.map((field) => [field.key, field]));
  const replaceToken = (_match: string, token: string) => {
    const value = values[token];
    if (value?.trim()) {
      return encodeURIComponent(value.trim());
    }
    return fieldsByKey.get(token)?.required ? `{${token}}` : "";
  };
  const resolvedPathname = pathname.replace(/\{([^}]+)\}/g, replaceToken);
  const resolvedQuery = query
    .split("&")
    .filter(Boolean)
    .map((part) => part.replace(/\{([^}]+)\}/g, replaceToken))
    .filter((part) => {
      const separatorIndex = part.indexOf("=");
      return separatorIndex === -1 || part.slice(separatorIndex + 1) !== "";
    })
    .join("&");

  return resolvedQuery ? `${resolvedPathname}?${resolvedQuery}` : resolvedPathname;
}

function getMissingRequiredFields(
  endpoint: ApiPlaygroundEndpointConfig,
  values: Record<string, string>
): string[] {
  return [...endpoint.pathFields, ...endpoint.bodyFields]
    .filter((field) => field.required)
    .filter((field) => !(values[field.key] ?? "").trim())
    .map((field) => field.label);
}

function getMethodBadgeVariant(
  method: ApiPlaygroundMethod
): ComponentProps<typeof Badge>["variant"] {
  if (method === "DELETE") {
    return "danger";
  }

  if (method === "POST") {
    return "warning";
  }

  if (method === "PUT" || method === "PATCH") {
    return "info";
  }

  return "success";
}

function isValidSdpApiKey(rawValue: string): boolean {
  return /^sk_(test|live)_[A-Za-z0-9_-]+$/.test(rawValue);
}

function buildFetchSnippet(
  endpoint: ApiPlaygroundEndpointConfig,
  resolvedPath: string,
  requestBody: unknown | null,
  apiBaseUrl: string
): string {
  const lines = [
    'const API_KEY = "<paste_api_key_here>";',
    "",
    `const response = await fetch(\`${apiBaseUrl || "https://api.example.com"}${resolvedPath}\`, {`,
    `  method: "${endpoint.method}",`,
    "  headers: {",
    // biome-ignore lint/suspicious/noTemplateCurlyInString: Generated code intentionally contains a template placeholder.
    "    Authorization: `Bearer ${API_KEY}`,",
    '    "Content-Type": "application/json",',
    "  },",
  ];

  if (requestBody && hasRequestBody(endpoint.method)) {
    lines.push(`  body: JSON.stringify(${prettyJson(requestBody)}),`);
  }

  lines.push("});", "", "const data = await response.json();", "console.log(data);");

  return lines.join("\n");
}

function buildAiInstructions(
  endpoint: ApiPlaygroundEndpointConfig,
  fieldValues: Record<string, string>,
  requestBody: unknown | null,
  productName: string,
  t: (key: MessageKey, values?: TranslationValues) => string
): string {
  const pathParameterLines = endpoint.pathFields.length
    ? endpoint.pathFields
        .map(
          (field) =>
            `- ${field.label}: ${fieldValues[field.key]?.trim() || t("Shared.SharedComponents.fillBeforeSending")}`
        )
        .join("\n")
    : t("Shared.SharedComponents.noValue");
  const requestBodySection =
    requestBody && Object.keys(requestBody).length > 0 ? prettyJson(requestBody) : "{}";

  return [
    t("Shared.SharedComponents.aiInstructionIntro", {
      productName,
      method: endpoint.method,
      path: endpoint.path,
    }),
    "",
    t("Shared.SharedComponents.aiPathParameters"),
    pathParameterLines,
    "",
    t("Shared.SharedComponents.aiRequestBody"),
    requestBodySection,
    "",
    t("Shared.SharedComponents.aiInstructionOutro"),
  ].join("\n");
}

function buildResponseBody(
  executionResult: ExecutionResult | null,
  executeError: string | null,
  t: (key: MessageKey, values?: TranslationValues) => string
) {
  if (executionResult) {
    return prettyJson(executionResult.body);
  }

  if (executeError) {
    return prettyJson({ error: executeError });
  }

  return prettyJson({
    message: t("Shared.SharedComponents.runRequestToInspectOutput"),
  });
}

function resolvePanelContent(
  activePanel: "code" | "response" | "example",
  codeSnippet: string,
  responseBody: string,
  exampleBody: string
) {
  if (activePanel === "code") {
    return codeSnippet;
  }

  if (activePanel === "response") {
    return responseBody;
  }

  return exampleBody;
}

function getExecutionStatus(
  executionResult: ExecutionResult | null,
  executeError: string | null,
  t: (key: MessageKey, values?: TranslationValues) => string
): {
  statusToneVariant: ComponentProps<typeof Badge>["variant"];
  statusLabel: string;
} {
  if (executionResult) {
    return {
      statusToneVariant: executionResult.ok ? "success" : "danger",
      statusLabel: `${executionResult.status} ${executionResult.statusText}`,
    };
  }

  if (executeError) {
    return {
      statusToneVariant: "danger",
      statusLabel: t("Shared.SharedComponents.requestFailed"),
    };
  }

  return {
    statusToneVariant: "default",
    statusLabel: t("Shared.SharedComponents.ready"),
  };
}

function FieldLabel({ children, htmlFor }: { children: string; htmlFor: string }) {
  return (
    <label
      htmlFor={htmlFor}
      className="text-[12px] leading-5 font-medium tracking-[0.02em] text-secondary"
    >
      {children}
    </label>
  );
}

function EmptyState({ children }: { children: string }) {
  return (
    <div className="rounded-2xl border border-dashed border-border-default bg-surface-raised/50 px-4 py-5 text-sm text-tertiary">
      {children}
    </div>
  );
}

/** Shown in the Response panel before a request runs, instead of placeholder JSON. */
function ResponseEmptyState({ message }: { message: string }) {
  return (
    <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">
      <span className="flex size-11 items-center justify-center rounded-xl bg-fill-strong text-tertiary">
        <Braces className="size-5" aria-hidden="true" />
      </span>
      <p className="max-w-xs text-sm text-tertiary">{message}</p>
    </div>
  );
}

function MessageCard({ message }: { message: ApiPlaygroundMessage }) {
  return (
    <div
      className={cn(
        "rounded-xl border px-4 py-3 text-sm",
        message.tone === "critical"
          ? "border-error-border bg-error-bg text-error"
          : "border-border-default bg-surface-raised/60 text-secondary"
      )}
    >
      {message.text}
    </div>
  );
}

const MOBILE_SECTION_LABEL_KEYS = [
  { value: "request", labelKey: "Shared.SharedComponents.request" },
  { value: "output", labelKey: "Shared.SharedComponents.output" },
] as const satisfies readonly { value: "request" | "output"; labelKey: MessageKey }[];

const OUTPUT_PANEL_LABEL_KEYS = [
  { value: "code", labelKey: "Shared.SharedComponents.code" },
  { value: "response", labelKey: "Shared.SharedComponents.response" },
  { value: "example", labelKey: "Shared.SharedComponents.example" },
] as const satisfies readonly {
  value: "code" | "response" | "example";
  labelKey: MessageKey;
}[];

export function ApiPlaygroundShell({
  apiBaseUrl,
  apiKeySelector,
  apiKeyValue,
  defaultEndpointId,
  endpoints,
  leftMessages = [],
  requiresApiKey = false,
  productName,
  rightMessages = [],
}: ApiPlaygroundShellProps) {
  const t = useTranslations();
  const { replaceSearchParams, searchParams } = useDashboardUrlState();
  const initialEndpoint =
    endpoints.find((endpoint) => endpoint.id === defaultEndpointId) ?? endpoints[0];
  const initialEndpointId = initialEndpoint?.id ?? "";
  // Deep links can preselect the active resource, e.g. ?tokenId=… from the asset
  // management workspace, so the playground opens focused on that token. State
  // stays shareable because it's the URL-driven endpoint + token.
  const tokenIdParam = searchParams.get("tokenId");
  const preselectedFieldValues = useMemo(
    () => (tokenIdParam ? { tokenId: tokenIdParam } : undefined),
    [tokenIdParam]
  );
  const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
    initialEndpoint ? buildInitialFieldValues(initialEndpoint, preselectedFieldValues) : {}
  );
  const [mobileSection, setMobileSection] = useState<"request" | "output">("request");
  const [activePanel, setActivePanel] = useState<"code" | "response" | "example">("code");
  const [isExecuting, setIsExecuting] = useState(false);
  const [executeError, setExecuteError] = useState<string | null>(null);
  const [executionResult, setExecutionResult] = useState<ExecutionResult | null>(null);
  const [copiedAction, setCopiedAction] = useState<"code" | "ai" | null>(null);
  const endpointsRef = useRef(endpoints);
  const endpointParam = searchParams.get("endpoint");

  const activeEndpointId = endpoints.some((endpoint) => endpoint.id === endpointParam)
    ? (endpointParam ?? "")
    : initialEndpointId;
  const activeEndpoint =
    endpoints.find((endpoint) => endpoint.id === activeEndpointId) ?? initialEndpoint;
  const effectiveApiBaseUrl = useMemo(
    () => (apiBaseUrl ?? getDefaultApiBaseUrl()).replace(/\/$/, ""),
    [apiBaseUrl]
  );

  useEffect(() => {
    endpointsRef.current = endpoints;
  }, [endpoints]);

  const updateEndpointInUrl = useCallback(
    (endpointId: string) => {
      replaceSearchParams({
        endpoint: endpointId,
      });
    },
    [replaceSearchParams]
  );

  useEffect(() => {
    if (!activeEndpointId || endpointParam === activeEndpointId) {
      return;
    }

    updateEndpointInUrl(activeEndpointId);
  }, [activeEndpointId, endpointParam, updateEndpointInUrl]);

  useEffect(() => {
    if (!activeEndpointId) {
      return;
    }

    const endpoint = endpointsRef.current.find((entry) => entry.id === activeEndpointId);
    if (!endpoint) {
      return;
    }

    setFieldValues(buildInitialFieldValues(endpoint, preselectedFieldValues));
    setMobileSection("request");
    setActivePanel("code");
    setExecutionResult(null);
    setExecuteError(null);
  }, [activeEndpointId, preselectedFieldValues]);

  const requestBodyResult = useMemo(
    () => (activeEndpoint ? buildRequestBody(activeEndpoint.bodyFields, fieldValues) : null),
    [activeEndpoint, fieldValues]
  );
  const requestBody = requestBodyResult?.body ?? null;
  const resolvedPath = useMemo(
    () => (activeEndpoint ? resolvePath(activeEndpoint, fieldValues) : ""),
    [activeEndpoint, fieldValues]
  );
  const codeSnippet = useMemo(
    () =>
      activeEndpoint
        ? buildFetchSnippet(activeEndpoint, resolvedPath, requestBody, effectiveApiBaseUrl)
        : "",
    [activeEndpoint, effectiveApiBaseUrl, requestBody, resolvedPath]
  );
  const exampleBody = useMemo(
    () => (activeEndpoint ? prettyJson(activeEndpoint.expectedResponse) : "{}"),
    [activeEndpoint]
  );
  const responseBody = useMemo(
    () => buildResponseBody(executionResult, executeError, t),
    [executionResult, executeError, t]
  );
  const aiInstructions = useMemo(
    () =>
      activeEndpoint
        ? buildAiInstructions(activeEndpoint, fieldValues, requestBody, productName, t)
        : "",
    [activeEndpoint, fieldValues, productName, requestBody, t]
  );

  if (!activeEndpoint) {
    return null;
  }

  const panelContent = resolvePanelContent(activePanel, codeSnippet, responseBody, exampleBody);
  const panelLanguage: HighlightLanguage = activePanel === "code" ? "javascript" : "json";

  const getFieldId = (fieldKey: string) =>
    `${activeEndpoint.id}-${fieldKey.replace(/[^a-zA-Z0-9_-]/g, "-")}`;

  const updateFieldValue = (fieldKey: string, value: string) => {
    setFieldValues((current) => ({
      ...current,
      [fieldKey]: value,
    }));
  };

  const copyText = async (text: string, action: "code" | "ai") => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedAction(action);
      window.setTimeout(() => setCopiedAction(null), 1600);
    } catch {
      setCopiedAction(null);
    }
  };

  const handleReset = () => {
    setFieldValues(buildInitialFieldValues(activeEndpoint, preselectedFieldValues));
    setMobileSection("request");
    setActivePanel("code");
    setExecutionResult(null);
    setExecuteError(null);
  };

  const handleExecute = async () => {
    setExecuteError(null);
    setExecutionResult(null);

    const missingFields = getMissingRequiredFields(activeEndpoint, fieldValues);
    if (missingFields.length > 0) {
      setExecuteError(
        t("Shared.SharedComponents.completeRequiredFields", { fields: missingFields.join(", ") })
      );
      setActivePanel("response");
      return;
    }

    if (requestBodyResult?.invalidJsonField) {
      setExecuteError(
        t("Shared.SharedComponents.invalidJsonField", {
          field: requestBodyResult.invalidJsonField,
        })
      );
      setActivePanel("response");
      return;
    }

    const normalizedApiKey = normalizeApiKeyInput(apiKeyValue);
    const hasApiKey = Boolean(normalizedApiKey);

    if (hasApiKey && !isValidSdpApiKey(normalizedApiKey)) {
      setExecuteError(t("Shared.SharedComponents.invalidApiKeyFormat"));
      setActivePanel("response");
      return;
    }

    const startedAt = Date.now();
    setIsExecuting(true);

    try {
      const proxyResponse = await fetch("/api/playground/execute", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          method: activeEndpoint.method,
          path: resolvedPath,
          body: requestBody,
          apiKey: hasApiKey ? normalizedApiKey : null,
        }),
      });

      const envelope = (await proxyResponse.json()) as {
        ok?: boolean;
        status?: number;
        statusText?: string;
        body?: unknown;
        error?: string;
      };

      if (!proxyResponse.ok || envelope.status === undefined || envelope.statusText === undefined) {
        setExecuteError(envelope.error ?? t("Shared.SharedComponents.playgroundExecutionFailed"));
        setActivePanel("response");
        return;
      }

      setExecutionResult({
        ok: envelope.ok ?? false,
        status: envelope.status,
        statusText: envelope.statusText,
        durationMs: Date.now() - startedAt,
        authMode: hasApiKey ? "api_key" : "session",
        body: envelope.body ?? {},
      });
      setMobileSection("output");
      setActivePanel("response");
    } catch (error) {
      setExecuteError(
        error instanceof Error ? error.message : t("Shared.SharedComponents.requestExecutionFailed")
      );
      setMobileSection("output");
      setActivePanel("response");
    } finally {
      setIsExecuting(false);
    }
  };

  const { statusToneVariant, statusLabel } = getExecutionStatus(executionResult, executeError, t);

  return (
    <div className="relative flex h-full min-h-0 w-full flex-col overflow-hidden">
      <div className="pointer-events-none absolute top-0 bottom-0 left-1/2 hidden w-px -translate-x-1/2 bg-fill-strong lg:block" />
      <div className="grid shrink-0 border-b border-border-default lg:grid-cols-2">
        <div className="px-6 py-5">
          <div className="relative">
            <div className="pointer-events-none flex h-11 w-full items-center rounded-xl border border-border-default bg-surface-raised px-3 shadow-none">
              <span className="flex min-w-0 items-center gap-3 pr-8">
                <Badge variant={getMethodBadgeVariant(activeEndpoint.method)}>
                  {activeEndpoint.method}
                </Badge>
                <span className="truncate text-[15px] font-medium text-primary">
                  {activeEndpoint.title}
                </span>
              </span>
            </div>
            <select
              aria-label={t("Shared.SharedComponents.selectApiEndpoint")}
              className="absolute inset-0 h-full w-full cursor-pointer appearance-none rounded-xl bg-surface-raised text-primary opacity-0"
              value={activeEndpoint.id}
              onChange={(event) => updateEndpointInUrl(event.currentTarget.value)}
            >
              {endpoints.map((endpoint) => (
                <option
                  key={endpoint.id}
                  value={endpoint.id}
                  className="bg-surface-raised text-primary"
                >
                  {endpoint.method} {endpoint.title}
                </option>
              ))}
            </select>
            <svg
              aria-hidden="true"
              viewBox="0 0 16 16"
              className="pointer-events-none absolute top-1/2 right-4 h-4 w-4 -translate-y-1/2 text-muted"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.75"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="m4 6 4 4 4-4" />
            </svg>
          </div>
        </div>

        <div className="border-t border-border-default px-6 py-5 lg:border-t-0">
          <div className="flex justify-stretch lg:justify-end">{apiKeySelector ?? null}</div>
        </div>
      </div>

      <div className="border-b border-border-default px-6 py-4 lg:hidden">
        <div className="grid grid-cols-2 gap-1 rounded-full bg-fill-strong p-1">
          {MOBILE_SECTION_LABEL_KEYS.map(({ value, labelKey }) => (
            <button
              key={value}
              type="button"
              onClick={() => setMobileSection(value)}
              className={cn(
                "rounded-full px-4 py-2 text-sm font-medium transition-colors",
                mobileSection === value
                  ? "bg-surface-raised text-primary shadow-sm"
                  : "text-tertiary"
              )}
            >
              {t(labelKey)}
            </button>
          ))}
        </div>
      </div>

      <div className="flex min-h-0 flex-1 flex-col border-b border-border-default lg:grid lg:grid-cols-2">
        <div
          className={cn("min-h-0", mobileSection === "request" ? "flex-1" : "hidden", "lg:block")}
        >
          <div className="flex h-full min-h-0 flex-col px-6 py-6">
            {leftMessages.length > 0 ? (
              <div className="mb-4 shrink-0 space-y-4">
                {leftMessages.map((message) => (
                  <MessageCard
                    key={`${message.tone ?? "neutral"}-${message.text}`}
                    message={message}
                  />
                ))}
              </div>
            ) : null}

            <div className="min-h-0 flex-1 space-y-6 overflow-y-auto lg:pr-2">
              <section className="space-y-3">
                <h2 className="text-[18px] leading-6 font-medium text-primary">
                  {t("Shared.SharedComponents.pathParameters")}
                </h2>
                {activeEndpoint.pathFields.length === 0 ? (
                  <EmptyState>{t("Shared.SharedComponents.noPathParameters")}</EmptyState>
                ) : (
                  <div className="space-y-4">
                    {activeEndpoint.pathFields.map((field) => (
                      <div key={field.key} className="space-y-2">
                        <FieldLabel htmlFor={getFieldId(field.key)}>{field.label}</FieldLabel>
                        {field.description ? (
                          <p className="text-[13px] leading-5 text-tertiary">{field.description}</p>
                        ) : null}
                        {field.kind === "select" ? (
                          <select
                            id={getFieldId(field.key)}
                            value={fieldValues[field.key] ?? ""}
                            onChange={(event) =>
                              updateFieldValue(field.key, event.currentTarget.value)
                            }
                            className="h-11 w-full rounded-[var(--sdp-field-radius)] border border-border-default bg-surface-raised px-4 text-sm text-primary outline-none transition-[box-shadow,border-color] focus:border-border-strong focus:ring-2 focus:ring-border-default"
                          >
                            <option value="">
                              {field.placeholder ?? t("Shared.SharedComponents.selectValue")}
                            </option>
                            {(field.options ?? []).map((option) => (
                              <option key={option.value} value={option.value}>
                                {option.label}
                              </option>
                            ))}
                          </select>
                        ) : field.kind === "textarea" ? (
                          <textarea
                            id={getFieldId(field.key)}
                            value={fieldValues[field.key] ?? ""}
                            onChange={(event) =>
                              updateFieldValue(field.key, event.currentTarget.value)
                            }
                            placeholder={field.placeholder}
                            rows={8}
                            spellCheck={false}
                            className="w-full resize-y rounded-[var(--sdp-field-radius)] border border-border-default bg-surface-raised px-4 py-3 font-mono text-sm text-primary shadow-none outline-none transition-[box-shadow,border-color] focus:border-border-strong focus:ring-2 focus:ring-border-default"
                          />
                        ) : (
                          <Input
                            id={getFieldId(field.key)}
                            value={fieldValues[field.key] ?? ""}
                            onChange={(event) =>
                              updateFieldValue(field.key, event.currentTarget.value)
                            }
                            placeholder={field.placeholder}
                            className="h-11 rounded-[var(--sdp-field-radius)] border-border-default bg-surface-raised px-4 shadow-none"
                          />
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </section>

              <section className="space-y-3">
                <h2 className="text-[18px] leading-6 font-medium text-primary">
                  {t("Shared.SharedComponents.requestBody")}
                </h2>
                {activeEndpoint.bodyFields.length === 0 ? (
                  <EmptyState>{t("Shared.SharedComponents.noRequestBody")}</EmptyState>
                ) : (
                  <div className="space-y-4">
                    {activeEndpoint.bodyFields.map((field) => (
                      <div key={field.key} className="space-y-2">
                        <FieldLabel htmlFor={getFieldId(field.key)}>{field.label}</FieldLabel>
                        {field.description ? (
                          <p className="text-[13px] leading-5 text-tertiary">{field.description}</p>
                        ) : null}
                        {field.kind === "select" ? (
                          <select
                            id={getFieldId(field.key)}
                            value={fieldValues[field.key] ?? ""}
                            onChange={(event) =>
                              updateFieldValue(field.key, event.currentTarget.value)
                            }
                            className="h-11 w-full rounded-[var(--sdp-field-radius)] border border-border-default bg-surface-raised px-4 text-sm text-primary outline-none transition-[box-shadow,border-color] focus:border-border-strong focus:ring-2 focus:ring-border-default"
                          >
                            <option value="">
                              {field.placeholder ?? t("Shared.SharedComponents.selectValue")}
                            </option>
                            {(field.options ?? []).map((option) => (
                              <option key={option.value} value={option.value}>
                                {option.label}
                              </option>
                            ))}
                          </select>
                        ) : field.kind === "textarea" ? (
                          <textarea
                            id={getFieldId(field.key)}
                            value={fieldValues[field.key] ?? ""}
                            onChange={(event) =>
                              updateFieldValue(field.key, event.currentTarget.value)
                            }
                            placeholder={field.placeholder}
                            rows={10}
                            spellCheck={false}
                            className="w-full resize-y rounded-[var(--sdp-field-radius)] border border-border-default bg-surface-raised px-4 py-3 font-mono text-sm text-primary shadow-none outline-none transition-[box-shadow,border-color] focus:border-border-strong focus:ring-2 focus:ring-border-default"
                          />
                        ) : (
                          <Input
                            id={getFieldId(field.key)}
                            value={fieldValues[field.key] ?? ""}
                            onChange={(event) =>
                              updateFieldValue(field.key, event.currentTarget.value)
                            }
                            placeholder={field.placeholder}
                            className="h-11 rounded-[var(--sdp-field-radius)] border-border-default bg-surface-raised px-4 shadow-none"
                          />
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </section>
            </div>
          </div>
        </div>

        <div
          className={cn(
            "min-h-0 border-t border-border-default lg:border-t-0",
            mobileSection === "output" ? "flex-1" : "hidden",
            "lg:flex lg:h-full lg:min-h-0 lg:flex-col"
          )}
        >
          <div className="flex h-full min-h-0 flex-col px-6 py-6">
            {rightMessages.length > 0 ? (
              <div className="mb-4 shrink-0 space-y-4">
                {rightMessages.map((message) => (
                  <MessageCard
                    key={`${message.tone ?? "neutral"}-${message.text}`}
                    message={message}
                  />
                ))}
              </div>
            ) : null}

            <div className="mb-4 shrink-0 rounded-full bg-fill-strong p-1">
              <div className="grid grid-cols-3 gap-1">
                {OUTPUT_PANEL_LABEL_KEYS.map(({ value: tab, labelKey }) => (
                  <button
                    key={tab}
                    type="button"
                    onClick={() => setActivePanel(tab)}
                    className={cn(
                      "rounded-full px-4 py-2 text-sm font-medium capitalize transition-colors",
                      activePanel === tab
                        ? "bg-surface-raised text-primary shadow-sm"
                        : "text-tertiary"
                    )}
                  >
                    {t(labelKey)}
                  </button>
                ))}
              </div>
            </div>

            <div
              className="code-block-line-numbers group relative flex h-full min-h-0 flex-1 flex-col overflow-hidden rounded-[var(--button-radius-md)]"
              style={{
                border: "1px solid var(--code-block-border)",
                background: "var(--code-block-bg)",
                fontFamily: "var(--font-berkeley-mono), ui-monospace, monospace",
              }}
            >
              <div className="min-h-0 flex-1 overflow-hidden">
                {activePanel === "response" && !executionResult && !executeError ? (
                  <ResponseEmptyState
                    message={t("Shared.SharedComponents.runRequestToInspectOutput")}
                  />
                ) : (
                  <HighlightedCode content={panelContent} language={panelLanguage} />
                )}
              </div>
              <div
                className="flex shrink-0 flex-wrap items-center gap-2 px-4 py-3 text-sm"
                style={{
                  background: "var(--code-block-header-bg)",
                  color: "var(--code-block-header-text)",
                  boxShadow: "inset 0 1px 0 var(--code-block-header-border)",
                }}
              >
                <span className="leading-none text-tertiary">
                  {t("Shared.SharedComponents.status")}
                </span>
                <Badge
                  className="h-6 whitespace-nowrap px-2.5 leading-none"
                  variant={statusToneVariant}
                >
                  {statusLabel}
                </Badge>
                {executionResult ? (
                  <Badge className="h-6 whitespace-nowrap px-2.5 leading-none [&>span]:inline-flex [&>span]:items-center [&>span]:gap-1.5 [&>span]:leading-none">
                    <Clock3 className="inline-block size-3 shrink-0" aria-hidden="true" />
                    <span className="tabular-nums">
                      {t("Shared.SharedComponents.durationMilliseconds", {
                        duration: executionResult.durationMs,
                      })}
                    </span>
                  </Badge>
                ) : null}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid shrink-0 lg:grid-cols-2">
        <div className="px-6 py-5">
          <div className="flex flex-col gap-3">
            {requiresApiKey ? (
              <p className="text-sm leading-6 text-secondary">
                {t("Shared.SharedComponents.apiKeyRequired")}
              </p>
            ) : null}
            <div className="flex flex-wrap items-center gap-3">
              <Button
                type="button"
                onClick={handleExecute}
                disabled={isExecuting || requiresApiKey}
                className="h-10 rounded-[var(--button-radius-lg)] bg-primary px-4 text-on-primary hover:opacity-90 max-sm:flex-1 whitespace-nowrap"
                iconLeft={
                  isExecuting ? (
                    <Loader2 className="size-4 animate-spin" />
                  ) : (
                    <Play className="size-4 fill-current" />
                  )
                }
              >
                {t("Shared.SharedComponents.runRequest")}
              </Button>
              <Button
                type="button"
                variant="ghost"
                onClick={handleReset}
                className="h-10 rounded-[var(--button-radius-lg)] px-2 text-secondary hover:bg-transparent hover:text-primary"
              >
                {t("Shared.SharedComponents.reset")}
              </Button>
            </div>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-3 border-t border-border-default px-6 py-5 lg:border-t-0">
          <Button
            type="button"
            variant="outline"
            onClick={() => copyText(codeSnippet, "code")}
            className="h-10 rounded-[var(--button-radius-lg)] border-border-default bg-surface-raised px-4 max-sm:flex-1 whitespace-nowrap"
            iconLeft={<Copy className="size-4" />}
          >
            {copiedAction === "code"
              ? t("Shared.SharedComponents.copied")
              : t("Shared.SharedComponents.copyCode")}
          </Button>
          <Button
            type="button"
            variant="outline"
            onClick={() => copyText(aiInstructions, "ai")}
            className="h-10 rounded-[var(--button-radius-lg)] border-border-default bg-surface-raised px-4 max-sm:flex-1 whitespace-nowrap"
            iconLeft={<Sparkles className="size-4" />}
          >
            {copiedAction === "ai"
              ? t("Shared.SharedComponents.copied")
              : t("Shared.SharedComponents.aiInstructions")}
          </Button>
        </div>
      </div>
    </div>
  );
}
