import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { KEYS } from "../data/mock/keys";
import { I18nProvider } from "../i18n/I18nContext";
import { translate } from "../lib/i18n/messages";
import type { RadarWatch } from "../domain/types";
import { RadarWatchesPage } from "./RadarWatchesPage";

const t = (key: string, params?: Record<string, string | number>) => translate("zh-TW", key, params);

const backend = vi.hoisted(() => ({
  watches: [] as RadarWatch[],
  assigned: [] as Array<{ id: string; brandId: string; productId: string }>,
}));

vi.mock("../data/DataContext", () => {
  const repos = {
    scout: {
      async listBrands() { return [{ id: "b1", display_name: "澄光品牌", brief: "" }]; },
      async listProducts() {
        return [{
          id: "p1", brand_id: "b1", label: "舒緩精華", product_context: "",
          match_tags: [], pain_points: [], provider_capability_terms: [], provider_exclude_terms: [],
          created_at: 1, updated_at: 1,
        }];
      },
    },
    radar: {
      async listWatches() {
        return {
          list: backend.watches,
          total: backend.watches.length,
          active_count: backend.watches.filter((w) => w.status === "active").length,
          max_active: 5,
          profile_exists: true,
        };
      },
      async updateWatch(id: string, patch: Record<string, unknown>) {
        const w = backend.watches.find((x) => x.id === id)!;
        Object.assign(w, patch);
        return w;
      },
      async assignWatchProduct(id: string, brandId: string, productId: string) {
        backend.assigned.push({ id, brandId, productId });
        const w = backend.watches.find((x) => x.id === id)!;
        Object.assign(w, { brand_id: brandId, product_id: productId, context_mode: "product" });
        return w;
      },
      async getDemandMap() {
        return { product_id: "p1", state: "empty", pains: [], scenarios: [], audiences: [], exclusions: [], updated_at: 1 };
      },
      async suggestWatchTerms() { return []; },
    },
  };
  return { useRepos: () => repos };
});

function renderPage() {
  return render(
    <I18nProvider>
      <MemoryRouter>
        <RadarWatchesPage />
      </MemoryRouter>
    </I18nProvider>,
  );
}

beforeEach(() => {
  localStorage.setItem(KEYS.uiPrefs, JSON.stringify({ locale: "zh-TW", currency: "TWD", theme: "system" }));
  backend.assigned = [];
  backend.watches = [{
    id: "w1",
    terms: ["敏感肌"],
    exclude_terms: [],
    regions: [],
    status: "active",
    created_at: 1,
    updated_at: 1,
  } as RadarWatch];
});

describe("舊訂閱補綁品牌與產品", () => {
  it("選了品牌之後，產品選單不能跟著消失", async () => {
    renderPage();
    fireEvent.click(await screen.findByRole("button", { name: t("common.edit") }));

    fireEvent.change(screen.getByLabelText(t("radar.inbox.brand"), { exact: false }), { target: { value: "b1" } });

    const product = await screen.findByLabelText(t("radar.inbox.product"), { exact: false });
    expect(product).toBeTruthy();
    await waitFor(() => expect(screen.getByRole("option", { name: "舒緩精華" })).toBeTruthy());
  });

  it("儲存時把補綁的品牌與產品一起寫回", async () => {
    renderPage();
    fireEvent.click(await screen.findByRole("button", { name: t("common.edit") }));

    fireEvent.change(screen.getByLabelText(t("radar.inbox.brand"), { exact: false }), { target: { value: "b1" } });
    await waitFor(() => expect(screen.getByRole("option", { name: "舒緩精華" })).toBeTruthy());
    fireEvent.change(screen.getByLabelText(t("radar.inbox.product"), { exact: false }), { target: { value: "p1" } });
    fireEvent.click(screen.getByRole("button", { name: t("common.save") }));

    await waitFor(() => expect(backend.assigned).toEqual([{ id: "w1", brandId: "b1", productId: "p1" }]));
  });
});
