import { Link } from "react-router-dom";
import type { RadarSweep } from "../../domain/types";
import { useI18n } from "../../i18n/I18nContext";
import { sanitizeReviewCopy } from "../../lib/reviewCopy";
import { Badge } from "../ui";

function isCrawlerSessionFailure(reason: string): boolean {
  return /crawler session|Chrome crawler|Chrome 登入已過期/i.test(reason);
}

export function SweepFunnelSummary({ sweep }: { sweep: RadarSweep }) {
  const { t, locale } = useI18n();
  const status = sweep.sweep_status ?? "complete";
  const statusKey = `radar.sweep.status.${status}`;
  const cells = [
    [t("radar.sweep.hits"), sweep.hit_count],
    [t("radar.sweep.deduped"), sweep.deduped_count ?? 0],
    [t("radar.sweep.prefilterPass"), sweep.prefilter_pass_count ?? 0],
    [t("radar.sweep.prefilterReject"), sweep.prefilter_rejected_count ?? 0],
    [t("radar.sweep.cached"), sweep.cached_judgment_count ?? 0],
    [t("radar.sweep.aiJudge"), sweep.judged_count],
    [t("radar.sweep.created"), sweep.created_count],
    [t("radar.sweep.deferred"), sweep.budget_deferred_count ?? 0],
  ] as const;
  return (
    <section className="hb-sweep-funnel" aria-label={t("radar.sweep.aria")}>
      <div className="hb-sweep-funnel__head"><div><h3>{t("radar.sweep.title")}</h3><p className="hb-radar-section__hint">{t("radar.sweep.hint")}</p></div><Badge tone={status === "complete" ? "success" : status === "failed" ? "danger" : "warning"}>{t(statusKey) === statusKey ? status : t(statusKey)}</Badge></div>
      <div className="hb-sweep-funnel__grid">{cells.map(([label, value]) => <div key={label}><span>{label}</span><strong>{value}</strong></div>)}</div>
      <div className="hb-sweep-funnel__credits"><span>{t("radar.sweep.credits", { search: sweep.credit_search ?? 0, map: sweep.credit_demand_map ?? 0, judge: sweep.credit_judge ?? 0 })}</span><strong>{t("radar.sweep.total", { n: sweep.credits_used })}</strong></div>
      {sweep.failed_reason ? (
        <p className="hb-banner-error" role="alert">
          {sanitizeReviewCopy(sweep.failed_reason, locale)}
          {isCrawlerSessionFailure(sweep.failed_reason) ? (
            <>
              {" "}
              <Link to="/app/settings">{t("radar.reconnectSearch")}</Link>
            </>
          ) : null}
        </p>
      ) : null}
      {status === "partial_budget" || status === "blocked_budget" ? <p className="hb-radar-section__hint">{t("radar.sweep.budgetHint")}</p> : null}
    </section>
  );
}
