/* AIWine CRM — Market Intelligence.
   Reads scan_intel: every off-catalogue bottle an app user identified — i.e.
   what NZ drinkers want but can't yet buy from AIWine. Aggregated into a
   recruitment shortlist (producers not on the platform, ranked by demand),
   plus variety & region demand. All computed client-side. */

function Market({ country }) {
  const store = window.UI.useStore();
  const { Ic, toast } = window.UI;

  const rows = store.t('scan_intel') || [];
  const wineries = store.t('wineries') || [];

  const norm = (s) => String(s || '').toLowerCase().replace(/^the\s+/, '').replace(/[^a-z0-9 ]/g, ' ').replace(/\s+/g, ' ').trim();
  const onPlatform = React.useMemo(() => new Set(wineries.map((w) => norm(w.name))), [wineries]);

  // ---- aggregate by producer ----
  const byProducer = {};
  rows.forEach((r) => {
    const key = norm(r.producer);
    if (!key) return;
    const g = (byProducer[key] = byProducer[key] || { name: r.producer, count: 0, varieties: {}, regions: {}, last: 0 });
    g.count++;
    if (r.variety) g.varieties[r.variety] = (g.varieties[r.variety] || 0) + 1;
    if (r.region) g.regions[r.region] = (g.regions[r.region] || 0) + 1;
    const ts = Date.parse(r.created_at) || 0; if (ts > g.last) g.last = ts;
  });
  const top1 = (obj) => { const e = Object.entries(obj).sort((a, b) => b[1] - a[1])[0]; return e ? e[0] : ''; };
  const producers = Object.values(byProducer)
    .map((g) => ({ ...g, topVariety: top1(g.varieties), topRegion: top1(g.regions), listed: onPlatform.has(norm(g.name)) }))
    .sort((a, b) => b.count - a.count);
  const targets = producers.filter((p) => !p.listed);

  // ---- variety & region demand ----
  const tally = (field) => {
    const t = {}; rows.forEach((r) => { const k = (r[field] || '').trim(); if (k) t[k] = (t[k] || 0) + 1; });
    return Object.entries(t).sort((a, b) => b[1] - a[1]);
  };
  const varieties = tally('variety');
  const regions = tally('region');
  const maxV = varieties.length ? varieties[0][1] : 0;
  const maxR = regions.length ? regions[0][1] : 0;

  const since = rows.reduce((m, r) => Math.min(m, Date.parse(r.created_at) || Date.now()), Date.now());
  const days = Math.max(1, Math.round((Date.now() - since) / 86400000));

  const recruit = (name) => {
    try { navigator.clipboard && navigator.clipboard.writeText(name); } catch (e) {}
    toast(`"${name}" copied — add them as a lead`);
    window.go('wineries');
  };

  const Bar = ({ frac, color }) => (
    <div style={{ flex: 1, height: 8, background: 'var(--bone-alt)', borderRadius: 999, overflow: 'hidden' }}>
      <div style={{ width: Math.max(2, Math.round((frac || 0) * 100)) + '%', height: '100%', background: color || 'var(--claret)' }}></div>
    </div>
  );

  const when = (ts) => { if (!ts) return '—'; const d = Math.round((Date.now() - ts) / 86400000); return d <= 0 ? 'today' : d === 1 ? '1d ago' : d < 30 ? d + 'd ago' : Math.round(d / 30) + 'mo ago'; };

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>{rows.length} off-catalogue scans · last {days} days</div>
          <h1 className="page-title">Market intelligence</h1>
        </div>
      </div>

      {rows.length === 0 && (
        <window.UI.Empty
          msg="No demand signals yet"
          hint="When app users scan a wine AIWine doesn't stock, it lands here — a live shortlist of wineries worth recruiting. Run migration 11-scan-intel.sql if this stays empty." />
      )}

      {rows.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(3,1fr)' }}>
            <div className="stat-tile"><div className="label">Demand signals</div><div className="num" style={{ fontSize: 26 }}>{rows.length}</div></div>
            <div className="stat-tile"><div className="label">Distinct producers</div><div className="num" style={{ fontSize: 26 }}>{producers.length}</div></div>
            <div className="stat-tile"><div className="label">Not yet on AIWine</div><div className="num" style={{ fontSize: 26, color: 'var(--claret)' }}>{targets.length}</div></div>
          </div>

          {/* recruitment shortlist */}
          <div className="card">
            <div className="card-head">
              <h3 className="card-title">Recruitment shortlist</h3>
              <span className="label" style={{ fontSize: 9 }}>producers your customers want · not yet stocked</span>
            </div>
            <div className="card-pad" style={{ padding: 0 }}>
              <table className="tbl">
                <thead><tr><th className="l">Producer</th><th className="l">Most-wanted</th><th className="l">Region</th><th>Demand</th><th>Last</th><th></th></tr></thead>
                <tbody>
                  {targets.slice(0, 30).map((p) => (
                    <tr key={p.name}>
                      <td className="l" style={{ fontWeight: 600 }}>{p.name}</td>
                      <td className="l" style={{ color: 'var(--ink-soft)' }}>{p.topVariety || '—'}</td>
                      <td className="l" style={{ color: 'var(--ink-soft)' }}>{p.topRegion || '—'}</td>
                      <td className="num">{p.count}</td>
                      <td className="num" style={{ color: 'var(--muted)' }}>{when(p.last)}</td>
                      <td style={{ textAlign: 'right' }}>
                        <button className="btn-sm" onClick={() => recruit(p.name)}><Ic name="plus" w={13} /> Recruit</button>
                      </td>
                    </tr>
                  ))}
                  {targets.length === 0 && <tr><td className="l" colSpan={6} style={{ color: 'var(--muted)', padding: 14 }}>Every scanned producer is already on AIWine — great coverage.</td></tr>}
                </tbody>
              </table>
            </div>
          </div>

          <div className="split">
            <div className="card">
              <div className="card-head"><h3 className="card-title">Variety demand</h3></div>
              <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                {varieties.slice(0, 8).map(([k, n]) => (
                  <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <span style={{ width: 130, fontSize: 12.5, color: 'var(--ink-soft)' }}>{k}</span>
                    <Bar frac={maxV ? n / maxV : 0} color="var(--claret)" />
                    <span className="mono" style={{ width: 34, textAlign: 'right', fontSize: 12 }}>{n}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="card">
              <div className="card-head"><h3 className="card-title">Region demand</h3></div>
              <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                {regions.slice(0, 8).map(([k, n]) => (
                  <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <span style={{ width: 130, fontSize: 12.5, color: 'var(--ink-soft)' }}>{k}</span>
                    <Bar frac={maxR ? n / maxR : 0} color="var(--brass)" />
                    <span className="mono" style={{ width: 34, textAlign: 'right', fontSize: 12 }}>{n}</span>
                  </div>
                ))}
                {regions.length === 0 && <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>No region data yet.</div>}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.Market = Market;
