/* enterpriseTopicExplorer.jsx — Enterprise topic explorer (#/enterprise/explore).
 *
 * One reusable exploration surface for all 14 canonical topics and the seven
 * friendly groups, rather than fourteen marketing pages.
 *
 * ROUTE
 *   #/enterprise/explore                       directory of every real topic
 *   #/enterprise/explore/Climate               a canonical topic
 *   #/enterprise/explore/economy-finance       a friendly group -> Economy,Trade,Debt
 *
 * Path segments rather than a query string, because the existing Enterprise
 * router already splits the hash on "/" and passes the parts through; a query
 * string would need changes in the shared router.
 *
 * WHAT IT SHOWS
 *   Only funding, and only what the corpus genuinely returns. Signals are
 *   deliberately NOT included: that surface is being rebuilt in another session,
 *   and reading it mid-rewrite would either duplicate its logic or render a
 *   shape that is about to change. Geography is omitted for the same reason the
 *   audit gave — most records carry no resolved country, so any distribution
 *   would be a picture of missing data.
 *
 * Read-only throughout. No writes, no classification, no new taxonomy.
 */
(function () {
  'use strict';
  var h = React.createElement;

  function TG() { return window.EnterpriseTopicGroups; }
  function MXC() { return window.MX; }

  // Topic -> funding sectors. Reuses the mapping the consumer feed already
  // defines rather than inventing a second one; when it is unavailable the
  // section says so instead of silently returning nothing.
  function sectorsFor(topics) {
    var map = window.TOPIC_SECTORS || null;
    if (!map) return null;
    var out = [];
    topics.forEach(function (t) {
      (map[t] || []).forEach(function (s) {
        var v = String(s).replace(/^sector:/, '');
        if (out.indexOf(v) === -1) out.push(v);
      });
    });
    return out;
  }

  function injectCSS() {
    if (document.getElementById('ete-css')) return;
    var s = document.createElement('style');
    s.id = 'ete-css';
    s.textContent = [
      '.ete{--nv:#09213D;--or:#FF5A1F;--bl:#3478F6;--tl:#19A58C;--cr:#FBF8F1;--sd:#EFE5D4;',
      '  background:var(--cr);color:var(--nv);min-height:100%;padding:34px 30px 60px;',
      '  font-family:ui-sans-serif,-apple-system,"Segoe UI",Roboto,sans-serif}',
      '.ete-k{font-size:11px;letter-spacing:.09em;text-transform:uppercase;color:#6B7A8C;margin:0 0 10px}',
      '.ete-h1{font-size:34px;line-height:1.12;font-weight:660;margin:0 0 10px;letter-spacing:-.02em}',
      '.ete-lede{font-size:15px;line-height:1.55;color:#41566E;margin:0 0 26px;max-width:56ch}',
      '.ete-sec{margin-top:34px}',
      '.ete-sh{display:flex;align-items:baseline;justify-content:space-between;gap:16px;',
      '  border-bottom:1px solid var(--sd);padding-bottom:9px;margin-bottom:16px}',
      '.ete-sh h2{font-size:13px;letter-spacing:.07em;text-transform:uppercase;margin:0;font-weight:640}',
      '.ete-sh a{font-size:13px;color:var(--or);text-decoration:none}',
      '.ete-sh a:hover{text-decoration:underline}',
      /* topic directory */
      '.ete-grid{display:flex;flex-wrap:wrap;gap:9px}',
      '.ete-t{display:inline-flex;align-items:center;gap:8px;background:#fff;border:1px solid var(--sd);',
      '  border-radius:11px;padding:11px 15px;font-size:14.5px;color:var(--nv);text-decoration:none;',
      '  min-height:44px;transition:border-color .15s,transform .15s}',
      '.ete-t:hover{border-color:var(--or);transform:translateY(-1px)}',
      '.ete-t i{width:7px;height:7px;border-radius:2px;background:var(--bl);display:block}',
      '.ete-t.on{background:var(--nv);color:#fff;border-color:var(--nv)}',
      '.ete-g{display:grid;grid-template-columns:repeat(auto-fill,minmax(215px,1fr));gap:10px}',
      '.ete-gc{background:#fff;border:1px solid var(--sd);border-radius:13px;padding:15px 16px;',
      '  text-decoration:none;color:var(--nv);display:block;transition:border-color .15s}',
      '.ete-gc:hover{border-color:var(--tl)}',
      '.ete-gc b{display:block;font-size:15px;font-weight:600;margin-bottom:5px}',
      '.ete-gc span{font-size:12px;color:#6B7A8C}',
      /* funding rows */
      '.ete-r{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 18px;padding:13px 0;',
      '  border-bottom:1px solid #EFE9DF;align-items:start}',
      '.ete-r:last-child{border-bottom:0}',
      '.ete-rt{font-size:14.5px;font-weight:550;line-height:1.4;margin:0}',
      '.ete-rm{font-size:12.5px;color:#6B7A8C;margin:3px 0 0}',
      '.ete-rd{font-size:12.5px;color:var(--nv);white-space:nowrap;text-align:right}',
      '.ete-empty{background:#fff;border:1px dashed var(--sd);border-radius:12px;padding:18px 20px;',
      '  font-size:13.5px;color:#41566E;line-height:1.55}',
      '.ete-sw{display:flex;flex-wrap:wrap;gap:7px;margin:0 0 26px}',
      '.ete-sw a{font-size:13px;padding:7px 12px;border-radius:20px;border:1px solid var(--sd);',
      '  background:#fff;color:var(--nv);text-decoration:none;min-height:36px;display:inline-flex;align-items:center}',
      '.ete-sw a.on{background:var(--nv);color:#fff;border-color:var(--nv)}',
      '.ete-bad{background:#fff;border:1px solid var(--sd);border-radius:13px;padding:22px 24px;max-width:60ch}',
      '@media (max-width:760px){',
      '  .ete{padding:22px 16px 48px}',
      '  .ete-h1{font-size:26px}',
      '  .ete-r{grid-template-columns:1fr}',
      '  .ete-rd{text-align:left;white-space:normal}',
      '  .ete-g{grid-template-columns:1fr}',
      '}',
    ].join('');
    document.head.appendChild(s);
  }

  function fmtAmount(o) {
    var v = o.amount_max != null ? o.amount_max : o.amount_min;
    if (v == null) return 'Amount not stated';
    var c = String(o.currency || 'USD').toUpperCase();
    var sym = c === 'GBP' ? '£' : c === 'EUR' ? '€' : '$';
    return v >= 1e6 ? sym + (v / 1e6).toFixed(1).replace(/\.0$/, '') + 'm'
         : v >= 1e3 ? sym + Math.round(v / 1e3) + 'k' : sym + Math.round(v);
  }

  // ── all-topics directory ──────────────────────────────────────────────────
  function Directory() {
    var G = TG();
    return h('div', { className: 'ete', 'data-ui-part': 'topic-explorer-directory' },
      h('p', { className: 'ete-k' }, 'Explore development'),
      h('h1', { className: 'ete-h1' }, 'What are you working on?'),
      h('p', { className: 'ete-lede' },
        'Explore funding and intelligence around the development areas your organisation works in.'),

      h('div', { className: 'ete-sec' },
        h('div', { className: 'ete-sh' }, h('h2', null, 'By area of work')),
        h('div', { className: 'ete-g' }, G.GROUPS.map(function (g) {
          return h('a', { key: g.slug, className: 'ete-gc', href: '#/enterprise/explore/' + g.slug },
            h('b', null, g.label),
            h('span', null, g.topics.join(' · ')));
        }))),

      h('div', { className: 'ete-sec' },
        h('div', { className: 'ete-sh' }, h('h2', null, 'All topics')),
        h('div', { className: 'ete-grid' }, G.CANONICAL_TOPICS.map(function (t) {
          return h('a', { key: t, className: 'ete-t', href: '#/enterprise/explore/' + encodeURIComponent(t) },
            h('i', null), t);
        }))));
  }

  // ── one topic or group ────────────────────────────────────────────────────
  function TopicView(p) {
    var G = TG(), res = p.resolved;
    var st = React.useState({ loading: true, rows: [], total: 0, err: null });
    var s = st[0], set = st[1];

    React.useEffect(function () {
      var live = true;
      var mx = MXC();
      if (!mx || !mx.searchFunding) {
        set({ loading: false, rows: [], total: 0, err: 'unavailable' });
        return;
      }
      var sectors = sectorsFor(res.topics);
      // One sector per query is what the RPC accepts; use the first resolved
      // sector rather than silently OR-ing a list the server cannot honour.
      var params = { page: 0, pageSize: 6, sortField: 'deadline', sortDirection: 'asc' };
      if (sectors && sectors.length) params.sector = sectors[0];
      mx.searchFunding(params).then(function (r) {
        if (!live) return;
        set({ loading: false, rows: r.records || [],
          total: (r.pagination && r.pagination.totalRecords) || 0, err: null });
      }).catch(function (e) {
        if (!live) return;
        set({ loading: false, rows: [], total: 0, err: (e && e.message) || 'Query failed' });
      });
      return function () { live = false; };
    }, [res.topics.join(',')]);

    function fundingBody() {
      if (s.loading) return h('p', { className: 'ete-empty' }, 'Loading funding…');
      if (s.err === 'unavailable') {
        return h('p', { className: 'ete-empty' },
          'Funding search is not available on this screen yet. Open Find funding to search the corpus directly.');
      }
      if (s.err) return h('p', { className: 'ete-empty' }, 'Funding could not be loaded: ' + s.err);
      if (!s.rows.length) {
        return h('p', { className: 'ete-empty' },
          'No active funding opportunities are currently recorded for ' + res.label.toLowerCase()
          + '. This reflects what Mira has verified so far, not the whole funding world.');
      }
      return h('div', null, s.rows.map(function (o, i) {
        return h('div', { className: 'ete-r', key: o.id || i },
          h('div', null,
            h('p', { className: 'ete-rt' }, o.title),
            h('p', { className: 'ete-rm' },
              [o.funder, (o.countries || []).slice(0, 2).join(', ') || null]
                .filter(Boolean).join(' · '))),
          h('div', { className: 'ete-rd' }, fmtAmount(o)));
      }));
    }

    return h('div', { className: 'ete', 'data-ui-part': 'topic-explorer-topic' },
      h('p', { className: 'ete-k' }, h('a', { href: '#/enterprise/explore', style: { color: 'inherit' } },
        '← Explore development')),
      h('h1', { className: 'ete-h1' }, res.label),
      h('p', { className: 'ete-lede' },
        res.kind === 'group'
          ? 'Funding and intelligence across ' + res.topics.join(', ') + '.'
          : 'Funding and intelligence connected to ' + res.label.toLowerCase() + '.'),

      // switcher — groups first, then every canonical topic
      h('nav', { className: 'ete-sw', 'aria-label': 'Switch topic' },
        G.GROUPS.map(function (g) {
          return h('a', { key: g.slug, href: '#/enterprise/explore/' + g.slug,
            className: res.kind === 'group' && res.label === g.label ? 'on' : '' }, g.label);
        }).concat(G.CANONICAL_TOPICS.map(function (t) {
          return h('a', { key: t, href: '#/enterprise/explore/' + encodeURIComponent(t),
            className: res.kind === 'topic' && res.label === t ? 'on' : '' }, t);
        }))),

      h('div', { className: 'ete-sec' },
        h('div', { className: 'ete-sh' },
          h('h2', null, 'Funding'),
          h('a', { href: '#/enterprise/funding' }, 'Find funding →')),
        fundingBody(),
        s.total > s.rows.length
          ? h('p', { className: 'ete-rm', style: { marginTop: '12px' } },
              'Showing ' + s.rows.length + ' of ' + s.total + ' recorded opportunities.')
          : null));
  }

  function NotFound(p) {
    return h('div', { className: 'ete', 'data-ui-part': 'topic-explorer-unknown' },
      h('p', { className: 'ete-k' }, 'Explore development'),
      h('h1', { className: 'ete-h1' }, 'That topic is not one we track'),
      h('div', { className: 'ete-bad' },
        h('p', { style: { margin: '0 0 14px', lineHeight: 1.55 } },
          '“' + String(p.raw).slice(0, 60) + '” is not one of the development areas Globally '
          + 'currently classifies.'),
        h('a', { className: 'ete-t', href: '#/enterprise/explore' }, 'See all topics')));
  }

  function Explorer(p) {
    injectCSS();
    var G = TG();
    if (!G) return h('div', { className: 'ete' }, h('p', null, 'Topic taxonomy unavailable.'));
    // parts: ['explore'] or ['explore', '<topic-or-group>']
    var raw = (p.parts && p.parts[1]) ? decodeURIComponent(p.parts[1]) : null;
    if (!raw) return h(Directory);
    var res = G.resolve(raw);
    if (!res) return h(NotFound, { raw: raw });
    return h(TopicView, { resolved: res });
  }

  window.EnterpriseTopicExplorer = Explorer;
})();
