/* AI-referred traffic and orders: the "AI traffic" tab.

   Shown to the client with the code and to the team in admin. Every
   figure is a lower bound and the page says so; the weekly chart carries
   markers for the dates fixes were verified and says they are dates, not
   causes. "Not measured yet" until a connection exists and numbers were
   pulled. */

function fmtMoney(v, cur) {
  if (v === null || v === undefined) return '—';
  const n = Number(v);
  return (cur ? cur + ' ' : '$') + n.toLocaleString(undefined, { maximumFractionDigits: 0 });
}

function WeeklyChart({ series, markers }) {
  if (!series || !series.length) return null;
  const w = 720, h = 170, pad = 28, bw = Math.max(6, (w - pad * 2) / series.length - 4);
  const max = Math.max(1, ...series.map((s) => s.sessions + s.orders));
  const x = (i) => pad + i * ((w - pad * 2) / series.length);
  const markerWeeks = {};
  (markers || []).forEach((m) => { (markerWeeks[m.week] = markerWeeks[m.week] || []).push(m); });
  return (
    <div style={{ overflowX: 'auto' }}>
      <svg viewBox={`0 0 ${w} ${h + 30}`} width="100%" style={{ maxWidth: w, display: 'block' }} role="img" aria-label="AI-referred sessions per week">
        {series.map((s, i) => {
          const hs = (s.sessions / max) * h, ho = (s.orders / max) * h;
          const ms = markerWeeks[s.week];
          return (
            <g key={s.week}>
              <rect x={x(i)} y={pad + h - hs} width={bw} height={hs} fill="var(--accent)" opacity="0.85">
                <title>{`week of ${s.week}: ${s.sessions} AI-referred sessions, ${s.conversions} key events${s.orders ? `, ${s.orders} orders` : ''}`}</title>
              </rect>
              {s.orders > 0 && <rect x={x(i)} y={pad + h - hs - ho} width={bw} height={ho} fill="var(--good)" opacity="0.9" />}
              {ms && <g>
                <line x1={x(i) + bw / 2} x2={x(i) + bw / 2} y1={pad - 6} y2={pad + h} stroke="var(--warn)" strokeDasharray="3 3" />
                <circle cx={x(i) + bw / 2} cy={pad - 10} r="5" fill="var(--warn)"><title>{ms.map((m) => `${m.date}: ${m.title || m.kind}`).join('\n')}</title></circle>
              </g>}
              {(i % Math.ceil(series.length / 8) === 0) && <text x={x(i)} y={pad + h + 16} fontSize="10" fill="var(--fg-subtle)" fontFamily="var(--font-mono)">{s.week.slice(5)}</text>}
            </g>);
        })}
      </svg>
      <div className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)', display: 'flex', gap: 14, flexWrap: 'wrap' }}>
        <span><span style={{ display: 'inline-block', width: 10, height: 10, background: 'var(--accent)', marginRight: 5, verticalAlign: 'middle' }}></span>AI-referred sessions</span>
        <span><span style={{ display: 'inline-block', width: 10, height: 10, background: 'var(--good)', marginRight: 5, verticalAlign: 'middle' }}></span>AI-referred orders</span>
        <span><span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: 5, background: 'var(--warn)', marginRight: 5, verticalAlign: 'middle' }}></span>a fix was verified that week</span>
      </div>
    </div>);
}

function AttributionNotMeasured({ a, admin }) {
  const m = (a && a.measured) || {};
  const connected = m.ga4 || m.shopify;
  return (
    <div style={{ padding: '28px 24px', borderRadius: 'var(--r-lg)', background: 'var(--navy-2)',
      border: '1px solid var(--line)', color: 'var(--fg-muted)', fontSize: 14.5, lineHeight: 1.7, maxWidth: 720 }}>
      <div style={{ color: 'var(--fg)', fontWeight: 600, marginBottom: 6 }}>Not measured yet.</div>
      {connected
        ? 'A connection exists but the numbers have not been pulled yet.' + (admin ? ' Use "Pull the numbers" in the AI traffic panel.' : '')
        : 'This measures visits and orders that arrived from an AI assistant, from your own Google Analytics 4 and Shopify. Nothing is shown until one of them is connected' + (admin ? ' (AI traffic panel above).' : ' by the Lojo team with your help.')}
    </div>);
}

function AttributionTab({ report, admin }) {
  const a = report.attribution;
  if (!a || !a.series) return <AttributionNotMeasured a={a} admin={admin} />;
  const t = a.totals || {};
  const cur = a.currency;
  const tiles = [
    { label: 'AI-referred sessions', value: t.sessions, note: a.share.sessions !== null && a.share.sessions !== undefined ? `${(a.share.sessions * 100).toFixed(1)}% of all sessions · ${a.days} days` : `${a.days} days` },
    { label: 'Key events from AI', value: t.conversions, note: a.measured.ga4 ? 'GA4 key events on those sessions' : 'needs GA4' },
    { label: 'Orders from AI', value: a.measured.shopify ? t.orders : '—', note: a.measured.shopify ? (a.share.orders !== null ? `${(a.share.orders * 100).toFixed(1)}% of all orders` : '') : 'needs Shopify' },
    { label: 'Revenue from AI', value: a.measured.shopify || t.revenue ? fmtMoney(t.revenue, cur) : '—', note: a.measured.shopify ? 'Shopify orders, refunds excluded' : (t.revenue ? 'GA4 reported revenue' : 'needs Shopify') },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div style={{ padding: '12px 16px', borderRadius: 'var(--r-md)', background: 'var(--warn-bg)', border: '1px solid color-mix(in oklab, var(--warn) 40%, transparent)', fontSize: 13, color: 'var(--fg)', lineHeight: 1.6 }}>
        <span className="mono" style={{ fontSize: 10.5, color: 'var(--warn)', letterSpacing: '0.08em' }}>LOWER BOUND · </span>{a.label}
        {' '}Pulled {String(a.computed_at || '').slice(0, 10)} from {[a.measured.ga4 && 'Google Analytics 4', a.measured.shopify && 'Shopify'].filter(Boolean).join(' and ')}.
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 12 }}>
        {tiles.map((s, i) => <StatTile key={i} s={s} />)}
      </div>
      <div>
        <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--fg-subtle)', marginBottom: 8 }}>By week</div>
        <WeeklyChart series={a.series} markers={a.markers} />
        <div style={{ fontSize: 12.5, color: 'var(--fg-subtle)', lineHeight: 1.6, marginTop: 8 }}>{a.markers_note}</div>
        {(a.markers || []).length > 0 &&
        <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 6 }}>
          {a.markers.slice(-6).map((m, i) => <div key={i}><span className="mono" style={{ color: 'var(--fg-subtle)' }}>{m.date}</span> · {m.title || m.kind}</div>)}
        </div>}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 14 }}>
        <div>
          <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--fg-subtle)', marginBottom: 8 }}>By assistant</div>
          {(a.sources || []).length === 0
            ? <div style={{ fontSize: 13.5, color: 'var(--fg-subtle)' }}>No AI-referred visit or order was identified in this window.</div>
            : <BenchTable head={['Assistant', 'Sessions', 'Key events', 'Orders', 'Revenue']}
                rows={a.sources.map((s) => [s.label, s.sessions, s.conversions, a.measured.shopify ? s.orders : '—', s.revenue ? fmtMoney(s.revenue, cur) : '—'])} />}
        </div>
        <div>
          <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--fg-subtle)', marginBottom: 8 }}>Pages AI visitors land on</div>
          {(a.landing_pages || []).length === 0
            ? <div style={{ fontSize: 13.5, color: 'var(--fg-subtle)' }}>{a.measured.ga4 ? 'No AI-referred landing page in this window.' : 'Needs GA4.'}</div>
            : <BenchTable head={['Page', 'Sessions', 'Key events']}
                rows={a.landing_pages.slice(0, 10).map((p) => [p.page, p.sessions, p.conversions])} />}
        </div>
      </div>
      {a.errors && Object.keys(a.errors).length > 0 &&
      <div style={{ fontSize: 13, color: 'var(--warn)' }}>Part of the data could not be read: {Object.entries(a.errors).map(([k, v]) => `${k}: ${v}`).join('; ')}</div>}
    </div>);
}
