// marketplace.jsx — country-first eSIM marketplace
const {
  useState: useStateM,
  useMemo: useMemoM,
  useEffect: useEffectM,
} = React;

const MARKETPLACE_REGION_HINTS = {
  Asia: ["Japan","South Korea","Thailand","Singapore","India","China","Hong Kong","Taiwan","Vietnam","Malaysia","Indonesia","Philippines","Cambodia","Sri Lanka","Bangladesh","Mongolia","Pakistan","Kazakhstan","Kyrgyzstan","Uzbekistan","Macao","Azerbaijan","Lao People's Democratic Republic","Armenia"],
  Oceania: ["Australia","New Zealand","Fiji","Kiribati","Papua New Guinea","Tonga"],
  Europe: ["France","Germany","Italy","Spain","United Kingdom","Netherlands","Portugal","Greece","Belgium","Austria","Switzerland","Sweden","Norway","Denmark","Finland","Poland","Czech Republic","Hungary","Romania","Bulgaria","Croatia","Serbia","Slovakia","Slovenia","Estonia","Latvia","Lithuania","Iceland","Ireland","Luxembourg","Cyprus","Moldova","Ukraine","Georgia","Albania","Bosnia and Herzegovina","Belarus","Russian Federation","Andorra","Faroe Islands","Guernsey","Jersey","Liechtenstein","Malta","Montenegro","North Macedonia"],
  Americas: ["United States","Canada","Mexico","Brazil","Argentina","Chile","Colombia","Peru","Ecuador","Bolivia","Paraguay","Uruguay","Costa Rica","Panama","Guatemala","El Salvador","Honduras","Dominican Republic","Nicaragua","Bermuda","Bahamas","Barbados","British Virgin Islands","Cayman Islands","Curacao","Dominica","French Guiana","Grenada","Guadeloupe","Haiti","Jamaica","Martinique","Montserrat","Puerto Rico","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Trinidad and Tobago","Turks and Caicos Islands"],
  Mideast: ["United Arab Emirates","Saudi Arabia","Israel","Jordan","Kuwait","Qatar","Bahrain","Oman","Iraq","Turkey","Türkiye","Egypt"],
  Africa: ["South Africa","Kenya","Nigeria","Morocco","Tunisia","Ghana","Uganda","Tanzania","Zambia","Botswana","Benin","Rwanda","Cameroon","Congo-Kinshasa","Algeria","Cote D'Ivoire","Gabon","Guinea","Guinea-Bissau","Liberia","Madagascar","Malawi","Mauritius","Sudan"],
};

const MARKETPLACE_PHOTOS = {
  "Japan":"1540959733332-eab4deabeeaf","United States":"1496442226666-8d4d0e62e6e9",
  "United Kingdom":"1513635269975-59663e0ac1ad","France":"1502602898657-3e91760cbb34",
  "Germany":"1570862687812-8b841fad0733","Italy":"1552832230-c0197dd311b5",
  "Spain":"1583422409516-2895a77efded","Thailand":"1528181304800-259b08848526",
  "Singapore":"1525625293386-3f8f99389edd","South Korea":"1538485399081-7191377e8241",
  "Australia":"1506973035872-a4ec16b8e8d9","India":"1524492412937-b28074a5d7da",
  "United Arab Emirates":"1512453979798-5ea266f8880c","Turkey":"1541432901042-2d8bd64b4a9b",
  "Türkiye":"1541432901042-2d8bd64b4a9b","Canada":"1517935706615-2717063c2225",
  "Mexico":"1518638150340-f706e86654de","Brazil":"1483729558449-99ef09a8c325",
  "South Africa":"1580060839134-75a5edca2e99","Greece":"1570077188670-e3a8d69ac5ff",
  "Portugal":"1746485415555-4188d435c8ff","Netherlands":"1744072837147-7b142f6f3aaf",
  "Switzerland":"1506905925346-21bda4d32df4","Austria":"1516550893923-42d28e5677af",
  "New Zealand":"1469521669194-babb45599def","Indonesia":"1518548419970-58e3b4079ab2",
  "Vietnam":"1528360983277-13d401cdc186","Malaysia":"1748504801753-a93a087110fa",
  "Philippines":"1695051702427-1c24ce3682e7","China":"1608037521277-154cd1b89191",
  "Hong Kong":"1513622790541-eaa84d356909","Taiwan":"1470004914212-05527e49370b",
  "Czech Republic":"1541849546-216549ae216d","Hungary":"1616432902940-b7a1acbc60b3",
  "Poland":"1501854140801-50d01698950b","Norway":"1527004013197-933c4bb611b3",
  "Sweden":"1509356843151-3e7d96241e11","Denmark":"1513622470522-26c3c8a854bc",
  "Finland":"1476514525535-07fb3b4ae5f1","Iceland":"1476610182048-b716b8518aae",
  "Ireland":"1570875450638-044bca38ec92","Belgium":"1491557345352-5929e343eb89",
  "Croatia":"1555990793-da11153b2473","Morocco":"1489749798305-4fea3ae63d43",
  "Egypt":"1553913861-c0fddf2619ee","Kenya":"1663848990481-8e0da3374a9c",
  "Argentina":"1483728642387-6c3bdd6c93e5","Chile":"1494783435443-c15feee0a80a",
  "Colombia":"1534943441045-1009d7cb0bb9","Peru":"1526392060635-9d6019884377",
  "Albania":"1705405999564-23bf3ccf4294","Algeria":"1714313164992-4c33788bd6f7",
  "Andorra":"1775224867785-3a39f4827a24","Anguilla":"1732817205106-d2161b8aaa18",
  "Antigua and Barbuda":"1771373119629-8f73d660cb7d","Armenia":"1651942697247-3623f3f57192",
  "Azerbaijan":"1621856291734-ed7e47df4f9e","Bahamas":"1506126483163-f4d1558dbf85",
  "Bahrain":"1716740974959-c733e57536b6","Bangladesh":"1672561924208-7762120e7077",
  "Barbados":"1636728150922-e7361791595a","Belarus":"1708669793150-fd69f335db66",
  "Benin":"1600241005059-71de13374958","Bermuda":"1594048899243-d070b8d9e18f",
  "Bolivia":"1589490156822-157850fe9972","Bosnia and Herzegovina":"1704974738004-133747005cbb",
  "Botswana":"1635349826951-b3a32b391384","British Virgin Islands":"1561928932-248c3263a62a",
  "Bulgaria":"1576072152864-be50a4c3e1c7","Cambodia":"1566706546199-a93ba33ce9f7",
  "Cameroon":"1623930180584-1b14bc584169","Cayman Islands":"1618426018046-77564bc4b0eb",
  "Congo-Kinshasa":"1729006122953-e3cafd3dd875",
  "Costa Rica":"1704386622459-b1e07e68d54f","Cote D'Ivoire":"1690394919910-3f647aced51a",
  "Curacao":"1724597837795-1fcb53817a13","Cyprus":"1714989575014-9c53e037dd31",
  "Dominica":"1649703196751-9019ead6b2f4","Dominican Republic":"1564394232860-52605aab6780",
  "Ecuador":"1589490156822-157850fe9972","El Salvador":"1590856029192-284cc8461706",
  "Estonia":"1579019554443-843d9130e480","Faroe Islands":"1533654655195-905c71b17211",
  "Fiji":"1743356174523-b04efcc66b46","French Guiana":"1669632477422-25054b68cbaa",
  "Gabon":"1758671105080-8f7a359e244f","Georgia":"1565067703613-c64e364c204f",
  "Ghana":"1740447342649-8b68b10b42d0","Gibraltar":"1683669447068-3ce32ed90f21",
  "Greenland":"1490791135648-882cc5638215","Grenada":"1625694100768-181ea98d028a",
  "Guadeloupe":"1652300842180-abd09727d3f9","Guam":"1507525428034-b723cf961d3e",
  "Guatemala":"1548131968-0517d86ff8fb","Guernsey":"1716890750873-ca24926d0c54",
  "Guinea":"1690394919910-3f647aced51a","Guinea-Bissau":"1500056363169-ebc595d60d0f",
  "Haiti":"1583875074734-b6fd484ddc67","Honduras":"1577849952112-89f058939e76",
  "Iraq":"1635016893171-e8c00941ce02","Israel":"1529079875474-0a66a1f176d0",
  "Jamaica":"1557129603-ff35a0c70e5e","Jersey":"1716890750873-ca24926d0c54",
  "Jordan":"1580834341580-8c17a3a630ca","Kazakhstan":"1661193133821-aad6ceb21fab",
  "Kiribati":"1506126483163-f4d1558dbf85","Kuwait":"1607138803282-34d6c7684751",
  "Kyrgyzstan":"1608497735578-11912e18ed9f","Lao People's Democratic Republic":"1590523277543-a94d2e4eb00b",
  "Latvia":"1579019554443-843d9130e480","Liberia":"1658872181467-d041dc3b5cf5",
  "Liechtenstein":"1668031084677-1bda87d5e23c","Lithuania":"1643040902038-0ac541dce632",
  "Luxembourg":"1662239936406-522b4f82546a","Macao":"1733919505005-d71d8f0272ad",
  "Madagascar":"1558694440-03ade9215d7b","Malawi":"1777804872457-cb3d931388bd",
  "Maldives":"1574226780565-388f10f8121e","Malta":"1583422409516-2895a77efded",
  "Martinique":"1570871821811-4f5504c08c4c","Mauritius":"1513415277900-a62401e19be4",
  "Moldova":"1693309400997-be1ab6a3ee12","Mongolia":"1742205024727-245bb73b38e5",
  "Montenegro":"1664958451522-90ce9fd47b2c","Montserrat":"1594048899243-d070b8d9e18f",
  "Nicaragua":"1577849952112-89f058939e76","Nigeria":"1577900190299-7316c32fe85f",
  "North Macedonia":"1644391616935-9e2d620bdbf2","Oman":"1506797792766-47522c5dd5b6",
  "Pakistan":"1609681980718-340e7f4b11d7","Panama":"1741658006725-6adb0f1a1aa0",
  "Papua New Guinea":"1700144068853-671567b77ea8","Paraguay":"1698242078904-4585152ef37a",
  "Puerto Rico":"1563641490003-06b23eae3074","Qatar":"1512453979798-5ea266f8880c",
  "Reunion":"1725789836723-c5015ed6745f","Romania":"1597834777623-acd73456aca1",
  "Russian Federation":"1664019597420-da9184af1e9e","Rwanda":"1583140310426-9187b6489be3",
  "Saint Kitts and Nevis":"1507525428034-b723cf961d3e","Saint Lucia":"1710633549419-7a76599c6e96",
  "Saint Vincent and the Grenadines":"1625694100768-181ea98d028a","Saudi Arabia":"1586724237569-f3d0c1dee8c6",
  "Serbia":"1600453878652-52c2c4aa96af","Slovakia":"1470043201067-764120126eb4",
  "Slovenia":"1562083589-3bf71182e9c2","Sri Lanka":"1544015759-237f87d55ef3",
  "Sudan":"1764685761993-4bbb0cf4ba49","Tanzania":"1629290439635-80e8740a0c7d",
  "Tonga":"1743356174523-b04efcc66b46","Trinidad and Tobago":"1625694100768-181ea98d028a",
  "Tunisia":"1674222708559-02878659dd2f","Turks and Caicos Islands":"1618426018046-77564bc4b0eb",
  "Uganda":"1629290439635-80e8740a0c7d","Ukraine":"1649453172896-e6ce31f0358d",
  "Uruguay":"1596930211624-0e83b02e3f0a","Uzbekistan":"1627646393465-93969d6a6549",
  "Zambia":"1553683700-cb04c63e144a",
};

const MARKETPLACE_REGION_GRAD = {
  Asia: ["#3a2c6e", "#ffb3c6"],
  Europe: ["#2b4e8c", "#cdd6e8"],
  Americas: ["#1f9e8a", "#ffcf6b"],
  Mideast: ["#a8553c", "#ffd9a0"],
  Africa: ["#3a6ea8", "#ffc46b"],
  Oceania: ["#ff8c6b", "#7be0d0"],
  Travel: ["#54388c", "#7ad0ff"],
};

const MARKETPLACE_POPULAR = new Set([
  "Japan","United States","United Kingdom","France","Germany","Italy",
  "Spain","Thailand","Singapore","South Korea","Australia","India",
  "United Arab Emirates","Brazil","Canada","Mexico","Turkey","Türkiye",
  "Portugal","Greece","Netherlands","Switzerland",
]);

const SMART_RECOMMENDATIONS_URL = "/api/smart-pricing-rules";
const SMART_PLAN_LADDER = [
  { key: "1GB_7d", mb: 1024, days: 7, rank: 10 },
  { key: "3GB_15d", mb: 3072, days: 15, rank: 20 },
  { key: "3GB_30d", mb: 3072, days: 30, rank: 30 },
  { key: "5GB_30d", mb: 5120, days: 30, rank: 40 },
  { key: "10GB_30d", mb: 10240, days: 30, rank: 50 },
  { key: "20GB_30d", mb: 20480, days: 30, rank: 60 },
  { key: "50GB_90d", mb: 51200, days: 90, rank: 70 },
  { key: "100GB_180d", mb: 102400, days: 180, rank: 80 },
];
const SMART_PLAN_KEY_BY_SHAPE = new Map(SMART_PLAN_LADDER.map(item => [`${item.mb}-${item.days}`, item]));

function marketMoney(n) {
  const s = Number(n || 0).toFixed(2);
  return "$" + (s.endsWith(".00") ? s.slice(0, -3) : s);
}

function inferMarketplaceRegion(country, fallback) {
  if (fallback && fallback !== "Bundles") return fallback;
  for (const [region, names] of Object.entries(MARKETPLACE_REGION_HINTS)) {
    if (names.includes(country)) return region;
  }
  return "Travel";
}

function marketplacePhotoUrl(name, width = 480) {
  const id = MARKETPLACE_PHOTOS[name];
  return id ? `https://images.unsplash.com/photo-${id}?w=${width}&q=86&auto=format&fit=crop` : null;
}

function groupByDays(plans) {
  const map = new Map();
  plans.forEach(plan => {
    const days = plan.days || 0;
    if (!map.has(days)) map.set(days, []);
    map.get(days).push(plan);
  });
  return [...map.entries()]
    .sort((a, b) => a[0] - b[0])
    .map(([days, rows]) => [
      days,
      rows.sort((a, b) => (a.dataMb || 0) - (b.dataMb || 0) || a.price - b.price),
    ]);
}

function sortSmartPlans(plans) {
  return plans.slice().sort((a, b) => {
    const aRank = a.smartRank ?? 999;
    const bRank = b.smartRank ?? 999;
    return a.days - b.days || aRank - bRank || (a.dataMb || 0) - (b.dataMb || 0) || a.price - b.price;
  });
}

function isSmartPlanShape(plan) {
  return SMART_PLAN_KEY_BY_SHAPE.has(`${plan.dataMb}-${plan.days}`);
}

function isGenericNetworkLabel(value) {
  return !value || /^4g\/5g$/i.test(String(value).trim());
}

function isGenericCarrierLabel(value) {
  return !value || /^\d+\s+(country|countries|destination|destinations)$/i.test(String(value).trim());
}

function networkMetaParts(plan) {
  const parts = [];
  if (!isGenericNetworkLabel(plan?.net)) parts.push(plan.net);
  if (!isGenericCarrierLabel(plan?.carriers)) parts.push(plan.carriers);
  return parts;
}

function countrySlug(name) {
  return String(name || "")
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .replace(/&/g, " and ")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

function deriveRegionLabel(countries) {
  const counts = {};
  (countries || []).forEach(c => {
    const r = inferMarketplaceRegion(c, null);
    counts[r] = (counts[r] || 0) + 1;
  });
  const top = Object.entries(counts).sort((a, b) => b[1] - a[1]);
  if (!top.length) return "Multi-country";
  if (top.length === 1 || top[1][1] < 3) return `${top[0][0]} Regional`;
  return "Multi-region";
}

function MarketplacePhoto({ country, region }) {
  const [loaded, setLoaded] = useStateM(false);
  const [failed, setFailed] = useStateM(false);
  const url = marketplacePhotoUrl(country);
  const grad = MARKETPLACE_REGION_GRAD[region] || MARKETPLACE_REGION_GRAD.Travel;
  return (
    <div className="destimg" style={!url || failed ? { background: `linear-gradient(160deg, ${grad[0]}, ${grad[1]})` } : null}>
      {url && !failed && (
        <img
          className={"destimg-photo" + (loaded ? " in" : "")}
          src={url}
          alt={country}
          loading="lazy"
          onLoad={() => setLoaded(true)}
          onError={() => setFailed(true)}
        />
      )}
      <div className="destimg-scrim"></div>
    </div>
  );
}

function DestinationCard({ entry, onOpen }) {
  const planCount = entry.plans.length + (entry.unlimitedPlans?.length || 0);
  return (
    <button type="button" className="plan-card pv-dest-card" onClick={() => onOpen(entry)}>
      <div className="plan-banner">
        <MarketplacePhoto country={entry.name} region={entry.region} />
        {entry.popular && (
          <div className="plan-banner-top">
            <span className="plan-pop"><Ic.spark/> Popular</span>
          </div>
        )}
        <div className="plan-banner-name">{entry.name}</div>
        <div className="plan-banner-region">{entry.region}</div>
      </div>
      <div className="plan-info">
        <div className="plan-foot">
          <span className="chip" style={{ fontSize: 11 }}>
            {planCount} plan{planCount === 1 ? "" : "s"}
          </span>
          <span className="pv-from-price">
            <span>from</span>{marketMoney(entry.minPrice)}
          </span>
        </div>
      </div>
    </button>
  );
}

function PlanRow({ plan, onSelect, disabled }) {
  const metaParts = networkMetaParts(plan);
  return (
    <div className={"pv-plan-row" + (disabled ? " disabled" : "")}>
      <div>
        <div className={"pv-plan-data" + (plan.unlimited ? " unlimited" : "")}>
          {plan.data}
          {plan.popular && <span className="pv-popular"><Ic.spark/> Popular</span>}
        </div>
        <div className="pv-plan-meta">{metaParts.join(" · ")}</div>
      </div>
      <div className="pv-plan-right">
        <div className="pv-plan-price">
          <b>{marketMoney(plan.price)}</b>
          <small>{plan.unlimited ? "unlimited" : "one-time"}</small>
        </div>
        <button
          type="button"
          className="pv-plan-btn"
          disabled={disabled}
          onClick={() => !disabled && onSelect(plan)}
        >
          {disabled ? "Soon" : "Select"}
        </button>
      </div>
    </div>
  );
}

function DaySections({ groups, onSelect, disabled }) {
  if (!groups.length) {
    return (
      <div className="pv-empty">
        <div className="pv-empty-icon"><Ic.signal/></div>
        <div>No plans available in this tab.</div>
      </div>
    );
  }
  return (
    <>
      {groups.map(([days, rows]) => (
        <div className="pv-section" key={days}>
          <div className="pv-section-head">
            <span className="pv-section-head-title">{days} day{days === 1 ? "" : "s"}</span>
            <span className="chip" style={{ fontSize: 11 }}>{rows.length} option{rows.length === 1 ? "" : "s"}</span>
          </div>
          {rows.map(plan => (
            <PlanRow key={plan.id} plan={plan} onSelect={onSelect} disabled={disabled} />
          ))}
        </div>
      ))}
    </>
  );
}

function RegionCard({ bundle, onOpen }) {
  const label       = deriveRegionLabel(bundle.countries);
  const photoCountry = bundle.countries.find(c => MARKETPLACE_PHOTOS[c]) || "";
  return (
    <button type="button" className="plan-card pv-dest-card" onClick={() => onOpen(bundle)}>
      <div className="plan-banner">
        <MarketplacePhoto country={photoCountry} region={label} />
        <div className="plan-banner-name">{label}</div>
        <div className="plan-banner-region">{bundle.countries.length} countries</div>
      </div>
      <div className="plan-info">
        <div className="plan-foot">
          <span className="chip" style={{ fontSize: 11 }}>{bundle.plans.length} plan{bundle.plans.length === 1 ? "" : "s"}</span>
          <span className="pv-from-price">
            <span>from</span>{marketMoney(bundle.minPrice)}
          </span>
        </div>
      </div>
    </button>
  );
}

function RegionalSection({ entry, regionalBundles, onOpen }) {
  const matching = regionalBundles.filter(bundle =>
    (bundle.countries || []).some(c => String(c).toLowerCase() === entry.name.toLowerCase())
  );
  if (!matching.length) return null;
  return (
    <div className="pv-regional">
      <div className="pv-regional-header">
        <span className="eyebrow"><span className="dot"></span> Also covers {entry.name}</span>
        <h2>Regional eSIMs</h2>
        <p>Multi-country plans that include {entry.name} — useful when your trip spans multiple destinations.</p>
      </div>
      <div className="pv-grid">
        {matching.map(bundle => (
          <RegionCard key={bundle.name} bundle={bundle} onOpen={onOpen} />
        ))}
      </div>
    </div>
  );
}

function Marketplace({ plans = [], meta = {}, route = "marketplace", go, onSelectPlan }) {
  const [search, setSearch] = useStateM("");
  const [tab, setTab] = useStateM("standard");
  const [smartRules, setSmartRules] = useStateM(null);
  const [smartError, setSmartError] = useStateM("");
  const [fromCountry, setFromCountry] = useStateM(null);

  const routeSuffix = route.startsWith("marketplace/")
    ? decodeURIComponent(route.slice("marketplace/".length))
    : "";
  const routeRegionSlug  = routeSuffix.startsWith("region-") ? routeSuffix.slice("region-".length) : "";
  const routeCountrySlug = routeRegionSlug ? "" : (routeSuffix ? countrySlug(routeSuffix) : "");

  useEffectM(() => {
    let alive = true;
    fetch(SMART_RECOMMENDATIONS_URL)
      .then(response => {
        if (!response.ok) throw new Error("Could not load smart pricing rules");
        return response.json();
      })
      .then(data => {
        if (!alive) return;
        const map = new Map();
        (data.recommendations || []).forEach(rule => map.set(rule.country, rule));
        setSmartRules(map);
        setSmartError("");
      })
      .catch(error => {
        if (!alive) return;
        setSmartRules(new Map());
        setSmartError(error.message || "Could not load smart pricing rules");
      });
    return () => { alive = false; };
  }, []);

  const { countryEntries, regionalBundles } = useMemoM(() => {
    const countryMap = new Map();
    const fallbackCountryMap = new Map();
    const bundles = new Map();
    if (!smartRules) return { countryEntries: [], regionalBundles: [] };

    const ensureCountryEntry = (map, plan) => {
      if (!map.has(plan.country)) {
        const rule = smartRules.get(plan.country);
        const region = inferMarketplaceRegion(plan.country, plan.region);
        map.set(plan.country, {
          name: plan.country,
          region,
          plans: [],
          minPrice: Infinity,
          popular: MARKETPLACE_POPULAR.has(plan.country),
          smartBundle: rule?.recommendedBundle || "",
          smartBundleId: rule?.recommendedBundleId || "",
          smartConfidence: rule?.confidence || "",
          networkSummary: rule?.networkSummary || "",
          unlimitedPlans: [],
        });
      }
      return map.get(plan.country);
    };

    const addCountryPlan = (map, plan, overrides = {}) => {
      const entry = ensureCountryEntry(map, plan);
      entry.plans.push({
        ...plan,
        net: isGenericNetworkLabel(plan.net) ? "" : plan.net,
        carriers: overrides.carriers || entry.networkSummary || plan.carriers,
        ...overrides,
      });
      if (plan.price < entry.minPrice) entry.minPrice = plan.price;
    };

    const addUnlimitedPlan = (map, plan) => {
      const entry = ensureCountryEntry(map, plan);
      entry.unlimitedPlans.push({
        ...plan,
        net: isGenericNetworkLabel(plan.net) ? "" : plan.net,
        carriers: entry.networkSummary || plan.carriers,
      });
    };

    plans.forEach(plan => {
      if (plan.type === "country") {
        if (plan.unlimited) {
          addUnlimitedPlan(fallbackCountryMap, plan);
          return;
        }

        const fallbackShape = SMART_PLAN_KEY_BY_SHAPE.get(`${plan.dataMb}-${plan.days}`);
        addCountryPlan(fallbackCountryMap, plan, {
          smartRank: fallbackShape?.rank ?? 999,
          smartKey: fallbackShape?.key || "",
        });

        const rule = smartRules.get(plan.country);
        const smartShape = SMART_PLAN_KEY_BY_SHAPE.get(`${plan.dataMb}-${plan.days}`);
        const isMarkedSmartPlan = !!plan.smartLadderPlan;
        const isLegacySmartPlan = !!plan.providerBundleId
          && !!rule
          && String(plan.providerBundleId) === String(rule.recommendedBundleId)
          && !!smartShape
          && rule.prices?.[smartShape.key] != null;
        if (!smartShape || (!isMarkedSmartPlan && !isLegacySmartPlan)) return;

        addCountryPlan(countryMap, plan, {
          carriers: rule.networkSummary || plan.carriers,
          smartRank: plan.smartRank ?? smartShape.rank,
          smartKey: plan.smartKey || smartShape.key,
        });
      } else if (plan.type === "regional" || plan.type === "global" || plan.region === "Bundles") {
        if (!isSmartPlanShape(plan)) return;
        const key = plan.country;
        if (!bundles.has(key)) {
          bundles.set(key, {
            name: plan.country,
            type: plan.type || "regional",
            countries: plan.countries || [],
            plans: [],
            minPrice: Infinity,
          });
        }
        const bundle = bundles.get(key);
        const smartShape = SMART_PLAN_KEY_BY_SHAPE.get(`${plan.dataMb}-${plan.days}`);
        bundle.plans.push({ ...plan, smartRank: smartShape?.rank ?? 999 });
        if (plan.price < bundle.minPrice) bundle.minPrice = plan.price;
      }
    });

    const allowFallbackCountryPlans = smartRules.size === 0;
    fallbackCountryMap.forEach((entry, country) => {
      const unlimitedPlans = sortSmartPlans(entry.unlimitedPlans || []);
      if (countryMap.has(country)) {
        const existing = countryMap.get(country);
        existing.unlimitedPlans = unlimitedPlans;
      } else if (allowFallbackCountryPlans) {
        countryMap.set(country, {
          ...entry,
          plans: sortSmartPlans(entry.plans),
          unlimitedPlans,
        });
      }
    });

    const countryEntries = [...countryMap.values()].sort((a, b) => {
      if (a.popular !== b.popular) return a.popular ? -1 : 1;
      return a.name.localeCompare(b.name);
    });
    const regionalBundles = [...bundles.values()].map(bundle => ({
      ...bundle,
      plans: sortSmartPlans(bundle.plans),
    })).sort((a, b) => a.name.localeCompare(b.name));

    return { countryEntries, regionalBundles };
  }, [plans, smartRules]);

  useEffectM(() => {
    setTab("standard");
  }, [routeCountrySlug]);

  const shownCountries = useMemoM(() => {
    const q = search.toLowerCase().trim();
    if (!q) return countryEntries;
    return countryEntries.filter(entry =>
      entry.name.toLowerCase().includes(q) || entry.region.toLowerCase().includes(q)
    );
  }, [countryEntries, search]);

  const selectedCountry = useMemoM(() => {
    if (!routeCountrySlug) return null;
    return countryEntries.find(entry => countrySlug(entry.name) === routeCountrySlug) || null;
  }, [countryEntries, routeCountrySlug]);

  const activePlans = useMemoM(() => {
    if (!selectedCountry) return [];
    const hasUnlimitedPlans = (selectedCountry.unlimitedPlans || []).length > 0;
    return tab === "unlimited" && hasUnlimitedPlans
      ? sortSmartPlans(selectedCountry.unlimitedPlans || [])
      : sortSmartPlans(selectedCountry.plans);
  }, [selectedCountry, tab]);
  const groupedPlans = useMemoM(() => groupByDays(activePlans), [activePlans]);

  const selectedRegion = useMemoM(() => {
    if (!routeRegionSlug) return null;
    return regionalBundles.find(b => countrySlug(b.name) === routeRegionSlug) || null;
  }, [regionalBundles, routeRegionSlug]);

  const openCountry = entry => {
    const next = `marketplace/${countrySlug(entry.name)}`;
    if (go) go(next);
    else location.hash = next;
  };
  const backToCountries = () => {
    if (go) go("marketplace");
    else location.hash = "marketplace";
  };
  const openRegion = bundle => {
    setFromCountry(selectedCountry);
    const next = `marketplace/region-${countrySlug(bundle.name)}`;
    if (go) go(next);
    else location.hash = next;
  };
  const backFromRegion = () => {
    if (fromCountry) {
      const next = `marketplace/${countrySlug(fromCountry.name)}`;
      if (go) go(next);
      else location.hash = next;
    } else {
      backToCountries();
    }
  };

  if (routeRegionSlug) {
    if (!selectedRegion) {
      return (
        <div className="pv-shell">
          <div className="pv-plans">
            <button type="button" className="btn btn-ghost btn-sm pv-back" onClick={backFromRegion}>
              <Ic.arrow/> {fromCountry ? `Back to ${fromCountry.name}` : "All destinations"}
            </button>
            <div className="pv-empty">
              <div className="pv-empty-icon"><Ic.clock/></div>
              <div>{regionalBundles.length === 0 ? "Loading…" : "Region not found."}</div>
            </div>
          </div>
        </div>
      );
    }
    const regionLabel       = deriveRegionLabel(selectedRegion.countries);
    const groupedRegionPlans = groupByDays(sortSmartPlans(selectedRegion.plans));
    const regionPhotoCountry = selectedRegion.countries.find(c => MARKETPLACE_PHOTOS[c]) || "";
    const regionPagePhoto = marketplacePhotoUrl(regionPhotoCountry, 2200);
    const regionPageGrad = MARKETPLACE_REGION_GRAD[regionLabel.replace(" Regional", "")] || MARKETPLACE_REGION_GRAD.Travel;
    const regionPageStyle = regionPagePhoto
      ? { "--pv-page-photo": `url("${regionPagePhoto}")` }
      : { "--pv-page-fallback": `linear-gradient(160deg, ${regionPageGrad[0]}, ${regionPageGrad[1]})` };
    return (
      <div className={"pv-shell pv-country-page" + (regionPagePhoto ? " has-photo" : " has-fallback")} style={regionPageStyle}>
        <div className="pv-plans">
          <button type="button" className="btn btn-ghost btn-sm pv-back" onClick={backFromRegion}>
            <Ic.arrow/> {fromCountry ? `Back to ${fromCountry.name}` : "All destinations"}
          </button>
          <div className="pv-plans-hero">
            <div className="pv-plans-hero-body">
              <h1>{regionLabel}</h1>
              <div className="pv-plans-hero-meta">
                <span className="chip">{selectedRegion.countries.length} countries</span>
                <span className="chip">regional</span>
              </div>
              <div className="pv-region-countries">
                {selectedRegion.countries.map(c => (
                  <span key={c} className="chip" style={{ fontSize:11 }}>{c}</span>
                ))}
              </div>
            </div>
          </div>
          <DaySections groups={groupedRegionPlans} onSelect={onSelectPlan} disabled={false} />
        </div>
      </div>
    );
  }

  if (routeCountrySlug) {
    if (plans.length === 0 || !smartRules) {
      return (
        <div className="pv-shell">
          <div className="pv-plans">
            <div className="pv-empty">
              <div className="pv-empty-icon"><Ic.clock/></div>
              <div>{plans.length === 0 ? "Loading plans..." : "Loading smart pricing ladder..."}</div>
            </div>
          </div>
        </div>
      );
    }

    if (!selectedCountry) {
      return (
        <div className="pv-shell">
          <div className="pv-plans">
            <button type="button" className="btn btn-ghost btn-sm pv-back" onClick={backToCountries}>
              <Ic.arrow/> All destinations
            </button>
            <div className="pv-empty">
              <div className="pv-empty-icon"><Ic.search/></div>
              <div>Destination not found.</div>
            </div>
          </div>
        </div>
      );
    }

    const pagePhoto = marketplacePhotoUrl(selectedCountry.name, 2200);
    const pageGrad = MARKETPLACE_REGION_GRAD[selectedCountry.region] || MARKETPLACE_REGION_GRAD.Travel;
    const pageStyle = pagePhoto
      ? { "--pv-page-photo": `url("${pagePhoto}")` }
      : { "--pv-page-fallback": `linear-gradient(160deg, ${pageGrad[0]}, ${pageGrad[1]})` };
    const hasUnlimitedPlans = (selectedCountry.unlimitedPlans || []).length > 0;

    return (
      <div className={"pv-shell pv-country-page" + (pagePhoto ? " has-photo" : " has-fallback")} style={pageStyle}>
        <div className="pv-plans">
          <button type="button" className="btn btn-ghost btn-sm pv-back" onClick={backToCountries}>
            <Ic.arrow/> All destinations
          </button>

          <div className="pv-plans-hero">
            <div className="pv-plans-hero-body">
              <h1>{selectedCountry.name}</h1>
              <div className="pv-plans-hero-meta">
                <span className="pv-plans-hero-carriers">
                  {selectedCountry.plans.length + (selectedCountry.unlimitedPlans?.length || 0)} plan{selectedCountry.plans.length + (selectedCountry.unlimitedPlans?.length || 0) === 1 ? "" : "s"} available
                </span>
              </div>
            </div>
            {hasUnlimitedPlans && (
              <div className="pv-tab-bar">
                <button type="button" className={"pv-tab" + (tab === "standard" ? " active" : "")} onClick={() => setTab("standard")}>
                  Standard
                  <span className="pv-tab-note">Pay per GB</span>
                </button>
                <button type="button" className={"pv-tab" + (tab === "unlimited" ? " active" : "")} onClick={() => setTab("unlimited")}>
                  Unlimited
                  <span className="pv-tab-note">{selectedCountry.unlimitedPlans.length} live</span>
                </button>
              </div>
            )}
          </div>

          <DaySections groups={groupedPlans} onSelect={onSelectPlan} disabled={false} />
          {(tab === "standard" || !hasUnlimitedPlans) && (
            <RegionalSection entry={selectedCountry} regionalBundles={regionalBundles} onOpen={openRegion} />
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="pv-shell">
      <div className="pv-picker">
        <div className="mkt-head">
          <span className="eyebrow"><span className="dot"></span> {countryEntries.length || plans.length} destinations</span>
          <h1 className="mkt-title">The eSIM marketplace</h1>
          <p className="pv-market-sub">
            Choose a destination first, then compare the standard plans available for that country.
          </p>
        </div>

        {meta && meta.isLive === false && (
          <div className="catalog-note">
            <span className="chip accent">Demo catalog</span>
            <span>{meta.notice || "Live provider bundles are not connected yet."}</span>
          </div>
        )}

        <div className="mkt-toolbar pv-picker-toolbar">
          <div className="search">
            <Ic.search style={{ color: "var(--muted)", flexShrink: 0 }} />
            <input
              value={search}
              onChange={event => setSearch(event.target.value)}
              placeholder="Search countries or regions..."
              autoComplete="off"
              spellCheck="false"
            />
          </div>
        </div>

        {plans.length === 0 ? (
          <div className="pv-empty">
            <div className="pv-empty-icon"><Ic.clock/></div>
            <div>Loading plans...</div>
          </div>
        ) : !smartRules ? (
          <div className="pv-empty">
            <div className="pv-empty-icon"><Ic.clock/></div>
            <div>Loading smart pricing ladder...</div>
          </div>
        ) : smartError ? (
          <div className="pv-empty">
            <div className="pv-empty-icon"><Ic.signal/></div>
            <div>{smartError}</div>
          </div>
        ) : !shownCountries.length ? (
          <div className="pv-empty">
            <div className="pv-empty-icon"><Ic.search/></div>
            <div>No results for <strong>{search}</strong></div>
          </div>
        ) : (
          <div className="pv-grid">
            {shownCountries.map(entry => (
              <DestinationCard key={entry.name} entry={entry} onOpen={openCountry} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

window.Marketplace = Marketplace;
window.MARKETPLACE_PHOTOS = MARKETPLACE_PHOTOS;
window.MARKETPLACE_REGION_GRAD = MARKETPLACE_REGION_GRAD;
