/* Globby Wizard — targeting steps: Niche, Keywords, Problems, Persona. */

// =================== HS CODE PICKER ===================
function HsPicker(props) {
  const { data, set, lang, L } = props;
  const [q, setQ] = useState("");
  const [aiBusy, setAiBusy] = useState(false);
  const [aiList, setAiList] = useState(null);
  const sector = window.SECTORS.find(function (s) { return s.id === data.sectorId; });
  const sub = sector ? sector.subSectors.find(function (x) { return x.slug === data.subSlug; }) : null;
  const ctx = { niches: window.niceNiches(data, lang), productName: data.productName, keywords: data.keywords, subName: sub ? window.subName(sub, lang) : "", sectorName: sector ? (lang === "tr" ? sector.name : sector.nameEn) : "" };
  const ctxKey = JSON.stringify(data.niches) + "|" + JSON.stringify(data.nicheCustom) + "|" + data.productName + "|" + data.subSlug + "|" + JSON.stringify(data.keywords) + "|" + lang;
  const service = window.isServiceSub(data.subSlug, data.sectorId);
  useEffect(function () { setAiList(null); }, [ctxKey]);
  const suggested = useMemo(function () { return aiList || window.hsSuggest(ctx, service ? 15 : 10); }, [ctxKey, aiList, service]);
  const results = useMemo(function () { return window.hsSearch(q, 12); }, [q]);
  const picked = data.hsCodes || [];
  const toggle = function (code) { set({ hsCodes: picked.indexOf(code) >= 0 ? picked.filter(function (x) { return x !== code; }) : picked.concat(code) }); };
  const lbl = function (h) { return lang === "tr" ? h.tr : h.en; };
  const aiRerank = function () {
    if (!window.hasAI) return;
    setAiBusy(true);
    (async function () {
      try {
        const shortlist = window.hsSuggest(ctx, 30);
        const list = shortlist.map(function (h) { return h.c + " " + lbl(h); }).join("\n");
        const kws = (ctx.keywords || []).join(", ");
        const prompt = "You are an HS-code classification expert (6-digit Harmonized System). Product: \"" + (ctx.productName || "") + "\". Niches: " + ctx.niches.join(", ") + ". Sector: " + ctx.sectorName + " / " + ctx.subName + ". The company's website keywords are: " + kws + ". From the candidate list below choose up to 10 MOST accurate 6-digit codes, best first, and for each give a match percentage (0-100) reflecting how well the HS description fits the product and website keywords. Respond STRICT JSON only: {\"codes\":[{\"code\":\"\",\"match\":0}]}. Use ONLY codes from the list.\nCANDIDATES:\n" + list;
        const raw = await window.aiComplete(prompt);
        const j = JSON.parse(raw.slice(raw.indexOf("{"), raw.lastIndexOf("}") + 1));
        const mapped = (j.codes || []).map(function (o) {
          var code = String(o.code || o).replace(/\D/g, "").padStart(6, "0").slice(0, 6);
          var h = window.hsByCode(code); if (!h) return null;
          return { c: h.c, tr: h.tr, en: h.en, pct: Math.max(40, Math.min(99, Number(o.match) || 80)) };
        }).filter(Boolean);
        if (mapped.length) setAiList(mapped);
      } catch (e) { }
      setAiBusy(false);
    })();
  };
  const hsCard = function (h, on) {
    return React.createElement("button", { key: h.c, type: "button", className: "hs-row" + (on ? " sel" : ""), onClick: function () { toggle(h.c); } },
      React.createElement("span", { className: "hs-code" }, window.hsFmt(h.c)),
      React.createElement("span", { className: "hs-desc" }, lbl(h)),
      (h.pct != null) ? React.createElement("span", { className: "hs-pct" }, "%" + h.pct) : null,
      React.createElement(GIcon, { name: on ? "check" : "plus", size: 15, stroke: 2.4, cls: "hs-ic" }));
  };
  return React.createElement("div", { className: "field" },
    props.bare ? null : React.createElement("label", null, L.niche.hsLabel),
    props.bare ? null : React.createElement("p", { className: "sublabel" }, L.niche.hsHint),
    service ? React.createElement(Tip, { icon: "info" }, L.niche.hsService) : null,
    picked.length ? React.createElement("div", { className: "chips", style: { marginTop: 12, marginBottom: 4 } },
      picked.map(function (c) { const h = window.hsByCode(c); return React.createElement(Chip, { key: c, kw: true, removable: true, onClick: function () { toggle(c); } }, window.hsFmt(c) + "  " + (h ? lbl(h) : "")); })) : null,
    React.createElement("div", { className: "search-row", style: { marginTop: 14 } },
      React.createElement(GIcon, { name: "search", size: 16 }),
      React.createElement("input", { placeholder: L.niche.hsSearchPh, value: q, onChange: function (e) { setQ(e.target.value); } })),
    (q && results.length) ? React.createElement("div", { className: "hs-list", style: { marginTop: 8 } },
      results.map(function (h) { return hsCard(h, picked.indexOf(h.c) >= 0); })) : null,
    React.createElement("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, flexWrap: "wrap", margin: "14px 0 8px" } },
      React.createElement("span", { className: "muted-hint" }, L.niche.hsSuggested),
      (window.hasAI) ? React.createElement("button", { className: "btn btn-ghost-v btn-sm", onClick: aiRerank, disabled: aiBusy },
        React.createElement(GIcon, { name: aiBusy ? "loader" : "sparkles", size: 15, cls: aiBusy ? "spin" : "" }), aiBusy ? L.niche.hsAiBusy : L.niche.hsAi) : null),
    React.createElement("div", { className: "hs-list" },
      suggested.length ? suggested.map(function (h) { return hsCard(h, picked.indexOf(h.c) >= 0); }) : React.createElement("div", { className: "muted-hint", style: { padding: 8 } }, L.niche.hsNone))
  );
}
window.HsPicker = HsPicker;

// =================== TITLE PICKER (autocomplete over all titles) ===================
function TitlePicker(props) {
  const { data, set, lang, L } = props;
  const [q, setQ] = useState("");
  const sel = data.titles || [];
  const sectorIds = window.WIZ.titlesForTrade(data.sectorId, data.trade).map(function (t) { return t.id; });
  const extra = sel.filter(function (id) { return sectorIds.indexOf(id) < 0; }).map(function (id) { return window.WIZ.titleById(id); }).filter(Boolean);
  const toggle = function (id) { set({ titles: sel.indexOf(id) >= 0 ? sel.filter(function (x) { return x !== id; }) : sel.concat(id) }); };
  const ql = q.trim().toLowerCase();
  const results = ql ? window.WIZ.JOB_TITLES.filter(function (t) { return t.tr.toLowerCase().indexOf(ql) >= 0 || t.en.toLowerCase().indexOf(ql) >= 0; }).slice(0, 12) : [];
  return React.createElement("div", null,
    extra.length ? React.createElement("div", { className: "chips", style: { marginTop: 10 } },
      extra.map(function (t) { return React.createElement(Chip, { key: t.id, sel: true, removable: true, onClick: function () { toggle(t.id); } }, lang === "tr" ? t.tr : t.en); })) : null,
    React.createElement("div", { className: "search-row", style: { marginTop: 10 } },
      React.createElement(GIcon, { name: "search", size: 16 }),
      React.createElement("input", { placeholder: L.persona.titlePh, value: q, onChange: function (e) { setQ(e.target.value); } })),
    (q && results.length) ? React.createElement("div", { className: "country-list", style: { marginTop: 8 } },
      results.map(function (t) {
        const on = sel.indexOf(t.id) >= 0;
        return React.createElement("button", { key: t.id, type: "button", className: "country-row" + (on ? " sel" : ""), onClick: function () { toggle(t.id); } },
          React.createElement("span", { className: "cn" }, lang === "tr" ? t.tr : t.en),
          on ? React.createElement(GIcon, { name: "check", size: 15, stroke: 2.6, cls: "ck" }) : React.createElement(GIcon, { name: "plus", size: 15, cls: "ck" }));
      })) : null
  );
}
window.TitlePicker = TitlePicker;

// =================== INDUSTRY PICKER (autocomplete over the whole sector taxonomy) ===================
// Buyer industries = which sectors/sub-sectors buy from you. Those already live
// in the system (SECTORS → subSectors), so we let the user search the full
// taxonomy and add any match. Picks are stored as free-text in buyerIndCustom.
function IndustryPicker(props) {
  const { data, set, lang, L } = props;
  const [q, setQ] = useState("");
  const picked = data.buyerIndCustom || [];
  const add = function (label) {
    if (!label) return;
    if (picked.indexOf(label) < 0) set({ buyerIndCustom: picked.concat(label) });
    setQ("");
  };
  const ql = q.trim().toLowerCase();
  const results = useMemo(function () {
    if (ql.length < 2) return [];
    const out = [], seen = {};
    (window.SECTORS || []).forEach(function (s) {
      const sn = lang === "tr" ? s.name : s.nameEn;
      s.subSectors.forEach(function (ss) {
        const label = window.subName(ss, lang);
        if (!label) return;
        if ((label + " " + sn).toLowerCase().indexOf(ql) >= 0 && !seen[label.toLowerCase()]) {
          seen[label.toLowerCase()] = 1; out.push({ label: label, sector: sn });
        }
      });
      if (sn && sn.toLowerCase().indexOf(ql) >= 0 && !seen[sn.toLowerCase()]) {
        seen[sn.toLowerCase()] = 1; out.push({ label: sn, sector: "" });
      }
    });
    return out.slice(0, 14);
  }, [ql, lang]);
  return React.createElement("div", null,
    React.createElement("div", { className: "search-row", style: { marginTop: 12 } },
      React.createElement(GIcon, { name: "search", size: 16 }),
      React.createElement("input", { placeholder: L.persona.indSearchPh || L.persona.indPlaceholder, value: q, onChange: function (e) { setQ(e.target.value); } })),
    (ql.length >= 2 && results.length) ? React.createElement("div", { className: "country-list", style: { marginTop: 8 } },
      results.map(function (r, i) {
        const on = picked.indexOf(r.label) >= 0;
        return React.createElement("button", { key: i, type: "button", className: "country-row" + (on ? " sel" : ""), onClick: function () { add(r.label); } },
          React.createElement("span", { className: "cn" }, r.label,
            r.sector ? React.createElement("span", { style: { color: "var(--gb-ink-400)", fontSize: 12, marginLeft: 7 } }, "· " + r.sector) : null),
          on ? React.createElement(GIcon, { name: "check", size: 15, stroke: 2.6, cls: "ck" }) : React.createElement(GIcon, { name: "plus", size: 15, cls: "ck" }));
      })) : (ql.length >= 2 ? React.createElement("div", { className: "muted-hint", style: { padding: "8px 2px" } }, L.cp ? L.cp.empty : "—") : null)
  );
}
window.IndustryPicker = IndustryPicker;

// =================== NICHE ===================
function NicheStep(props) {
  const { L, lang, data, set } = props;
  const imp = data.trade === "import";
  const [custom, setCustom] = useState("");
  const raw = (window.NICHES[data.subSlug] && window.NICHES[data.subSlug].length)
    ? window.NICHES[data.subSlug]
    : window.WIZ.NICHE_BANK.map(n => [n.tr, n.en]);
  const sub = (() => { const s = window.SECTORS.find(x => x.id === data.sectorId); return s ? s.subSectors.find(x => x.slug === data.subSlug) : null; })();

  const toggle = (id) => {
    const n = data.niches.includes(id) ? data.niches.filter(x => x !== id) : data.niches.concat(id);
    set({ niches: n });
  };
  const addCustom = () => {
    const v = custom.trim(); if (!v) return;
    if (!(data.nicheCustom || []).includes(v)) set({ nicheCustom: (data.nicheCustom || []).concat(v) });
    setCustom("");
  };
  const removeCustom = (v) => set({ nicheCustom: (data.nicheCustom || []).filter(x => x !== v) });

  return React.createElement("div", null,
    React.createElement(StepHead, { eyebrow: L.niche.kicker, title: L.niche.title, sub: imp ? L.imp.nicheSub : L.niche.sub, ai: L.aiBadge, compact: props.compact, num: props.num }),
    sub ? React.createElement("p", { className: "muted-hint", style: { marginTop: -2, marginBottom: 4 } }, window.subName(sub, lang)) : null,
    React.createElement("div", { className: "chips", style: { marginTop: 18 } },
      window.selFirst(raw, function (pair) { return data.niches.includes(pair[0]); }).map((pair, i) => {
        const id = pair[0];
        return React.createElement(Chip, { key: id, sel: data.niches.includes(id), onClick: () => toggle(id) }, nLabel(pair, lang));
      })
    ),
    (data.aiKeywords && data.aiKeywords.length) ? React.createElement("div", { className: "field" },
      React.createElement("label", null, L.niche.aiKwLabel),
      React.createElement("div", { className: "chips" },
        data.aiKeywords.map(function (k, i) {
          const has = (data.nicheCustom || []).includes(k);
          return React.createElement(Chip, { key: i, suggest: !has, sel: has, onClick: () => set({ nicheCustom: has ? data.nicheCustom.filter(x => x !== k) : (data.nicheCustom || []).concat(k) }) }, k);
        }))
    ) : null,
    // custom / other
    React.createElement("div", { className: "field" },
      React.createElement("label", null, L.niche.otherTitle),
      React.createElement("div", { className: "add-inline" },
        React.createElement("input", { className: "inp", placeholder: L.niche.otherPlaceholder, value: custom, onChange: e => setCustom(e.target.value), onKeyDown: e => { if (e.key === "Enter") addCustom(); } }),
        React.createElement("button", { className: "icon-btn-v", onClick: addCustom }, React.createElement(GIcon, { name: "plus", size: 16 }), L.niche.addCustom)),
      (data.nicheCustom && data.nicheCustom.length) ? React.createElement("div", { className: "chips", style: { marginTop: 12 } },
        data.nicheCustom.map((v, i) => React.createElement(Chip, { key: i, sel: true, removable: true, onClick: () => removeCustom(v) }, v))) : null
    ),
    // note field
    React.createElement("div", { className: "field" },
      React.createElement("label", null, L.addNote, " ", React.createElement("span", { style: { color: "var(--gb-ink-300)", fontWeight: 500 } }, "· " + L.optional)),
      React.createElement("textarea", { className: "inp", placeholder: L.notePlaceholder, value: data.note || "", onChange: e => set({ note: e.target.value }) })
    )
  );
}
window.NicheStep = NicheStep;

// =================== HS CODE STEP ===================
function HsStep(props) {
  const { L, lang, data, set } = props;
  return React.createElement("div", null,
    React.createElement(StepHead, { eyebrow: L.niche.kicker, title: L.niche.hsLabel, sub: L.niche.hsHint, ai: L.aiBadge, compact: props.compact, num: props.num }),
    React.createElement(window.HsPicker, { data: data, set: set, lang: lang, L: L, bare: true })
  );
}
window.HsStep = HsStep;

// =================== KEYWORDS ===================
function KeywordStep(props) {
  const { L, lang, data, set } = props;
  const imp = data.trade === "import";
  const [add, setAdd] = useState("");
  const sector = window.SECTORS.find(s => s.id === data.sectorId);
  const sub = sector ? sector.subSectors.find(x => x.slug === data.subSlug) : null;

  // suggestion bank
  const suggestions = useMemo(() => {
    const base = window.WIZ.makeKeywords({ productName: data.productName, sector, sub, niches: data.niches }, lang);
    (data.aiKeywords || []).forEach(function (k) { base.push(k); });
    (data.niches || []).forEach(id => {
      const raw = window.NICHES[data.subSlug] || [];
      const pair = raw.find(p => p[0] === id);
      if (pair) base.push(nLabel(pair, lang));
    });
    (data.nicheCustom || []).forEach(function (c) { base.push(c); });
    return base.filter((v, i) => base.indexOf(v) === i);
  }, [data.productName, data.sectorId, data.subSlug, JSON.stringify(data.niches), JSON.stringify(data.nicheCustom), lang]);

  // re-seed when upstream context changes — AI keywords first, then generic suggestions to fill
  const kwKey = (data.subSlug || "") + "|" + JSON.stringify(data.niches) + "|" + JSON.stringify(data.nicheCustom) + "|" + lang;
  useEffect(() => {
    if (data._kwKey !== kwKey) {
      const ai = (data.aiKeywords || []).filter(Boolean);
      const extra = suggestions.filter(function (s) { return !ai.includes(s); });
      const merged = ai.concat(extra).filter(function (v, i, a) { return v && a.indexOf(v) === i; }).slice(0, 15);
      set({ keywords: merged.length ? merged : suggestions.slice(0, 8), _kwKey: kwKey });
    }
  }, [kwKey]);

  const remove = (k) => set({ keywords: data.keywords.filter(x => x !== k) });
  const addKw = (k) => { const v = (k || add).trim(); if (!v) return; if (!data.keywords.includes(v)) set({ keywords: data.keywords.concat(v) }); setAdd(""); };
  const remaining = suggestions.filter(s => !(data.keywords || []).includes(s));

  return React.createElement("div", null,
    React.createElement(StepHead, { eyebrow: L.kw.kicker, title: imp ? L.imp.kwTitle : L.kw.title, sub: L.kw.sub, ai: L.aiBadge, compact: props.compact, num: props.num }),
    React.createElement("div", { className: "field" },
      React.createElement("label", null, L.kw.yourKw),
      (data.keywords && data.keywords.length) ?
        React.createElement("div", { className: "chips" },
          data.keywords.map((k, i) => React.createElement(Chip, { key: i, kw: true, removable: true, onClick: () => remove(k) }, k)))
        : React.createElement("p", { className: "muted-hint" }, L.kw.empty),
      React.createElement("div", { className: "add-inline" },
        React.createElement("input", { className: "inp", placeholder: L.kw.addPlaceholder, value: add, onChange: e => setAdd(e.target.value), onKeyDown: e => { if (e.key === "Enter") addKw(); } }),
        React.createElement("button", { className: "icon-btn-v", onClick: () => addKw() }, React.createElement(GIcon, { name: "plus", size: 16 })))
    ),
    remaining.length ? React.createElement("div", { className: "field" },
      React.createElement("label", null, L.kw.suggested),
      React.createElement("div", { className: "chips" },
        remaining.map((s, i) => React.createElement(Chip, { key: i, suggest: true, onClick: () => addKw(s) }, s)))
    ) : null
  );
}
window.KeywordStep = KeywordStep;

// =================== PROBLEMS (optional) ===================
function ProblemStep(props) {
  const { L, lang, data, set } = props;
  const imp = data.trade === "import";
  const [busy, setBusy] = useState(false);
  const toggle = (id) => set({ problems: data.problems.includes(id) ? data.problems.filter(x => x !== id) : data.problems.concat(id) });
  const probItem = (id) => (id === "buyers" && imp) ? L.imp.problemBuyers : L.problems.items[id];
  const generic = window.WIZ.PROBLEMS;
  const sector = window.SECTORS.find(function (s) { return s.id === data.sectorId; });
  const sub = sector ? sector.subSectors.find(function (x) { return x.slug === data.subSlug; }) : null;
  const key = (data.subSlug || "") + "|" + JSON.stringify(data.niches) + "|" + lang;
  const spec = (data.genChallenges && data._chKey === key) ? data.genChallenges : [];
  const runGen = function () {
    if (!window.hasAI) return;
    setBusy(true);
    (async function () {
      try {
        const prompt = "List 7 realistic, COUNTRY-INDEPENDENT " + (data.trade === "import" ? "importing/sourcing" : "export") + " challenges that a company faces for this SPECIFIC product/niche. Do NOT mention any country, region or trade bloc (no EU, China, Asia, etc.) \\u2014 keep them universal. Product: \\\"" + (data.productName || "") + "\\\". Niches: " + window.niceNiches(data, lang).join(", ") + ". Sector: " + (sector ? (lang === "tr" ? sector.name : sector.nameEn) : "") + " / " + (sub ? window.subName(sub, lang) : "") + ". Respond STRICT JSON only: {\\\"challenges\\\":[\\\"\\\"]}. Each item a short phrase (3-7 words) in " + (lang === "tr" ? "Turkish" : "English") + ".";
        const raw = await window.aiComplete(prompt);
        const j = JSON.parse(raw.slice(raw.indexOf("{"), raw.lastIndexOf("}") + 1));
        const arr = (j.challenges || []).filter(Boolean).slice(0, 8);
        if (arr.length) set({ genChallenges: arr, _chKey: key });
      } catch (e) { }
      setBusy(false);
    })();
  };
  useEffect(function () { if (window.hasAI && data._chKey !== key && !busy) runGen(); }, [key]);

  return React.createElement("div", null,
    React.createElement(StepHead, { eyebrow: L.problems.kicker, title: (data.trade === "import" ? L.problems.titleImport : L.problems.title), sub: L.problems.sub, note: props.compact ? null : L.optional.toUpperCase(), compact: props.compact, num: props.num }),
    React.createElement("div", { className: "field" },
      React.createElement("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, flexWrap: "wrap", marginBottom: 8 } },
        React.createElement("label", { style: { margin: 0 } }, L.problems.specificLabel),
        (window.hasAI) ? React.createElement("button", { className: "btn btn-ghost-v btn-sm", onClick: runGen, disabled: busy },
          React.createElement(GIcon, { name: busy ? "loader" : "sparkles", size: 15, cls: busy ? "spin" : "" }), busy ? L.problems.aiBusy : L.problems.aiBtn) : null),
      busy && !spec.length ? React.createElement("p", { className: "muted-hint" }, L.problems.aiBusy) :
        (spec.length ? React.createElement("div", { className: "chips" },
          spec.map(function (c, i) { const id = "ch:" + c; return React.createElement(Chip, { key: i, sel: data.problems.includes(id), onClick: () => toggle(id) }, c); })) : null)),
    React.createElement("div", { className: "field" },
      React.createElement("label", null, L.problems.generalLabel),
      React.createElement("div", { className: "chips" },
        generic.map(id => React.createElement(Chip, { key: id, sel: data.problems.includes(id), onClick: () => toggle(id) }, probItem(id))))),
    React.createElement("div", { className: "field" },
      React.createElement("label", null, L.problems.moreLabel),
      React.createElement("textarea", { className: "inp", placeholder: L.problems.morePlaceholder, value: data.problemNote || "", onChange: e => set({ problemNote: e.target.value }) }))
  );
}
window.ProblemStep = ProblemStep;

// =================== PERSONA ===================
function PersonaStep(props) {
  const { L, lang, data, set } = props;
  const [custom, setCustom] = useState("");
  const [indCustom, setIndCustom] = useState("");
  const imp = data.trade === "import";
  const pickedSubs = (data.products && data.products.length) ? data.products.map(function (p) { return p.subSlug; }) : (data.subSlug ? [data.subSlug] : []);
  const metaList = pickedSubs.map(function (s) { return window.SUBMETA[s]; }).filter(Boolean);
  const sector0 = window.SECTORS.find(function (s) { return s.id === data.sectorId; });
  const sub0 = sector0 ? sector0.subSectors.find(function (x) { return x.slug === data.subSlug; }) : null;
  const typeSource = imp ? window.WIZ.SUPPLIER_TYPES : window.WIZ.BUYER_TYPES;
  const suggested = (function () {
    if (imp) return ["manufacturer", "exporter", "wholesaler", "distributor"];
    var t = []; metaList.forEach(function (m) { (m.b || []).forEach(function (id) { if (t.indexOf(id) < 0) t.push(id); }); });
    return t.length ? t : ["importer", "distributor", "wholesaler", "retailer"];
  })();
  const indBank = (function () {
    if (imp) return sub0 ? window.WIZ.supplierInds(window.subName(sub0, "tr"), window.subName(sub0, "en")) : [];
    var seen = {}, out = []; metaList.forEach(function (m) { (m.i || []).forEach(function (p) { if (!seen[p[0]]) { seen[p[0]] = 1; out.push(p); } }); });
    return out;
  })();

  const personaKey = JSON.stringify(pickedSubs) + "|" + data.trade;
  useEffect(() => {
    if (data._personaKey !== personaKey) {
      const tIds = (window.WIZ.titlesForTrade(data.sectorId, data.trade) || []).map(function (t) { return t.id; });
      set({ personas: suggested.slice(), buyerInds: indBank.map(function (p) { return p[0]; }), titles: tIds, personasInit: true, _personaKey: personaKey });
    }
  }, [personaKey]);

  const toggle = (id) => set({ personas: data.personas.includes(id) ? data.personas.filter(x => x !== id) : data.personas.concat(id) });
  const multi = (key, id) => { const cur = data[key] || []; const p = {}; p[key] = cur.indexOf(id) >= 0 ? cur.filter(x => x !== id) : cur.concat(id); set(p); };
  const toggleTitle = (id) => { const cur = data.titles || []; set({ titles: cur.indexOf(id) >= 0 ? cur.filter(x => x !== id) : cur.concat(id) }); };
  const toggleInd = (id) => set({ buyerInds: (data.buyerInds || []).includes(id) ? data.buyerInds.filter(x => x !== id) : (data.buyerInds || []).concat(id) });
  const addIndCustom = () => { const v = indCustom.trim(); if (!v) return; if (!(data.buyerIndCustom || []).includes(v)) set({ buyerIndCustom: (data.buyerIndCustom || []).concat(v) }); setIndCustom(""); };
  const removeIndCustom = (v) => set({ buyerIndCustom: (data.buyerIndCustom || []).filter(x => x !== v) });
  const addCustom = () => { const v = custom.trim(); if (!v) return; if (!(data.personaCustom || []).includes(v)) set({ personaCustom: (data.personaCustom || []).concat(v) }); setCustom(""); };
  const removeCustom = (v) => set({ personaCustom: (data.personaCustom || []).filter(x => x !== v) });

  const sector = window.SECTORS.find(s => s.id === data.sectorId);
  const sub = sector ? sector.subSectors.find(x => x.slug === data.subSlug) : null;
  const goalNames = (data.goals || []).map(g => L.goal.items[g].t).join(", ");
  const part = props.part || "who";
  const sf = window.selFirst;

  const whoBlocks = [
    React.createElement("div", { className: "field", key: "types" },
      React.createElement("label", null, imp ? L.imp.whoBuys : L.persona.whoBuys),
      React.createElement("div", { className: "grid c2", style: { marginTop: 6 } },
        sf(typeSource, function (b) { return data.personas.includes(b.id); }).map(b =>
          React.createElement(SelCard, {
            key: b.id, compact: true, icon: b.icon, sel: data.personas.includes(b.id),
            title: lang === "tr" ? b.tr : b.en, desc: lang === "tr" ? b.trH : b.enH,
            meta: suggested.includes(b.id) ? "★ " + L.aiSuggested : null,
            onClick: () => toggle(b.id),
          }))),
      React.createElement("div", { className: "add-inline", style: { marginTop: 12 } },
        React.createElement("input", { className: "inp", placeholder: L.persona.customPlaceholder, value: custom, onChange: e => setCustom(e.target.value), onKeyDown: e => { if (e.key === "Enter") addCustom(); } }),
        React.createElement("button", { className: "icon-btn-v", onClick: addCustom }, React.createElement(GIcon, { name: "plus", size: 16 }))),
      (data.personaCustom && data.personaCustom.length) ? React.createElement("div", { className: "chips", style: { marginTop: 12 } },
        data.personaCustom.map((v, i) => React.createElement(Chip, { key: i, sel: true, removable: true, onClick: () => removeCustom(v) }, v))) : null),
    React.createElement("div", { className: "field", key: "inds" },
      React.createElement("label", null, imp ? L.imp.indLabel : L.persona.indLabel),
      React.createElement("p", { className: "sublabel" }, imp ? L.imp.indHint : L.persona.indHint),
      React.createElement("div", { className: "chips" },
        sf(indBank, function (p) { return (data.buyerInds || []).includes(p[0]); }).map((pair, i) => React.createElement(Chip, { key: pair[0], sel: (data.buyerInds || []).includes(pair[0]), onClick: () => toggleInd(pair[0]) }, nLabel(pair, lang)))),
      React.createElement(window.IndustryPicker, { data: data, set: set, lang: lang, L: L }),
      React.createElement("p", { className: "field sublabel", style: { marginTop: 10, marginBottom: 0 } }, L.persona.indManualHint || ""),
      React.createElement("div", { className: "add-inline", style: { marginTop: 8 } },
        React.createElement("input", { className: "inp", placeholder: L.persona.indPlaceholder, value: indCustom, onChange: e => setIndCustom(e.target.value), onKeyDown: e => { if (e.key === "Enter") addIndCustom(); } }),
        React.createElement("button", { className: "icon-btn-v", onClick: addIndCustom }, React.createElement(GIcon, { name: "plus", size: 16 }))),
      (data.buyerIndCustom && data.buyerIndCustom.length) ? React.createElement("div", { className: "chips", style: { marginTop: 12 } },
        data.buyerIndCustom.map((v, i) => React.createElement(Chip, { key: i, sel: true, removable: true, onClick: () => removeIndCustom(v) }, v))) : null),
    React.createElement("div", { className: "field", key: "titles" },
      React.createElement("label", null, imp ? L.imp.titleLabel : L.persona.titleLabel),
      React.createElement("p", { className: "sublabel" }, imp ? L.imp.titleHint : L.persona.titleHint),
      React.createElement("div", { className: "chips" },
        sf(window.WIZ.titlesForTrade(data.sectorId, data.trade), function (t) { return (data.titles || []).includes(t.id); }).map(function (t) { return React.createElement(Chip, { key: t.id, sel: (data.titles || []).indexOf(t.id) >= 0, onClick: () => toggleTitle(t.id) }, lang === "tr" ? t.tr : t.en); })),
      React.createElement(TitlePicker, { data: data, set: set, lang: lang, L: L })),
  ];

  const prefBlocks = [
    React.createElement("div", { className: "field", key: "size" },
      React.createElement("label", null, imp ? L.imp.sizeLabel : L.persona.sizeLabel),
      React.createElement("p", { className: "sublabel" }, imp ? L.imp.sizeHint : L.persona.sizeHint),
      React.createElement("div", { className: "chips" },
        sf(window.WIZ.BUYER_SIZE, function (b) { return (data.buyerSize || []).indexOf(b.id) >= 0; }).map(b => React.createElement(Chip, { key: b.id, sel: (data.buyerSize || []).indexOf(b.id) >= 0, onClick: () => multi("buyerSize", b.id) }, lang === "tr" ? b.tr : b.en)))),
    React.createElement("div", { className: "field", key: "vol" },
      React.createElement("label", null, L.persona.volumeLabel),
      React.createElement("div", { className: "chips" },
        sf(window.WIZ.ORDER_VOLUME, function (b) { return (data.volume || []).indexOf(b.id) >= 0; }).map(b => React.createElement(Chip, { key: b.id, sel: (data.volume || []).indexOf(b.id) >= 0, onClick: () => multi("volume", b.id) }, lang === "tr" ? b.tr : b.en)))),
    React.createElement("div", { className: "field", key: "chan" },
      React.createElement("label", null, imp ? L.imp.channelLabel : L.persona.channelLabel),
      React.createElement("div", { className: "chips" },
        sf(window.WIZ.SALES_CHANNEL, function (b) { return (data.channel || []).indexOf(b.id) >= 0; }).map(b => React.createElement(Chip, { key: b.id, sel: (data.channel || []).indexOf(b.id) >= 0, onClick: () => multi("channel", b.id) }, lang === "tr" ? b.tr : b.en)))),
    React.createElement("div", { className: "field", key: "mk" },
      React.createElement("label", null, imp ? L.imp.marketsLabel : L.persona.marketsLabel),
      React.createElement("p", { className: "sublabel" }, imp ? L.imp.marketsHint : L.persona.marketsHint),
      React.createElement(CountryPicker, { selected: data.markets || [], onChange: arr => set({ markets: arr }), lang: lang, L: L })),
    React.createElement("div", { className: "summary-box", key: "sum" },
      React.createElement("h4", null, L.summary.title),
      React.createElement("div", { className: "summary-row" }, React.createElement("span", { className: "k" }, L.summary.product), React.createElement("span", { className: "v" }, data.productName || "—")),
      React.createElement("div", { className: "summary-row" }, React.createElement("span", { className: "k" }, L.summary.sector), React.createElement("span", { className: "v" }, (sector ? (lang === "tr" ? sector.name : sector.nameEn) : "—") + (sub ? " › " + window.subName(sub, lang) : ""))),
      (data.buyerInds && data.buyerInds.length || (data.buyerIndCustom || []).length) ? React.createElement("div", { className: "summary-row" }, React.createElement("span", { className: "k" }, imp ? L.imp.summaryInds : L.summary.buyerInds),
        React.createElement("span", { className: "v" }, niceInds(data, lang).join(", "))) : null,
      (data.niches.length || (data.nicheCustom || []).length) ? React.createElement("div", { className: "summary-row" }, React.createElement("span", { className: "k" }, L.summary.niche),
        React.createElement("span", { className: "v" }, niceNiches(data, lang).join(", "))) : null,
      data.personas.length ? React.createElement("div", { className: "summary-row" }, React.createElement("span", { className: "k" }, imp ? L.imp.summaryBuyers : L.summary.buyers),
        React.createElement("span", { className: "v" }, data.personas.map(id => { const b = typeSource.find(x => x.id === id); return b ? (lang === "tr" ? b.tr : b.en) : id; }).concat(data.personaCustom || []).join(", "))) : null,
      React.createElement("div", { className: "summary-row" }, React.createElement("span", { className: "k" }, imp ? L.imp.summaryMarkets : L.summary.markets),
        React.createElement("span", { className: "v" }, (data.markets && data.markets.length) ? data.markets.map(cc => window.countryName(cc, lang)).join(", ") : L.find.allMarkets)),
      data.keywords.length ? React.createElement("div", { className: "summary-row" }, React.createElement("span", { className: "k" }, L.summary.keywords), React.createElement("span", { className: "v" }, data.keywords.slice(0, 8).join(" · "))) : null,
      goalNames ? React.createElement("div", { className: "summary-row" }, React.createElement("span", { className: "k" }, L.summary.goal), React.createElement("span", { className: "v" }, goalNames)) : null),
  ];

  return React.createElement("div", null,
    part === "who"
      ? React.createElement(StepHead, { eyebrow: imp ? L.imp.personaKicker : L.persona.kicker, title: imp ? L.imp.personaTitle : L.persona.title, sub: imp ? L.imp.personaSub : L.persona.sub, ai: L.aiBadge, compact: props.compact, num: props.num })
      : React.createElement(StepHead, { eyebrow: imp ? L.imp.detailKicker : L.persona.detailKicker, title: imp ? L.imp.personaTitle : L.persona.title, sub: imp ? L.imp.detailNote : L.persona.detailNote, compact: props.compact, num: props.num }),
    part === "who" ? whoBlocks : prefBlocks
  );
}
window.PersonaStep = PersonaStep;

// helper: niche labels for current lang
window.niceNiches = function (data, lang) {
  const raw = window.NICHES[data.subSlug] || [];
  const sel = (data.niches || []).map(id => { const p = raw.find(x => x[0] === id); return p ? nLabel(p, lang) : id; });
  return sel.concat(data.nicheCustom || []);
};

// helper: buyer-industry labels for current lang (aggregated across picked products)
window.niceInds = function (data, lang) {
  if (data.trade === "import") {
    var sectorI = window.SECTORS.find(function (s) { return s.id === data.sectorId; });
    var subI = sectorI ? sectorI.subSectors.find(function (x) { return x.slug === data.subSlug; }) : null;
    var rawI = subI ? window.WIZ.supplierInds(window.subName(subI, "tr"), window.subName(subI, "en")) : [];
    var selI = (data.buyerInds || []).map(function (id) { var p = rawI.find(function (x) { return x[0] === id; }); return p ? nLabel(p, lang) : id; });
    return selI.concat(data.buyerIndCustom || []);
  }
  const subs = (data.products && data.products.length) ? data.products.map(function (p) { return p.subSlug; }) : [data.subSlug];
  let raw = []; subs.forEach(function (s) { const m = window.SUBMETA && window.SUBMETA[s]; if (m && m.i) raw = raw.concat(m.i); });
  const sel = (data.buyerInds || []).map(id => { const p = raw.find(x => x[0] === id); return p ? nLabel(p, lang) : id; });
  return sel.concat(data.buyerIndCustom || []);
};
