/* Globby — routing hub + destination pages: Market analysis, Email outreach. */

// goals → ordered unique destinations
window.destsForGoals = function (goals) {
  const out = [];
  const has = (g) => (goals || []).includes(g);
  if (has("market") || has("trend")) out.push("market");
  if (has("customers")) out.push("find");
  if (has("email")) out.push("email");
  if (!out.length) out.push("find");
  return out;
};

function destMeta(dest, L, imp) {
  const F = L.flow;
  if (dest === "market") return { icon: "globe-2", t: imp ? F.destMarketTimp : F.destMarketT, d: imp ? F.destMarketDimp : F.destMarketD };
  if (dest === "email") return { icon: "mail", t: F.destEmailT, d: F.destEmailD };
  return { icon: "users-round", t: imp ? F.destFindTimp : F.destFindT, d: imp ? F.destFindDimp : F.destFindD };
}
window.destMeta = destMeta;

// =================== HUB ===================
function HubPage(props) {
  const { L, lang, data, set, goRoute } = props;
  const imp = data.trade === "import";
  const dests = window.destsForGoals(data.goals);

  const [aiSummary, setAiSummary] = useState(data.aiSummary || null);
  const [aiLoading, setAiLoading] = useState(!data.aiSummary);
  const sentRef = React.useRef(false);

  useEffect(function () {
    if (sentRef.current) return;
    sentRef.current = true;
    window.track && window.track("hub_viewed", { dests: dests, lang: lang });
    (async function () {
      let summary = data.aiSummary || null;
      if (!summary && window.hasAI) {
        try {
          const sector = window.SECTORS ? window.SECTORS.find(function (s) { return s.id === data.sectorId; }) : null;
          const sub = sector ? sector.subSectors.find(function (x) { return x.slug === data.subSlug; }) : null;
          const sectorLabel = sector ? (lang === "tr" ? sector.name : sector.nameEn) : "";
          const subLabel = sub ? (" › " + window.subName(sub, lang)) : "";
          const mkts = (data.markets && data.markets.length)
            ? data.markets.slice(0, 4).map(function (cc) { return window.countryName(cc, lang); }).join(", ")
            : (lang === "tr" ? "tüm dünya" : "global markets");
          const niches = window.niceNiches ? window.niceNiches(data, lang).slice(0, 3).join(", ") : "";
          const prompt = lang === "tr"
            ? "Bir kullanıcı Globby ihracat/ithalat rehberini tamamladı. Bu kullanıcı için kısa, özgün ve motive edici bir plan özeti yaz (3-4 cümle, Türkçe). Şu bilgilerle yaz — Ürün: \"" + (data.productName || "—") + "\". İşlem: " + (imp ? "İthalat" : "İhracat") + ". Sektör: " + sectorLabel + subLabel + ". Hedef pazarlar: " + mkts + (niches ? ". Niş: " + niches : "") + ". Özet şunları içersin: ürünün potansiyeli, seçilen pazarların önemi, kullanıcıyı harekete geçirecek sonraki adım motivasyonu. Sadece özet paragrafını yaz, başlık veya liste ekleme."
            : "A user completed the Globby export/import wizard. Write a short, original and motivating plan summary (3-4 sentences, English). Use these details — Product: \"" + (data.productName || "—") + "\". Trade: " + (imp ? "Import" : "Export") + ". Sector: " + sectorLabel + subLabel + ". Target markets: " + mkts + (niches ? ". Niche: " + niches : "") + ". Cover: the product's potential, why the chosen markets matter, and a motivating next step. Write only the summary paragraph, no headings or bullet points.";
          const raw = await window.aiComplete(prompt);
          summary = raw.trim();
          setAiSummary(summary);
          set({ aiSummary: summary });
        } catch (e) {}
      }
      setAiLoading(false);
      if (!data.planSent) {
        set({ planSent: true });
        try {
          var planData = window.buildPlanSummary(data, lang);
          window.sendPlan(Object.assign({}, planData, { aiSummary: summary || null, contact: data.contact || null }));
        } catch (e) {}
      }
    })();
  }, []);

  const summaryLabel = lang === "tr" ? "Planınızın özeti" : "Your plan in brief";
  const summaryLoading = lang === "tr" ? "Özet hazırlanıyor…" : "Generating summary…";

  return React.createElement("div", { className: "hub" },
    React.createElement("div", { className: "hub-head" },
      React.createElement("div", { className: "hub-badge" }, React.createElement(GIcon, { name: "badge-check", size: 30 })),
      React.createElement("h2", { className: "step-title", style: { marginTop: 12 } }, L.flow.hubTitle),
      React.createElement("p", { className: "step-sub" }, L.flow.hubSub)),
    React.createElement("div", { className: "summary-box hub-ai-summary" },
      React.createElement("h4", null,
        React.createElement(GIcon, { name: "sparkles", size: 13, style: { display: "inline-block", verticalAlign: "-1px", marginRight: 6, color: "var(--gb-violet)" } }),
        summaryLabel),
      aiLoading
        ? React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, color: "var(--gb-ink-500)", fontSize: 14 } },
            React.createElement(GIcon, { name: "loader", size: 16, cls: "spin" }), summaryLoading)
        : React.createElement("p", { style: { margin: 0, fontSize: 15, lineHeight: 1.7, color: "var(--gb-ink-700)" } }, aiSummary || "")),
    React.createElement("div", { className: "hub-grid" },
      dests.map(function (d) {
        const m = destMeta(d, L, imp);
        return React.createElement("button", { key: d, type: "button", className: "hub-card", onClick: () => goRoute(d) },
          React.createElement("span", { className: "hub-ic" }, React.createElement(GIcon, { name: m.icon, size: 26 })),
          React.createElement("span", { className: "hub-card-body" },
            React.createElement("span", { className: "hub-card-t" }, m.t),
            React.createElement("span", { className: "hub-card-d" }, m.d)),
          React.createElement(GIcon, { name: "arrow-right", size: 20, cls: "hub-arrow" }));
      }))
  );
}
window.HubPage = HubPage;

// =================== MARKET ANALYSIS ===================
function MarketPage(props) {
  const { L, lang, data, goRoute, multiDest } = props;
  const imp = data.trade === "import";
  const sector = window.SECTORS.find(s => s.id === data.sectorId);
  const sub = sector ? sector.subSectors.find(x => x.slug === data.subSlug) : null;
  const markets = useMemo(function () {
    return window.WIZ.makeMarkets({ sectorId: data.sectorId, trade: data.trade, markets: data.markets }, lang, 14);
  }, [data.sectorId, data.trade, JSON.stringify(data.markets), lang]);

  const gated = !!(window.isGated && window.isGated());
  const viewedRef = React.useRef(false);
  useEffect(function () {
    if (viewedRef.current) return; viewedRef.current = true;
    window.track && window.track("market_viewed", { sectorId: data.sectorId, gated: gated, lang: lang });
  }, []);

  const bar = function (label, val, kind) {
    const lvl = val < 40 ? L.market.low : val < 70 ? L.market.mid : L.market.high;
    return React.createElement("div", { className: "mk-metric" },
      React.createElement("div", { className: "mk-metric-top" },
        React.createElement("span", null, label),
        React.createElement("span", { className: "mk-metric-v" }, kind === "comp" ? lvl : (kind === "pct" ? (val > 0 ? "+" : "") + val + "%" : val))),
      React.createElement("div", { className: "mk-bar" }, React.createElement("div", { className: "mk-bar-fill " + (kind || ""), style: { width: Math.max(6, Math.min(100, kind === "pct" ? (val + 4) * 3.5 : val)) + "%" } })));
  };

  return React.createElement("div", { className: "route-page" },
    React.createElement("div", { className: "route-head" },
      React.createElement("div", null,
        React.createElement("h2", { className: "step-title" }, L.market.title),
        React.createElement("p", { className: "step-sub" }, (imp ? L.market.subImp : L.market.subExp) + (sub ? "  ·  " + (lang === "tr" ? sector.name : sector.nameEn) + " › " + window.subName(sub, lang) : ""))),
      React.createElement("span", { className: "demo-note" }, React.createElement(GIcon, { name: "info", size: 14 }), L.market.demoNote)),
    // metric grid — full cards when open; locked teaser (rank/flag/name/fit only) when gated
    React.createElement("div", { className: "mk-grid" + (gated ? " mk-grid-teaser" : "") },
      (gated ? markets.slice(0, 6) : markets).map(function (m, i) {
        return React.createElement("div", { key: m.cc, className: "mk-card" + (gated ? " mk-card-locked" : "") },
          React.createElement("div", { className: "mk-card-head" },
            React.createElement("span", { className: "mk-rank" }, "#" + (i + 1)),
            React.createElement("span", { className: "mk-flag" }, m.country.f),
            React.createElement("span", { className: "mk-name" }, lang === "tr" ? m.country.tr : m.country.en),
            React.createElement("span", { className: "mk-score" }, m.score, React.createElement("span", { className: "mk-score-l" }, L.market.fit))),
          gated ? null : React.createElement("div", { className: "mk-metrics" },
            bar(L.market.demand, m.demand, "demand"),
            bar(L.market.growth, m.growth, "pct"),
            bar(L.market.competition, m.competition, "comp")));
      })),
    gated
      ? React.createElement("div", { style: { marginTop: 22 } },
          React.createElement(window.LeadGate, {
            L: L, lang: lang, source: "market",
            counts: { total: markets.length, countries: markets.slice(0, 6).map(function (m) { return m.cc; }), mode: "market" },
            context: { lang: lang, contact: data.contact || null, search: { trade: data.trade, product: data.productName, mode: "market", markets: data.markets || [] } },
            contact: data.contact || null,
          }))
      : React.createElement("div", { style: { marginTop: 22, display: "flex", justifyContent: "center" } },
          React.createElement("button", { className: "btn btn-primary", onClick: () => goRoute("find") },
            React.createElement(GIcon, { name: "users-round", size: 18 }), imp ? L.imp.marketOpenFind : L.market.openFind))
  );
}
window.MarketPage = MarketPage;

// =================== THANKS (shown in place of the market route for now) ===================
// MarketPage above is kept intact for when real trade data is connected; the "market"
// route is currently pointed here in app.jsx so users see a thank-you instead of the demo.
function ThanksPage(props) {
  const { lang, data, set } = props;
  const seenRef = React.useRef(false);
  useEffect(function () {
    if (seenRef.current) return; seenRef.current = true;
    window.track && window.track("thanks_viewed", { sectorId: data.sectorId, lang: lang });
    // Notify the sales team even when this is the sole destination (the wizard routes
    // straight here, skipping the Hub where the plan email is normally sent).
    if (!data.planSent) {
      set({ planSent: true });
      try {
        var planData = window.buildPlanSummary(data, lang);
        window.sendPlan(Object.assign({}, planData, { aiSummary: data.aiSummary || null, contact: data.contact || null }));
      } catch (e) {}
    }
  }, []);

  const title = lang === "tr" ? "Teşekkürler!" : "Thank you!";
  const msg = lang === "tr"
    ? "Talebiniz alındı. Ekibimiz en kısa sürede sizinle iletişime geçecektir."
    : "Your request has been received. Our team will get in touch with you shortly.";

  return React.createElement("div", { className: "route-page" },
    React.createElement("div", { className: "modal-success", style: { padding: "48px 20px", textAlign: "center" } },
      React.createElement("div", { className: "big" }, React.createElement(GIcon, { name: "badge-check", size: 32 })),
      React.createElement("h3", { style: { fontSize: 26 } }, title),
      React.createElement("p", { className: "msub" }, msg)));
}
window.ThanksPage = ThanksPage;

// =================== EMAIL OUTREACH ===================
function EmailPage(props) {
  const { L, lang, data } = props;
  const imp = data.trade === "import";
  const E = L.emailp;
  const [tmpl, setTmpl] = useState("intro");
  const [tone, setTone] = useState("formal");
  const [busy, setBusy] = useState(false);
  const [sent, setSent] = useState(false);
  const product = data.productName || (lang === "tr" ? "ürünümüz" : "our product");
  const country = window.countryName ? window.countryName(data.country, lang) : data.country;
  const indStr = (window.niceInds ? window.niceInds(data, lang) : []).slice(0, 3).join(", ");
  const mkStr = (data.markets && data.markets.length) ? data.markets.slice(0, 4).map(cc => window.countryName(cc, lang)).join(", ") : L.find.allMarkets;

  const seedFor = function (tp, tn) {
    const tr = {
      intro: { s: "İş birliği — " + product, b: "Merhaba,\n\nFirmamız " + product + " " + (imp ? "ithalatı" : "ihracatı/üretimi") + " yapmaktadır. " + (imp ? "Düzenli tedarik için" : country + " menşeli kaliteli ürünlerimizle") + " sizinle çalışmak isteriz.\n\nDetayları görüşmekten memnuniyet duyarız.\n\nSaygılarımızla" },
      offer: { s: "Teklif — " + product, b: "Merhaba,\n\n" + product + " için güncel fiyat ve koşullarımızı paylaşmak isteriz. İhtiyaçlarınıza özel teklif hazırlayabiliriz.\n\nSaygılarımızla" },
      sample: { s: "Numune talebi — " + product, b: "Merhaba,\n\n" + product + " için numune ve teknik bilgi talep ediyoruz. Uygunsa kataloğunuzu da paylaşabilir misiniz?\n\nSaygılarımızla" },
      follow: { s: "Takip — " + product, b: "Merhaba,\n\nÖnceki mesajımıza istinaden " + product + " konusundaki iş birliği fırsatını hatırlatmak istedik. Görüşmek için uygun bir zaman var mı?\n\nSaygılarımızla" },
    };
    const en = {
      intro: { s: "Partnership — " + product, b: "Hello,\n\nWe " + (imp ? "import " : "manufacture/export ") + product + ". We'd love to work with you" + (imp ? " on regular supply." : " in your market.") + "\n\nHappy to discuss the details.\n\nBest regards" },
      offer: { s: "Quote — " + product, b: "Hello,\n\nWe'd like to share our current pricing and terms for " + product + ". We can prepare an offer tailored to your needs.\n\nBest regards" },
      sample: { s: "Sample request — " + product, b: "Hello,\n\nWe'd like to request a sample and technical details for " + product + ". Could you also share your catalog?\n\nBest regards" },
      follow: { s: "Follow-up — " + product, b: "Hello,\n\nFollowing up on our previous message about " + product + ". Is there a good time to talk?\n\nBest regards" },
    };
    return (lang === "tr" ? tr : en)[tp];
  };
  const init = seedFor(tmpl, tone);
  const [subj, setSubj] = useState(init.s);
  const [body, setBody] = useState(init.b);

  const applyTmpl = function (tp) { setTmpl(tp); const s = seedFor(tp, tone); setSubj(s.s); setBody(s.b); };
  const aiWrite = function () {
    if (!window.hasAI) { const s = seedFor(tmpl, tone); setSubj(s.s); setBody(s.b); return; }
    setBusy(true);
    (async function () {
      try {
        const site = data.website ? (" Company website: " + data.website + ".") : "";
        const kw = (data.aiKeywords && data.aiKeywords.length) ? (" Site keywords: " + data.aiKeywords.join(", ") + ".") : "";
        const prompt = "Write a concise B2B outreach email in " + (lang === "tr" ? "Turkish" : "English") + " for a company that " + (imp ? "wants to import" : "exports") + " \"" + product + "\"." + site + kw + " Target audience: " + (indStr || "buyers") + " in " + mkStr + ". Template type: " + tmpl + ". Tone: " + tone + ". Make it specific to this company and product, not generic. Respond STRICT JSON only: {\"subject\":\"\",\"body\":\"\"}. Keep body under 90 words, professional, with a clear call to action.";
        const raw = await window.aiComplete(prompt);
        const j = JSON.parse(raw.slice(raw.indexOf("{"), raw.lastIndexOf("}") + 1));
        if (j.subject) setSubj(j.subject); if (j.body) setBody(j.body);
      } catch (e) { const s = seedFor(tmpl, tone); setSubj(s.s); setBody(s.b); }
      setBusy(false);
    })();
  };
  // auto-tailor to the website once, if we have one
  const [autoed, setAutoed] = useState(false);
  useEffect(function () {
    if (!autoed && data.website && window.hasAI) { setAutoed(true); aiWrite(); }
  }, []);

  if (sent) return React.createElement("div", { className: "route-page" },
    React.createElement("div", { className: "modal-success", style: { padding: "40px 20px" } },
      React.createElement("div", { className: "big" }, React.createElement(GIcon, { name: "send", size: 32 })),
      React.createElement("h3", { style: { fontSize: 26 } }, E.sentTitle),
      React.createElement("p", { className: "msub" }, E.sentDesc),
      React.createElement("button", { className: "btn btn-ghost-v", style: { marginTop: 10 }, onClick: () => setSent(false) }, E.reset)));

  const radio = function (val, cur, setFn, label) {
    return React.createElement("button", { type: "button", className: "seg2" + (cur === val ? " on" : ""), onClick: () => setFn(val) }, label);
  };

  return React.createElement("div", { className: "route-page narrow" },
    React.createElement("h2", { className: "step-title" }, E.title),
    React.createElement("p", { className: "step-sub" }, E.sub),
    React.createElement("div", { className: "summary-box", style: { marginTop: 16 } },
      React.createElement("h4", null, E.audience),
      React.createElement("p", { style: { margin: 0, fontWeight: 600, color: "var(--gb-ink-800)" } }, fmt(E.audienceLine, { inds: indStr || (imp ? L.imp.whoBuys : L.persona.whoBuys), markets: mkStr }))),
    React.createElement("div", { className: "field" },
      React.createElement("label", null, E.template),
      React.createElement("div", { className: "seg2row" },
        radio("intro", tmpl, applyTmpl, E.tIntro), radio("offer", tmpl, applyTmpl, E.tOffer), radio("sample", tmpl, applyTmpl, E.tSample), radio("follow", tmpl, applyTmpl, E.tFollow)),
      data.website ? React.createElement("p", { className: "muted-hint", style: { marginTop: 8 } }, React.createElement(GIcon, { name: "sparkles", size: 13, style: { display: "inline-block", verticalAlign: "-2px", marginRight: 5, color: "var(--gb-violet)" } }), E.siteNote) : null),
    React.createElement("div", { className: "field" },
      React.createElement("label", null, E.subject),
      React.createElement("input", { className: "inp", value: subj, onChange: e => setSubj(e.target.value) })),
    React.createElement("div", { className: "field" },
      React.createElement("label", null, E.body),
      React.createElement("textarea", { className: "inp", style: { minHeight: 170 }, value: body, onChange: e => setBody(e.target.value) })),
    React.createElement("div", { style: { display: "flex", gap: 10, marginTop: 18, flexWrap: "wrap", justifyContent: "flex-end" } },
      React.createElement("button", { className: "btn btn-ghost-v btn-sm", onClick: aiWrite, disabled: busy },
        React.createElement(GIcon, { name: busy ? "loader" : "sparkles", size: 16, cls: busy ? "spin" : "" }), busy ? E.aiBusy : E.aiWrite),
      React.createElement("button", { className: "btn btn-em btn-sm", onClick: () => { setSent(true); window.track && window.track("email_drafted", { surface: "email_page", template: tmpl, tone: tone, lang: lang }); } },
        React.createElement(GIcon, { name: "send", size: 16 }), E.send))
  );
}
window.EmailPage = EmailPage;
