/* Globby Wizard — setup steps: Goal, Product (AI), Sector, Subcategory. */

// ---- Fetch real website text ----
// Priority: 1) Tavily (server-side, multi-page extract)  2) api/read-site (server-side direct)  3) Jina client-side
const _withTimeout = (p, ms) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error("timeout")), ms))]);

// Memo of completed AI site analyses, keyed by normalized URL + lang. Re-analyzing the
// same site (e.g. navigating back, or re-confirming) skips the full scrape + Claude call.
const _siteMemo = new Map();
const _siteKey = (url, lang) => { let u = (url || "").trim(); if (!/^https?:\/\//i.test(u)) u = "https://" + u; return u.toLowerCase() + "|" + lang; };

// Common product/catalog paths to probe (TR + EN).
const PRODUCT_PATHS = [
  "/products", "/urunler", "/catalog", "/katalog",
  "/solutions", "/cozumler", "/cözümler",
  "/services", "/hizmetler",
  "/about", "/hakkimizda",
];

// Tavily extract: homepage + common product paths in one call. Returns formatted multi-page content.
async function tavilyFetchSite(u) {
  try {
    const origin = u.replace(/\/$/, "");
    const urls = [u].concat(PRODUCT_PATHS.map(function (p) { return origin + p; }));
    const res = await _withTimeout(fetch("/api/tavily", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ op: "extract", urls: urls }),
    }), 28000);
    if (!res.ok) return "";
    const j = await res.json().catch(function () { return null; });
    if (!j || !Array.isArray(j.results) || !j.results.length) return "";
    const clean = function (t) { return (t || "").replace(/[ \t]+/g, " ").replace(/\n{4,}/g, "\n\n").trim(); };
    const parts = j.results.map(function (r, i) {
      const text = clean((r.raw_content || r.content || "")).slice(0, i === 0 ? 6000 : 3000);
      if (text.length < 80) return "";
      return "### PAGE: " + r.url + "\n" + text;
    }).filter(Boolean);
    if (!parts.length) return "";
    return parts.join("\n\n").slice(0, 14000);
  } catch (e) { return ""; }
}

// Server-side reader (api/read-site.js): proper UA, Jina fallback for SPAs.
async function serverFetchSite(u) {
  try {
    const res = await _withTimeout(fetch("/api/read-site", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ url: u }),
    }), 22000);
    if (!res.ok) return "";
    const j = await res.json().catch(function () { return null; });
    return (j && j.ok && j.text && j.text.length > 100) ? j.text : "";
  } catch (e) { return ""; }
}

// Client-side reader: Jina homepage + relevant sub-pages, with CORS-proxy/HTML-strip fallback.
async function jinaRead(target, ms) {
  try {
    const res = await _withTimeout(fetch("https://r.jina.ai/" + target), ms || 12000);
    if (res.ok) { const t = await res.text(); if (t && t.length > 120) return t; }
  } catch (e) { /* ignore */ }
  return "";
}

function relevantLinks(md, baseUrl, max) {
  const host = (baseUrl.match(/^https?:\/\/([^\/]+)/) || [])[1] || "";
  const want = /(product|ürün|urun|catalog|katalog|collection|koleksiyon|about|hakk|company|kurumsal|service|hizmet|solution|çözüm|cozum|sector|sektör|brand|marka)/i;
  const re = /\[([^\]]{1,80})\]\((https?:\/\/[^\s)]+)\)/g;
  const out = [], seen = {}; let m;
  while ((m = re.exec(md)) && out.length < (max || 3)) {
    const text = m[1], href = m[2].split("#")[0].replace(/\/$/, "");
    if (host && href.indexOf(host) < 0) continue;
    if (!want.test(text) && !want.test(href)) continue;
    if (seen[href] || href === baseUrl.replace(/\/$/, "")) continue;
    seen[href] = 1; out.push(href);
  }
  return out;
}

async function clientReadSite(u) {
  const clean = function (t) { return t.replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").trim(); };
  const home = await jinaRead(u, 13000);
  if (home) {
    let extra = "";
    const links = relevantLinks(home, u, 3);
    if (links.length) {
      const pages = await Promise.all(links.map(function (l) { return jinaRead(l, 9000); }));
      extra = pages.filter(Boolean).map(function (p, i) { return "\n\n### PAGE: " + links[i] + "\n" + clean(p).slice(0, 3500); }).join("");
    }
    return clean("### HOMEPAGE\n" + home + extra).slice(0, 11000);
  }
  const proxies = [
    function (x) { return "https://api.allorigins.win/raw?url=" + encodeURIComponent(x); },
    function (x) { return "https://corsproxy.io/?url=" + encodeURIComponent(x); },
    function (x) { return "https://thingproxy.freeboard.io/fetch/" + x; },
  ];
  let html = "";
  for (let i = 0; i < proxies.length; i++) {
    try { const res = await _withTimeout(fetch(proxies[i](u)), 12000); if (res.ok) { html = await res.text(); if (html && html.length > 200) break; } } catch (e) { /* next */ }
  }
  if (!html) return "";
  html = html.replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<!--[\s\S]*?-->/g, " ");
  const title = (html.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || "";
  const desc = (html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) || [])[1] || "";
  const ogd = (html.match(/<meta[^>]+property=["']og:[a-z]+["'][^>]+content=["']([^"']+)["']/gi) || []).join(" ").replace(/<[^>]+>/g, " ");
  const kw = (html.match(/<meta[^>]+name=["']keywords["'][^>]+content=["']([^"']+)["']/i) || [])[1] || "";
  const h = (html.match(/<h[1-3][^>]*>([\s\S]*?)<\/h[1-3]>/gi) || []).map(function (s) { return s.replace(/<[^>]+>/g, " "); }).join(" ");
  const body = html.replace(/<[^>]+>/g, " ").replace(/&[a-z#0-9]+;/gi, " ").replace(/\s+/g, " ").trim();
  return ([title, desc, ogd, kw, h].filter(Boolean).join(". ") + " | " + body).slice(0, 6000);
}

// Main entry: Tavily → server read-site → client Jina.
async function fetchSiteText(url) {
  let u = (url || "").trim();
  if (!/^https?:\/\//i.test(u)) u = "https://" + u;
  const tavily = await tavilyFetchSite(u);
  if (tavily && tavily.length > 500) return tavily;
  const server = await serverFetchSite(u);
  if (server && server.length > 300) return server;
  const client = await clientReadSite(u);
  if (client && client.length > 100) return client;
  throw new Error("no content");
}

// ---- Real AI website analysis: returns MULTIPLE product areas ----
async function aiAnalyze(url, lang) {
  const memoKey = _siteKey(url, lang);
  if (_siteMemo.has(memoKey)) return _siteMemo.get(memoKey);
  let content = "";
  try { content = await fetchSiteText(url); } catch (e) { content = ""; }
  // Site could not be read (blocks the scraper / Tavily + read-site + Jina all failed).
  // Do NOT ask the AI to guess from the domain name — that yields irrelevant products.
  // Return a "blocked" result so the UI shows a warning instead. (Not memoized: the site
  // may be reachable on a later retry.)
  if (!content) return { candidates: [], keywords: [], readContent: false, blocked: true, note: null };
  const tax = window.SECTORS.map(function (s) {
    var subs = s.subSectors.map(function (ss) { var m = window.SUBMETA[ss.slug]; return ss.slug + ":" + (m && m.en ? m.en : ss.name); }).join(", ");
    return s.id + " | " + s.nameEn + " \u2014 " + subs;
  }).join("\n");
  const prompt =
    "You are a senior foreign-trade analyst. Your job is to read a company's website carefully and map its REAL products/services to a fixed trade taxonomy.\n\n" +
    (content
      ? "Below is the ACTUAL content from \"" + url + "\" \u2014 homepage PLUS dedicated product/catalog/solution pages (each marked '### PAGE: <url>'). This multi-page capture was collected specifically to find every product family.\n\n" +
        "RULES:\n" +
        "1. Identify EVERY distinct product or service AREA. A multi-product company may span several sectors \u2014 list each as its own entry.\n" +
        "2. Base EVERYTHING on the scraped content. Pay special attention to product page headings, catalog category names, product family names, and model names \u2014 these are the most reliable signal.\n" +
        "3. Be SPECIFIC: use the exact product name from the content (e.g. 'PC Strand', 'IBO Self-Drilling Anchor', 'HEB Steel Beam') not vague labels ('construction', 'steel products').\n" +
        "4. For keywords: scan EVERY product page and list the specific product names / product family names you see. A company with 7 product families must produce at least 7 keywords. Do NOT include industry labels or company-type words.\n" +
        "5. If the company is a distributor/reseller vs manufacturer, reflect that in 'note'.\n" +
        "6. productTr = Turkish product name, productEn = English product name.\n\n" +
        "WEBSITE CONTENT:\n" + content + "\n\n"
      : "You could NOT read the site content for \"" + url + "\". Give a LOW-confidence best guess of likely trade area(s) from the domain name only.\n\n") +
    "Respond with STRICT JSON only, no prose: " +
    '{"areas":[{"productTr":"","productEn":"","sectorId":0,"subSlug":"","confidence":0}],"keywords":[""],"note":""}. ' +
    "Return 1 to 5 areas, MOST IMPORTANT / core business first. Each sectorId and subSlug MUST be the closest match from the taxonomy below. " +
    "keywords = up to 15 short English product-name terms \u2014 one per distinct product line/family, exactly as a procurement manager would type it into a search engine (e.g. post-tensioning company: 'PC Strands', 'Prestressing Wire', 'Post Tensioning', 'Anchor Wedges', 'Soil Nails', 'Rock Bolt', 'Drill Bits', 'Tunnel Support'; food company: 'Extra Virgin Olive Oil', 'Dried Apricots', 'Hazelnut Kernels'). Use the EXACT product names found in the content \u2014 do NOT invent terms or use broad sector labels. " +
    "note = one short sentence in " + (lang === "tr" ? "Turkish" : "English") + " describing the company. confidence = 0-100 reflecting how directly the content supports each area.\n\nTAXONOMY (sectorId | sector \u2014 subSlug:name):\n" + tax;
  const raw = await window.aiComplete(prompt);
  const j = JSON.parse(raw.slice(raw.indexOf("{"), raw.lastIndexOf("}") + 1));
  const areas = Array.isArray(j.areas) && j.areas.length ? j.areas : [j];
  const candidates = [];
  areas.slice(0, 5).forEach(function (a) {
    const sector = window.SECTORS.find(function (s) { return s.id === Number(a.sectorId); });
    if (!sector) return;
    const sub = sector.subSectors.find(function (x) { return x.slug === a.subSlug; }) || sector.subSectors[0];
    candidates.push({
      productName: lang === "tr" ? (a.productTr || a.productEn) : (a.productEn || a.productTr),
      sectorId: sector.id, subSlug: sub.slug,
      sectorName: lang === "tr" ? sector.name : sector.nameEn, subName: window.subName(sub, lang),
      confidence: Math.max(content ? 60 : 42, Math.min(98, Number(a.confidence) || (content ? 80 : 58))),
    });
  });
  if (!candidates.length) throw new Error("no candidates");
  const result = { candidates: candidates, keywords: (j.keywords || []).filter(Boolean).slice(0, 15), readContent: !!content, note: j.note || null };
  if (_siteMemo.size > 50) _siteMemo.delete(_siteMemo.keys().next().value);
  _siteMemo.set(memoKey, result);
  return result;
}

// ---- Product autocomplete index (niches + subsectors) ----
let _pidx = null, _pidxLang = null;
function productIndex(lang) {
  if (_pidx && _pidxLang === lang) return _pidx;
  const out = [];
  window.SECTORS.forEach(function (s) {
    s.subSectors.forEach(function (ss) {
      out.push({ l: window.subName(ss, lang), s: s.id, sub: ss.slug, n: null });
      (window.NICHES[ss.slug] || []).forEach(function (pair) {
        out.push({ l: nLabel(pair, lang), s: s.id, sub: ss.slug, n: pair[0] });
      });
    });
  });
  _pidx = out; _pidxLang = lang; return out;
}

// ---- Simulated website analyzer (deterministic per URL) ----
function analyzeSite(url, lang) {
  const u = (url || "").toLowerCase();
  const hints = [
    { re: /text|fabric|cotton|tekstil|giyim|moda|apparel|wear|knit|denim|garment/, sid: 1, sub: "hazir-giyim", tr: "Pamuklu örme t-shirt", en: "Cotton knit t-shirt" },
    { re: /home.?text|towel|havlu|nevresim|bedding|linen/, sid: 1, sub: "ev-tekstilleri", tr: "Pamuklu havlu seti", en: "Cotton towel set" },
    { re: /olive|zeyt/, sid: 5, sub: "zeytin-zeytinyagi", tr: "Sızma zeytinyağı", en: "Extra virgin olive oil" },
    { re: /nut|find|hazel|pistach|fıstık/, sid: 5, sub: "findik-sert-kabuklu", tr: "İç fındık", en: "Hazelnut kernels" },
    { re: /dried|kuru|apricot|raisin|fig/, sid: 5, sub: "kuru-meyve", tr: "Kuru kayısı", en: "Dried apricots" },
    { re: /food|gida|snack|confect|sweet|biscuit|candy/, sid: 5, sub: "sekerleme-cikolata", tr: "Lokum / şekerleme", en: "Turkish delight & confectionery" },
    { re: /cnc|machin|makin|tezgah/, sid: 2, sub: "cnc-makineleri", tr: "CNC işleme merkezi", en: "CNC machining center" },
    { re: /pump|valve|pompa|vana/, sid: 2, sub: "pompa-vana-uretimi", tr: "Santrifüj pompa", en: "Centrifugal pump" },
    { re: /furnit|mobilya|sofa|chair|koltuk/, sid: 18, sub: "ev-mobilyasi", tr: "Modüler oturma grubu", en: "Modular sofa set" },
    { re: /wood|ahsap|parke|floor|kapi|door/, sid: 18, sub: "ahsap-kapi-pencere", tr: "Ahşap iç kapı", en: "Wooden interior door" },
    { re: /chem|kimya/, sid: 3, sub: "endustriyel-kimyasallar", tr: "Endüstriyel kimyasal", en: "Industrial chemical" },
    { re: /paint|boya|coating|vernik/, sid: 3, sub: "boya-vernik", tr: "Endüstriyel toz boya", en: "Industrial powder coating" },
    { re: /cosmet|kozmet|skincare|beauty/, sid: 3, sub: "kozmetik-hammaddeleri", tr: "Kozmetik hammaddesi", en: "Cosmetic raw material" },
    { re: /auto|otomotiv|parts|spare|yedek/, sid: 4, sub: "otomotiv-yedek-parca", tr: "Fren balatası", en: "Brake pads" },
    { re: /tire|lastik/, sid: 4, sub: "lastik-uretimi", tr: "Binek araç lastiği", en: "Passenger car tire" },
    { re: /leather|deri/, sid: 20, sub: "deri-canta", tr: "Hakiki deri el çantası", en: "Genuine leather handbag" },
    { re: /shoe|ayakkabi|footwear/, sid: 20, sub: "deri-ayakkabi", tr: "Deri klasik ayakkabı", en: "Leather classic shoes" },
    { re: /steel|celik|demir/, sid: 6, sub: "boru-profil", tr: "Dikişsiz çelik boru", en: "Seamless steel pipe" },
    { re: /pipe|boru|profil/, sid: 10, sub: "plastik-boru-profil", tr: "PVC boru", en: "PVC pipe" },
    { re: /tile|seramik|ceramic|karo|porcel/, sid: 12, sub: "yapi-seramikleri-karo", tr: "Porselen yer karosu", en: "Porcelain floor tile" },
    { re: /glass|cam/, sid: 11, sub: "temperli-cam", tr: "Temperli cam", en: "Tempered glass" },
    { re: /plastic|plastik|polymer|granul/, sid: 10, sub: "plastik-granul-hammadde", tr: "Plastik granül (PP)", en: "PP plastic granules" },
    { re: /elec|elektr|led|light|cable|kablo/, sid: 8, sub: "aydinlatma", tr: "LED armatür", en: "LED luminaire" },
    { re: /software|yazilim|saas|tech|app|digital/, sid: 17, sub: "yazilim-gelistirme", tr: "Kurumsal yazılım", en: "Enterprise software" },
    { re: /fish|seafood|balik|su.?urun/, sid: 19, sub: "su-urunleri-yetistiricilik", tr: "Çipura / levrek", en: "Sea bream / sea bass" },
    { re: /marble|mermer|stone|tas/, sid: 9, sub: "mermer-dogal-tas", tr: "Mermer plaka", en: "Marble slabs" },
    { re: /agri|tarim|grain|tahil|fruit|vegetable|sebze|meyve/, sid: 7, sub: "yas-meyve-sebze", tr: "Yaş meyve sebze", en: "Fresh fruit & vegetables" },
  ];
  // deterministic hash
  let h = 0; for (let i = 0; i < u.length; i++) h = (h * 31 + u.charCodeAt(i)) % 100003;
  let m = hints.find(h2 => h2.re.test(u));
  // varied fallback across common SME export sectors when no keyword match
  const fallback = [hints[0], hints[2], hints[12], hints[8], hints[19], hints[3], hints[15], hints[22]];
  if (!m) m = fallback[h % fallback.length];
  const conf = m && hints.indexOf(m) >= 0 && /[a-z]/.test(u) && hints.find(h2 => h2.re.test(u)) ? 82 + (h % 13) : 71 + (h % 14);
  const sector = window.SECTORS.find(s => s.id === m.sid);
  const sub = sector.subSectors.find(x => x.slug === m.sub);
  const kw = window.WIZ.makeKeywords({ productName: (lang === "tr" ? m.tr : m.en), sector, sub, niches: [] }, lang).slice(0, 8);
  return { productName: lang === "tr" ? m.tr : m.en, sectorId: m.sid, subSlug: m.sub, sectorName: lang === "tr" ? sector.name : sector.nameEn, subName: window.subName(sub, lang), confidence: conf, keywords: kw };
}

// =================== GOAL ===================
function GoalStep(props) {
  const { L, lang, data, set, toast } = props;
  const imp = data.trade === "import";
  const toggle = (id) => {
    const adding = !data.goals.includes(id);
    const g = adding ? data.goals.concat(id) : data.goals.filter(x => x !== id);
    set({ goals: g });
    if (toast) toast(iT(id) + " · " + (adding ? L.flow.selectedToast : L.flow.removedToast));
  };
  const iT = (g) => {
    if (!imp) return L.goal.items[g].t;
    return ({ customers: L.imp.goalCustomersT, market: L.imp.goalMarketT, trend: L.imp.goalTrendT, email: L.goal.items.email.t })[g] || L.goal.items[g].t;
  };
  const iD = (g) => {
    if (!imp) return L.goal.items[g].d;
    return ({ customers: L.imp.goalCustomersD, market: L.imp.goalMarketD, trend: L.imp.goalTrendD, email: L.imp.goalEmailD })[g] || L.goal.items[g].d;
  };
  return React.createElement("div", null,
    React.createElement(StepHead, { eyebrow: L.goal.kicker, title: L.goal.title, sub: props.compact ? null : L.goal.sub, compact: props.compact, num: props.num }),
    React.createElement("div", { className: "field", style: { marginTop: 18 } },
      React.createElement("label", null, L.goal.tradeLabel),
      React.createElement("div", { className: "dualtoggle" },
        React.createElement(SelCard, { compact: true, icon: "ship", sel: data.trade === "export", title: L.product.tradeExport, desc: L.product.tradeExportD, onClick: () => set({ trade: "export" }) }),
        React.createElement(SelCard, { compact: true, icon: "import", sel: data.trade === "import", title: L.product.tradeImport, desc: L.product.tradeImportD, onClick: () => set({ trade: "import" }) }))),
    React.createElement("p", { className: "muted-hint", style: { marginTop: 22 } }, L.goal.multi),
    React.createElement("div", { className: "grid c2", style: { marginTop: 12 } },
      window.WIZ.GOALS.map(g =>
        React.createElement(SelCard, {
          key: g.id, icon: g.icon, sel: data.goals.includes(g.id),
          title: iT(g.id), desc: iD(g.id), onClick: () => toggle(g.id),
        })
      )
    )
  );
}
window.GoalStep = GoalStep;

// =================== PRODUCT (AI) ===================
function ProductStep(props) {
  const { L, lang, data, set, toast } = props;
  const [phase, setPhase] = useState(data.aiResult ? "done" : "idle"); // idle | running | done
  const [astep, setAstep] = useState(0);
  const [acOpen, setAcOpen] = useState(false);
  const acMatches = useMemo(() => {
    const q = (data.productName || "").trim().toLowerCase();
    if (q.length < 2) return [];
    const idx = productIndex(lang);
    return idx.filter(function (x) { return x.l.toLowerCase().indexOf(q) >= 0; }).slice(0, 8);
  }, [data.productName, lang]);

  const runAnalyze = () => {
    if (!data.website || !data.website.trim()) return;
    setPhase("running"); setAstep(0);
    const steps = L.product.analyzingSteps;
    let i = 0;
    const adv = () => { i++; setAstep(i); if (i < steps.length) setTimeout(adv, 520); };
    setTimeout(adv, 380);
    const finish = (r) => { set({ aiResult: r }); setAstep(steps.length); setPhase("done"); };
    const wrapHeuristic = () => { const s = analyzeSite(data.website, lang); return { candidates: [{ productName: s.productName, sectorId: s.sectorId, subSlug: s.subSlug, sectorName: s.sectorName, subName: s.subName, confidence: Math.min(s.confidence, 60) }], keywords: s.keywords, readContent: false, note: null }; };
    (async () => {
      try {
        if (window.hasAI) { const r = await aiAnalyze(data.website, lang); finish(r); }
        else { setTimeout(() => finish(wrapHeuristic()), 1700); }
      } catch (e) {
        // With AI available, a failure means we couldn't read/analyze the site — show the
        // blocked warning rather than an irrelevant domain-name guess. Offline/no-AI dev
        // keeps the local heuristic so the wizard is still usable without a backend.
        if (window.hasAI) finish({ candidates: [], keywords: [], readContent: false, blocked: true, note: null });
        else finish(wrapHeuristic());
      }
    })();
  };

  const confirmAI = (cand) => {
    props.confirmAnalysis({ productName: cand.productName, sectorId: cand.sectorId, subSlug: cand.subSlug, keywords: (data.aiResult.keywords || []).slice(), aiConfirmed: true });
    if (props.next) props.next();
  };
  const togglePick = (ci) => {
    const cur = data.aiPicks || [];
    const adding = !cur.includes(ci);
    set({ aiPicks: adding ? cur.concat(ci) : cur.filter(x => x !== ci) });
    if (toast && data.aiResult && data.aiResult.candidates[ci]) {
      toast(data.aiResult.candidates[ci].productName + " · " + (adding ? L.flow.selectedToast : L.flow.removedToast));
    }
  };
  const confirmPicks = () => {
    const picks = (data.aiPicks || []); if (!picks.length) return;
    const cands = data.aiResult.candidates;
    const primary = cands[picks[0]];
    props.confirmAnalysis({ productName: primary.productName, sectorId: primary.sectorId, subSlug: primary.subSlug, keywords: (data.aiResult.keywords || []).slice(), aiKeywords: (data.aiResult.keywords || []).slice(), products: picks.map(function (i) { return cands[i]; }), aiConfirmed: true });
    if (props.next) props.next();
  };

  return React.createElement("div", null,
    React.createElement(StepHead, { eyebrow: L.product.kicker, title: (data.trade === "import" ? L.product2.titleImport : L.product2.titleExport), sub: L.product.sub, compact: props.compact, num: props.num }),

    // mode tabs
    React.createElement("div", { className: "segtabs" },
      React.createElement("button", { className: data.mode === "web" ? "on" : "", onClick: () => set({ mode: "web" }) },
        React.createElement(GIcon, { name: "sparkles", size: 16 }), L.product.tabWeb),
      React.createElement("button", { className: data.mode === "manual" ? "on" : "", onClick: () => set({ mode: "manual" }) },
        React.createElement(GIcon, { name: "edit-3", size: 16 }), L.product.tabManual)
    ),

    data.mode === "web" ?
      React.createElement("div", null,
        React.createElement("div", { className: "field" },
          React.createElement("label", null, L.product.webLabel),
          React.createElement("div", { className: "inp-wrap has-lead" },
            React.createElement("span", { className: "lead-ic" }, React.createElement(GIcon, { name: "globe", size: 18 })),
            React.createElement("input", {
              className: "inp", placeholder: L.product.webPlaceholder, value: data.website || "",
              onChange: e => { set({ website: e.target.value }); if (phase === "done") { setPhase("idle"); set({ aiResult: null }); } },
              onKeyDown: e => { if (e.key === "Enter") runAnalyze(); },
            })
          ),
          React.createElement("p", { className: "field sublabel", style: { marginTop: 8, marginBottom: 0 } }, L.product.webHint)
        ),

        phase === "idle" ? React.createElement("button", { className: "btn btn-ghost-v", style: { marginTop: 16 }, onClick: runAnalyze, disabled: !(data.website && data.website.trim()) },
          React.createElement(GIcon, { name: "sparkles", size: 18 }), L.product.analyze) : null,

        phase === "running" ? React.createElement("div", { className: "analyzing" },
          React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 10, marginBottom: 10, fontWeight: 700, color: "var(--gb-violet-700)" } },
            React.createElement(GIcon, { name: "loader", size: 20, cls: "spin" }), L.product.analyzing),
          L.product.analyzingSteps.map((s, i) =>
            React.createElement("div", { key: i, className: "astep" + (i < astep ? " ok" : i === astep ? " on" : "") },
              React.createElement("span", { className: "dot" }, i < astep ? React.createElement(GIcon, { name: "check", size: 11, stroke: 3 }) : null), s))
        ) : null,

        phase === "done" && data.aiResult ? (
          // Site couldn't be read → show a clear warning + manual entry, NOT irrelevant guesses.
          !(data.aiResult.candidates && data.aiResult.candidates.length) ? React.createElement("div", { className: "ai-detect" },
            React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 6 } },
              React.createElement("span", { className: "ai-badge", style: { background: "var(--gb-warning)" } }, React.createElement(GIcon, { name: "info", size: 13 })),
              React.createElement("span", { style: { fontWeight: 700, color: "var(--gb-ink-900)" } }, L.product.blockedTitle)),
            React.createElement("p", { className: "muted-hint", style: { marginTop: 0, marginBottom: 12, color: "var(--gb-warning)" } }, L.product.blockedMsg),
            React.createElement("button", { className: "btn btn-primary btn-sm", onClick: () => set({ mode: "manual" }) },
              React.createElement(GIcon, { name: "edit-3", size: 16 }), L.product.enterManual))
          : React.createElement("div", { className: "ai-detect" },
          React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 6, flexWrap: "wrap" } },
            React.createElement("span", { className: "ai-badge" }, React.createElement(GIcon, { name: "sparkles", size: 13 }), "AI"),
            React.createElement("span", { style: { fontWeight: 700, color: "var(--gb-ink-900)" } }, data.aiResult.candidates.length > 1 ? L.product.analyzedMulti : L.product.analyzed)),
          (!data.aiResult.readContent) ? React.createElement("p", { className: "muted-hint", style: { marginTop: 0, marginBottom: 10, color: "var(--gb-warning)" } }, L.product.couldNotRead) :
            (data.aiResult.note ? React.createElement("p", { className: "muted-hint", style: { marginTop: 0, marginBottom: 10 } }, "\u201c" + data.aiResult.note + "\u201d") : null),
          (data.aiResult.candidates.length > 1) ? React.createElement("p", { className: "muted-hint", style: { marginTop: 0, marginBottom: 10 } }, L.product.pickMulti) : null,
          React.createElement("div", { className: "grid", style: { gap: 10 } },
            data.aiResult.candidates.map(function (c, ci) {
              const on = (data.aiPicks || []).includes(ci);
              return React.createElement("button", { key: ci, type: "button", className: "cand-card" + (on ? " sel" : ""), onClick: () => togglePick(ci) },
                React.createElement("span", { className: "cand-check" }, on ? React.createElement(GIcon, { name: "check", size: 14, stroke: 3 }) : null),
                React.createElement("span", { className: "cand-body" },
                  React.createElement("span", { className: "cand-prod" }, c.productName),
                  React.createElement("span", { className: "cand-sec" }, c.sectorName + " \u203a " + c.subName)),
                React.createElement("span", { className: "cand-conf" }, "%" + c.confidence));
            })),
          React.createElement("div", { style: { display: "flex", gap: 10, marginTop: 14, flexWrap: "wrap", alignItems: "center" } },
            React.createElement("button", { className: "btn btn-primary btn-sm", disabled: !((data.aiPicks || []).length), onClick: confirmPicks },
              L.product.continueSelected + ((data.aiPicks || []).length ? " (" + data.aiPicks.length + ")" : ""), React.createElement(GIcon, { name: "arrow-right", size: 16, stroke: 2.4 })),
            React.createElement("button", { className: "btn btn-back btn-sm", onClick: () => props.confirmAnalysis({ mode: "manual", productName: data.aiResult.candidates[0].productName, sectorId: data.aiResult.candidates[0].sectorId, subSlug: data.aiResult.candidates[0].subSlug }) }, L.product.editInstead)),
          React.createElement("p", { className: "muted-hint", style: { marginTop: 8 } }, L.product.analyzedNote),
          (data.aiResult.keywords && data.aiResult.keywords.length) ?
            React.createElement("div", { style: { marginTop: 12, padding: "10px 12px", background: "var(--gb-violet-50,#f5f3ff)", borderRadius: 8, border: "1px solid var(--gb-violet-200,#ddd6fe)" } },
              React.createElement("div", { style: { fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".06em", color: "var(--gb-violet-600,#7c3aed)", marginBottom: 7, display: "flex", alignItems: "center", gap: 5 } },
                React.createElement(GIcon, { name: "tag", size: 12 }), (L.kw && L.kw.kicker) || "Keywords"),
              React.createElement("div", { className: "chips" },
                data.aiResult.keywords.map(function (k, i) { return React.createElement(Chip, { key: i, kw: true }, k); }))
            ) : null
        )) : null
      )
      :
      // manual
      React.createElement("div", null,
        React.createElement("div", { className: "field", style: { position: "relative" } },
          React.createElement("label", null, L.product.nameLabel + " *"),
          React.createElement("input", {
            className: "inp", placeholder: L.product.acPlaceholder, value: data.productName || "", autoComplete: "off",
            onChange: e => { set({ productName: e.target.value }); setAcOpen(true); },
            onFocus: () => setAcOpen(true),
            onBlur: () => setTimeout(() => setAcOpen(false), 150),
          }),
          (acOpen && acMatches.length) ? React.createElement("div", { className: "ac-list" },
            acMatches.map((m, i) => {
              const sec = window.SECTORS.find(s => s.id === m.s);
              return React.createElement("button", {
                key: i, type: "button", className: "ac-row",
                onMouseDown: e => { e.preventDefault(); set({ productName: m.l, sectorId: m.s, subSlug: m.sub, niches: m.n ? [m.n] : [] }); setAcOpen(false); },
              },
                React.createElement("span", { className: "ac-l" }, m.l),
                React.createElement("span", { className: "ac-meta" }, (sec ? (lang === "tr" ? sec.name : sec.nameEn) : "") + (m.n ? " \u00b7 " + window.subName(sec.subSectors.find(x => x.slug === m.sub), lang) : "")));
            })) : null,
          React.createElement("p", { className: "field sublabel", style: { marginTop: 8, marginBottom: 0 } }, L.product.acHint)
        )
      ),

    // origin/operation country
    React.createElement("div", { className: "field" },
      React.createElement("label", null, (data.trade === "import" ? L.product2.countryImport : L.product2.countryExport)),
      React.createElement("select", { className: "sel", value: data.country || "TR", onChange: e => set({ country: e.target.value }) },
        window.COUNTRIES_ALL.map(c => React.createElement("option", { key: c.c, value: c.c }, c.f + "  " + (lang === "tr" ? c.tr : c.en))))
    )
  );
}
window.ProductStep = ProductStep;

// =================== SECTOR ===================
function SectorStep(props) {
  const { L, lang, data, set } = props;
  const [q, setQ] = useState("");
  // Collect sectorIds from all AI-picked candidates (or all candidates if nothing picked yet)
  const aiSids = useMemo(function () {
    const cands = data.aiResult ? data.aiResult.candidates : [];
    const picks = data.aiPicks && data.aiPicks.length ? data.aiPicks : cands.map(function (_, i) { return i; });
    return new Set(picks.map(function (i) { return cands[i] && Number(cands[i].sectorId); }).filter(Boolean));
  }, [data.aiResult, data.aiPicks]);
  const list = useMemo(() => {
    const term = q.trim().toLowerCase();
    return window.SECTORS.filter(s => !term || s.name.toLowerCase().includes(term) || s.nameEn.toLowerCase().includes(term));
  }, [q]);
  const pick = (id) => set({ sectorId: id, subSlug: (data.sectorId === id ? data.subSlug : null) });
  return React.createElement("div", null,
    React.createElement(StepHead, { eyebrow: L.sector.kicker, title: L.sector.title, sub: L.sector.sub, compact: props.compact, num: props.num }),
    React.createElement("div", { className: "search-row" },
      React.createElement(GIcon, { name: "search", size: 18 }),
      React.createElement("input", { placeholder: L.searchPlaceholder, value: q, onChange: e => setQ(e.target.value) })),
    React.createElement("div", { className: "grid c3", style: { marginTop: 16 } },
      window.selFirst(list, function (s) { return s.id === data.sectorId || aiSids.has(s.id); }).map(s =>
        React.createElement(SelCard, {
          key: s.id, compact: true, icon: s.icon, sel: data.sectorId === s.id,
          title: lang === "tr" ? s.name : s.nameEn,
          meta: (aiSids.has(s.id) ? "★ " + L.sector.detected : s.subSectors.length + " " + L.sector.subsectors),
          onClick: () => pick(s.id),
        })
      )
    )
  );
}
window.SectorStep = SectorStep;

// =================== SUBCATEGORY ===================
function SubStep(props) {
  const { L, lang, data, set } = props;
  const [q, setQ] = useState("");
  const sector = window.SECTORS.find(s => s.id === data.sectorId);
  // Collect subSlugs from AI-picked candidates for the current sector
  const aiSubs = useMemo(function () {
    const cands = data.aiResult ? data.aiResult.candidates : [];
    const picks = data.aiPicks && data.aiPicks.length ? data.aiPicks : cands.map(function (_, i) { return i; });
    return new Set(picks.map(function (i) { return cands[i] && cands[i].subSlug; }).filter(Boolean));
  }, [data.aiResult, data.aiPicks]);
  if (!sector) return null;
  const term = q.trim().toLowerCase();
  const list = sector.subSectors.filter(ss => !term || ss.name.toLowerCase().includes(term) || window.subName(ss, lang).toLowerCase().includes(term));
  return React.createElement("div", null,
    React.createElement(StepHead, { eyebrow: L.sub.kicker, title: L.sub.title, sub: fmt(L.sub.subFmt, { sector: lang === "tr" ? sector.name : sector.nameEn }), compact: props.compact, num: props.num }),
    React.createElement("div", { className: "search-row" },
      React.createElement(GIcon, { name: "search", size: 18 }),
      React.createElement("input", { placeholder: L.searchPlaceholder, value: q, onChange: e => setQ(e.target.value) })),
    React.createElement("div", { className: "grid c2", style: { marginTop: 16 } },
      window.selFirst(list, function (ss) { return ss.slug === data.subSlug || aiSubs.has(ss.slug); }).map(ss =>
        React.createElement(SelCard, {
          key: ss.slug, compact: true, sel: data.subSlug === ss.slug,
          title: window.subName(ss, lang),
          meta: aiSubs.has(ss.slug) ? "★ " + L.sub.detected : ((window.NICHES[ss.slug] || []).length + " " + L.niche.countSuffix),
          onClick: () => set({ subSlug: ss.slug, niches: [] }),
        })
      )
    )
  );
}
window.SubStep = SubStep;
