/* tenroin-top/lp-catalog.jsx — 講座/商品LPテンプレ 共通：関連コンテンツ・カタログ ＋ 関連度セレクタ
   ──────────────────────────────────────────────────────────────────────
   Beyond（天狼院の、その先）の「おすすめコンテンツ」を、商品カタログから
   各LPのスキル/タグに応じて自動選定する仕組み。
   各LPの lp-data.jsx は window.lpPickReco({...}) を呼ぶだけ（下記参照）。
   - デザインは lp.jsx の Ecosystem（lp-eco-en / lp-eco-meta カード）をそのまま流用。
   - 新商品が出たら、この CATALOG に1行足すだけで全LPに反映される。
   - 手動で固定したいLPは pin:[id...]、出したくない物は exclude:[id...] を渡す。
   ※ href は新サイトの実URL確定後に差し替え（暫定は既存トップのアンカー）。
   読み込み順：この lp-catalog.jsx を lp-data.jsx より前に <script> で読むこと。 */
(function () {
  // skills: 海の8スキル〔読/書/AI/恋/稼/健/思/創〕。stage: ファネル上の役割。weight: 基本優先度(0-3)。
  const CATALOG = [
    // ★href は完全移行までの暫定＝実在の本番URL（絶対パス）。新サイト完成後に新URLへ差替。
    //   home(https://sea-publishing.com) は専用ページ未整備のものの安全な着地先（壊さない）。
    { id:'reading-club',     t:'天狼院 読書クラブ',            d:'仲間と読み、書く。',          meta:'READING LIFE 編集部',          en:'CLUB',       href:'https://tenro-in.com/book-club',                 skills:['読','書'],                          stage:'club',       tags:['reading','community','writing'], weight:3 },
    { id:'infinity-reading', t:'インフィニティ∞リーディング',  d:'読む力を、年間で。',          meta:'AI駆動 読書会 ／ 年間プログラム', en:'READING',    href:'https://sea-publishing.com/products/infinity-reading', skills:['読'],                          stage:'reading',    tags:['reading','ai','community'],      weight:3 },
    { id:'spell-method',     t:'スペル・メソッドAI',           d:'AIと、文章を磨き続ける。',    meta:'書く力の マスターAI',            en:'WRITING',    href:'https://sea-publishing.com',                     skills:['書'],                               stage:'tool',       tags:['writing','ai'],                  weight:2 },
    { id:'sea-scroll',       t:'SEA-SCROLL',                   d:'24時間、AIが採点する。',      meta:'書く力の 加速装置',              en:'SCROLL',     href:'https://sea-publishing.com',                     skills:['書'],                               stage:'tool',       tags:['writing','ai','learning'],       weight:2 },
    { id:'sea-learning',     t:'SEA LEARNING',                 d:'学びを、診断する。',          meta:'8コア要素であなたの学びを可視化', en:'DIAGNOSIS',  href:'https://sea-publishing.com',                     skills:['読','書','AI','恋','稼','健','思','創'], stage:'platform',   tags:['learning','diagnosis','ai'],     weight:1 },
    { id:'publishing',       t:'海の出版社',                   d:'書いたものを、本にする。',    meta:'天狼院がつくる、本のレーベル',    en:'PUBLISHING', href:'https://sea-publishing.com',                     skills:['書'],                               stage:'publishing', tags:['writing','publishing'],          weight:2 },
    { id:'reading-note',     t:'READING NOTE with AI',         d:'読書を、結果に変える。',      meta:'読書ノート × AI',               en:'NOTE',       href:'https://sea-publishing.com/products/reading-note', skills:['読'],                             stage:'tool',       tags:['reading','ai','note'],           weight:1 },
    { id:'ai-pilot',         t:'AIパイロット養成マニュアル',   d:'AIを、乗りこなす。',          meta:'AI実務の 養成プログラム',        en:'AI',         href:'https://sea-publishing.com/products/ai-pilot',   skills:['AI','稼'],                          stage:'course',     tags:['ai','business'],                 weight:1 },
    { id:'startup-academy',  t:'天狼院 起業アカデミー',        d:'起業を、形にする。',          meta:'起業の 体系講座',               en:'BUSINESS',   href:'https://sea-publishing.com',                     skills:['稼'],                               stage:'course',     tags:['business'],                      weight:1 },
    { id:'booklove',         t:'恋愛成就の教科書',             d:'恋を、科学する。',            meta:'恋愛診断 × AI',                 en:'LOVE',       href:'https://sea-publishing.com/products/love',       skills:['恋'],                               stage:'course',     tags:['love','diagnosis'],              weight:1 },
  ];

  /* 関連度で上位 n 件を選ぶ。
     opts = { selfId, skills:[], tags:[], pin:[id...], exclude:[id...], n }
     スコア = 基本weight + 同スキル一致×4（最重視）+ タグ一致×2。pin は先頭固定。 */
  function pick(opts) {
    opts = opts || {};
    const self = opts.selfId || '';
    const skills = opts.skills || [];
    const tags = opts.tags || [];
    const n = opts.n || 3;
    const exclude = {}; [self].concat(opts.exclude || []).forEach(function (id) { exclude[id] = true; });
    const byId = {}; CATALOG.forEach(function (c) { byId[c.id] = c; });

    function score(c) {
      let s = c.weight || 0;
      s += c.skills.filter(function (k) { return skills.indexOf(k) >= 0; }).length * 4;
      s += (c.tags || []).filter(function (k) { return tags.indexOf(k) >= 0; }).length * 2;
      return s;
    }

    const pinned = (opts.pin || []).map(function (id) { return byId[id]; })
      .filter(function (c) { return c && !exclude[c.id]; });
    const pinnedIds = {}; pinned.forEach(function (c) { pinnedIds[c.id] = true; });

    const rest = CATALOG
      .filter(function (c) { return !exclude[c.id] && !pinnedIds[c.id]; })
      .map(function (c) { return { c: c, s: score(c) }; })
      .sort(function (a, b) { return (b.s - a.s) || ((b.c.weight || 0) - (a.c.weight || 0)); })
      .map(function (x) { return x.c; });

    return pinned.concat(rest).slice(0, n).map(function (c) {
      return { t: c.t, d: c.d, meta: c.meta, en: c.en, href: c.href };
    });
  }

  /* 申込 → サーバの /api/lp/checkout で Stripe Checkout を作り、その URL へ遷移。
     opts = { lp, tier, seaScroll }（価格はサーバ側で確定。クライアントは金額を送らない）。 */
  let _checkoutBusy = false;
  async function lpCheckout(opts) {
    if (_checkoutBusy) return;
    _checkoutBusy = true;
    try {
      // Meta: InitiateCheckout（上流ファネル信号）＋ _fbp/_fbc を同送（サーバCAPIの帰属＝fbc に使う）。
      try { if (window.__fbTrack) window.__fbTrack('InitiateCheckout', { currency: 'JPY' }); } catch (e) {}
      const _fb = (window.__fbGet && window.__fbGet()) || {};
      const _payload = Object.assign({}, opts || {}, { fbp: _fb.fbp || '', fbc: _fb.fbc || '' });
      const r = await fetch('/api/lp/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(_payload),
      });
      const d = await r.json().catch(function () { return {}; });
      if (d && d.url) { window.location.href = d.url; return; }
      alert('決済の準備でエラーが発生しました。少し時間をおいて、もう一度お試しください。');
    } catch (e) {
      alert('通信エラーが発生しました。電波・接続をご確認のうえ、もう一度お試しください。');
    }
    _checkoutBusy = false;
  }

  window.LP_CATALOG = CATALOG;
  window.lpPickReco = pick;
  window.lpCheckout = lpCheckout;
})();
