import type { ReactElement } from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { KEYS } from "../../data/mock/keys";
import type { Brand, BrandProduct, DemandMap } from "../../domain/types";
import { I18nProvider } from "../../i18n/I18nContext";
import { DemandMapEditor } from "./DemandMapEditor";
import { ProductWatchForm } from "./ProductWatchForm";

beforeEach(() => {
  localStorage.setItem(KEYS.uiPrefs, JSON.stringify({ locale: "zh-TW", currency: "TWD", theme: "system" }));
});

function wrap(ui: ReactElement) {
  return render(<I18nProvider>{ui}</I18nProvider>);
}

const brand: Brand = { id: "brand-1", display_name: "測試品牌", brief: "" };
const product: BrandProduct = {
  id: "product-1",
  brand_id: brand.id,
  label: "測試產品",
  product_context: "",
  match_tags: [],
  pain_points: [],
  provider_capability_terms: [],
  provider_exclude_terms: [],
  created_at: 1,
  updated_at: 1,
};
const map: DemandMap = {
  product_id: product.id,
  demand_input_version: "demand-1",
  map_version: 1,
  state: "incomplete",
  pain_phrases: [],
  scenario_phrases: [],
  desired_outcomes: [],
  solution_signals: [],
  exclusion_signals: [],
  source_basis: [],
  custom_phrases: [],
  updated_at: 1,
};

describe("巡樓必填欄位", () => {
  it("品牌與產品是選項，不必先填", () => {
    wrap(
      <ProductWatchForm
        brands={[brand]}
        products={[product]}
        brandId=""
        productId=""
        onBrandChange={vi.fn()}
        onProductChange={vi.fn()}
      />,
    );

    for (const name of ["品牌", "產品"]) {
      const field = screen.getByLabelText(name, { exact: false }) as HTMLSelectElement;
      expect(field.required).toBe(false);
      expect(field.closest("label")?.querySelector(".hb-field__required")).toBeNull();
    }
  });

  it("只在需求地圖必要的三個欄位顯示星號", () => {
    wrap(<DemandMapEditor product={product} map={map} onSave={vi.fn()} />);

    for (const name of ["使用者痛點", "使用情境", "解法訊號"]) {
      const field = screen.getByLabelText(name, { exact: false }) as HTMLTextAreaElement;
      expect(field.required).toBe(true);
      expect(field.closest("label")?.querySelector(".hb-field__required")?.textContent).toBe("*");
    }
    for (const name of ["期待結果", "排除訊號", "自訂補充"]) {
      const field = screen.getByLabelText(name, { exact: false }) as HTMLTextAreaElement;
      expect(field.required).toBe(false);
      expect(field.closest("label")?.querySelector(".hb-field__required")).toBeNull();
    }
  });

  it("填完三個必要欄位會通知巡樓表單可直接保存", () => {
    const onDraftChange = vi.fn();
    wrap(<DemandMapEditor product={product} map={map} onSave={vi.fn()} onDraftChange={onDraftChange} />);

    fireEvent.change(screen.getByLabelText("使用者痛點", { exact: false }), { target: { value: "泛紅" } });
    fireEvent.change(screen.getByLabelText("使用情境", { exact: false }), { target: { value: "日常保養" } });
    fireEvent.change(screen.getByLabelText("解法訊號", { exact: false }), { target: { value: "舒緩修護" } });

    expect(onDraftChange).toHaveBeenLastCalledWith(expect.objectContaining({ state: "ready" }));
  });
});
