import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { test } from "bun:test";

import { CommandBar, commandInputRows } from "./CommandBar";

const sourcePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "CommandBar.tsx");

test("CommandBar releases the send lock on the next tick instead of waiting for the full agent turn", () => {
  const source = fs.readFileSync(sourcePath, "utf8");
  assert.match(source, /const submitted = props\.onSubmit\(next\);/u);
  assert.match(source, /window\.setTimeout\(\(\) => setSubmitting\(false\), 0\);/u);
  assert.doesNotMatch(source, /await props\.onSubmit\(next\)/u);
  assert.doesNotMatch(source, /\.finally\(\(\) => setSubmitting\(false\)\)/u);
});

test("CommandBar textarea grows to five physical lines then becomes scrollable", () => {
  assert.deepEqual(commandInputRows(""), { rows: 1, scrollable: false });
  assert.deepEqual(commandInputRows("one\ntwo\nthree"), { rows: 3, scrollable: false });
  assert.deepEqual(commandInputRows("1\n2\n3\n4\n5"), { rows: 5, scrollable: false });
  assert.deepEqual(commandInputRows("1\n2\n3\n4\n5\n6"), { rows: 5, scrollable: true });
});

test("CommandBar only locks editing for shell-level interaction disabled state", () => {
  const sessionRequiredHtml = renderToStaticMarkup(createElement(CommandBar, { ...baseCommandBarProps(), disabled: true, disabledReason: "session_required" }));
  assert.doesNotMatch(sessionRequiredHtml, /<textarea[^>]*id="command-input"[^>]*disabled/u);
  assert.match(sessionRequiredHtml, /<button[^>]*id="command-send"[^>]*disabled=""/u);

  const lockedHtml = renderToStaticMarkup(createElement(CommandBar, { ...baseCommandBarProps(), interactionDisabled: true }));
  assert.match(lockedHtml, /<select[^>]*id="code-agent-provider-profile"[^>]*disabled=""/u);
  assert.match(lockedHtml, /<textarea[^>]*id="command-input"[^>]*disabled=""/u);
  assert.match(lockedHtml, /<button[^>]*id="command-send"[^>]*disabled=""/u);
  assert.match(lockedHtml, /<button[^>]*id="command-clear"[^>]*disabled=""/u);
});

function baseCommandBarProps(): Parameters<typeof CommandBar>[0] {
  return {
    disabled: false,
    submitMode: "turn",
    targetTraceId: null,
    providerProfile: "deepseek",
    onProviderProfile: () => {},
    onSubmit: async () => {},
    onClear: () => {},
    pickedDraft: null,
    onPickedDraftConsumed: () => {},
    disabledReason: null,
    onTyping: () => {},
    onPickDraft: () => {}
  };
}
