import type { DemandMap, DemandMapPhrase } from "../../domain/types";
import { useI18n } from "../../i18n/I18nContext";
import { isThreadsSearchable, normalizeSearchTerm, searchableTermVariants } from "../../lib/threadsTerm";
import { Badge, Button } from "../ui";

export type QueryPlanGroup = { terms: string[]; basis: string; exclusion: string[] };

const MAX_GROUPS = 6;

function expandPhrases(list: DemandMapPhrase[] = []): DemandMapPhrase[] {
  const out: DemandMapPhrase[] = [];
  for (const item of list.filter((phrase) => phrase.enabled)) {
    const variants = searchableTermVariants(item.text).slice(0, 3);
    const basis = item.basis_text || item.text;
    for (const text of variants) {
      out.push({ ...item, text, basis_text: basis });
    }
  }
  return out;
}

/** Deterministic preview aligned with backend BuildQueryPlan: max 2 searchable tokens. */
export function buildQueryPlan(map: DemandMap): QueryPlanGroup[] {
  const pain = expandPhrases(map.pain_phrases);
  const scenario = expandPhrases(map.scenario_phrases);
  const outcomes = expandPhrases(map.desired_outcomes);
  const solutions = expandPhrases(map.solution_signals);
  const exclusion = (map.exclusion_signals ?? []).filter((item) => item.enabled).map((item) => item.text);
  const groups: QueryPlanGroup[] = [];
  const seen = new Set<string>();
  const add = (...parts: DemandMapPhrase[]) => {
    if (groups.length >= MAX_GROUPS) return;
    const terms = parts.map((part) => part.text).filter(Boolean);
    const query = normalizeSearchTerm(terms.join(" "));
    if (!query || !isThreadsSearchable(query) || seen.has(query.toLowerCase())) return;
    seen.add(query.toLowerCase());
    groups.push({ terms, basis: parts[0]?.basis_text || "", exclusion });
  };
  for (const item of pain) {
    add(item);
    if (groups.length >= MAX_GROUPS) break;
    for (const next of scenario) {
      add(item, next);
      if (groups.length >= MAX_GROUPS) break;
    }
    if (groups.length >= MAX_GROUPS) break;
    for (const next of outcomes) {
      add(item, next);
      if (groups.length >= MAX_GROUPS) break;
    }
    if (groups.length >= MAX_GROUPS) break;
  }
  if (!groups.length) {
    for (const item of scenario) {
      for (const next of solutions) {
        add(item, next);
        if (groups.length >= MAX_GROUPS) break;
      }
    }
  }
  if (!groups.length) {
    for (const item of [...scenario, ...outcomes, ...solutions]) {
      add(item);
      if (groups.length >= MAX_GROUPS) break;
    }
  }
  return groups;
}

export function QueryPlanPreview({
  map,
  onAdoptQueries,
}: {
  map: DemandMap;
  onAdoptQueries?: (queries: string[]) => void;
}) {
  const { t } = useI18n();
  const groups = buildQueryPlan(map);
  const queries = groups.map((group) => group.terms.join(" ")).filter(isThreadsSearchable);
  return (
    <section className="hb-query-plan" aria-label={t("radar.query.aria")}>
      <div className="hb-query-plan__head">
        <div><h4>{t("radar.query.title")}</h4><p className="hb-radar-section__hint">{t("radar.query.hint")}</p></div>
        <span className="hb-radar-section__hint">{t("radar.query.meta", { input: map.demand_input_version, map: map.map_version })}</span>
      </div>
      {groups.length ? (
        <>
          <div className="hb-query-plan__groups">
            {groups.map((group, index) => (
              <article className="hb-query-plan__group" key={`${group.basis}-${index}`}>
                <strong>{t("radar.query.group", { n: index + 1 })}</strong>
                <div className="hb-demand-map-editor__basis">
                  {group.terms.map((term) => <Badge key={term} tone="brand">{term}</Badge>)}
                </div>
                <small>{t("radar.query.basis", { text: group.basis || t("radar.query.defaultBasis") })}</small>
                {group.exclusion.length ? <small>{t("radar.query.exclude", { text: group.exclusion.join("、") })}</small> : null}
              </article>
            ))}
          </div>
          {onAdoptQueries && queries.length ? (
            <div className="hb-radar-actions">
              <Button type="button" variant="secondary" onClick={() => onAdoptQueries(queries)}>
                {t("radar.query.adopt")}
              </Button>
            </div>
          ) : null}
        </>
      ) : <p className="hb-radar-empty">{t("radar.query.empty")}</p>}
    </section>
  );
}
