import { useEffect, useState } from "react"; import { SERVICE_AREAS } from "./serviceAreas"; import { Button, Textarea } from "../ui"; import { useRepos } from "../../data/DataContext"; import type { Brand, BrandProduct } from "../../domain/types"; import { useI18n } from "../../i18n/I18nContext"; import { useFormatApiError } from "../../lib/apiErrors"; import { expandIncludeTerms } from "../../lib/threadsTerm"; import { ProductWatchForm } from "./ProductWatchForm"; function splitTerms(raw: string): string[] { return raw .split(/[\n,、]/) .map((s) => s.trim()) .filter(Boolean); } type Props = { /** firstSweepTriggered:後端已排第一輪,前端不該再叫使用者按「立即巡邏」。 */ onCreated: (result: { firstSweepTriggered: boolean }) => void; }; /** 今日空狀態:關鍵字就能開工,品牌/產品是選項。 */ export function QuickWatchStart({ onCreated }: Props) { const { t } = useI18n(); const repos = useRepos(); const formatError = useFormatApiError(); const [terms, setTerms] = useState(""); const [regions, setRegions] = useState([]); const [brandId, setBrandId] = useState(""); const [productId, setProductId] = useState(""); const [brands, setBrands] = useState([]); const [products, setProducts] = useState([]); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const scout = (repos as { scout?: { listBrands: () => Promise; listProducts: (id: string) => Promise } }).scout; useEffect(() => { if (!scout) return; void scout.listBrands().then(setBrands).catch(() => setBrands([])); }, [scout]); useEffect(() => { if (!scout || !brandId) { setProducts([]); return; } void scout.listProducts(brandId).then(setProducts).catch(() => setProducts([])); }, [scout, brandId]); async function submit() { const nextTerms = expandIncludeTerms(splitTerms(terms)); if (!nextTerms.length) { setError(t("radar.watches.threadsRequired")); return; } if ((brandId && !productId) || (!brandId && productId)) { setError(t("radar.watches.needBrandProductShort")); return; } setBusy(true); setError(""); try { const created = await repos.radar.createWatch({ terms: nextTerms, regions, enabled: true, brand_id: brandId || undefined, product_id: productId || undefined, }); onCreated({ firstSweepTriggered: Boolean(created.first_sweep_triggered) }); } catch (e) { setError(formatError(e)); } finally { setBusy(false); } } return (
{ e.preventDefault(); void submit(); }} >

{t("radar.start.hint")}