// trf-parts.jsx — Traffic tab sections 1-3
const { HelpIcon: TrfHelpIcon, HelpTitle: TrfHelpTitle } = window.OV2_UI || {};

/* ============== util ============== */
const fmtTrf = (n) => {
  if (n == null) return '—';
  if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M';
  if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'k';
  return n.toLocaleString('ru-RU');
};
const fmtTrfFix = (n, d=1) => Number(n).toFixed(d);

/* ============== SECTION 1 — Snapshot ============== */
function TrfSnapshot({ state, lang }) {
  const t = window.TRF_T[lang];
  const help = window.TRF_HELP[lang];
  const data = window.TRF.snapshot[state] || window.TRF.snapshot.default;
  const cards = [
    { k: 'sessions',  lbl: t.snap.sessions,  fmt: 'int' },
    { k: 'users',     lbl: t.snap.users,     fmt: 'int' },
    { k: 'newUsers',  lbl: t.snap.newUsers,  fmt: 'int' },
    { k: 'pageViews', lbl: t.snap.pageViews, fmt: 'int' },
    { k: 'avgEngage', lbl: t.snap.avgEngage, fmt: 'time' },
    { k: 'bounce',    lbl: t.snap.bounce,    fmt: 'pct1' },
    { k: 'pps',       lbl: t.snap.pps,       fmt: 'dec2' },
    { k: 'eventsPer', lbl: t.snap.eventsPer, fmt: 'dec1' },
    { k: 'conv',      lbl: t.snap.conv,      fmt: 'pct2' },
    { k: 'revPerS',   lbl: t.snap.revPerS,   fmt: 'eur2' },
  ];
  const fmt = (v, kind) => {
    if (kind === 'int')  return fmtTrf(v);
    if (kind === 'time') return v + 's';
    if (kind === 'pct1') return v.toFixed(1) + '%';
    if (kind === 'pct2') return v.toFixed(2) + '%';
    if (kind === 'dec2') return v.toFixed(2);
    if (kind === 'dec1') return v.toFixed(1);
    if (kind === 'eur2') return '€' + v.toFixed(2);
    return v;
  };
  return (
    <div className="trf-snapshot">
      {cards.map(c => {
        const d = data[c.k];
        const positiveDir = !['bounce'].includes(c.k); // bounce: lower is better
        const isPositive = positiveDir ? d.delta >= 0 : d.delta <= 0;
        return (
          <div key={c.k} className={`trf-snap-card ${d.alert ? 'alert' : ''}`}>
            <div className="trf-snap-label">
              <span>{c.lbl}</span>
              <TrfHelpIcon help={help[c.k]} />
            </div>
            <div className="trf-snap-value">{fmt(d.value, c.fmt)}</div>
            <div className={`trf-snap-delta ${isPositive ? 'up' : 'down'}`}>
              {d.delta > 0 ? '↑' : d.delta < 0 ? '↓' : '·'} {Math.abs(d.delta).toFixed(1)}{c.fmt === 'pct1' || c.fmt === 'pct2' ? 'pp' : '%'}
              <span className="trf-snap-delta-lbl"> {t.deltaUp}</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ============== SECTION 2 — Channels ============== */
function TrfChannels({ lang }) {
  const t = window.TRF_T[lang];
  const help = window.TRF_HELP[lang];
  const rows = window.TRF.channels;
  const totalRev = rows.reduce((s, r) => s + r.rev, 0);
  const totalS = rows.reduce((s, r) => s + r.s, 0);

  return (
    <div className="trf-block">
      <div className="trf-block-head">
        <h2 className="trf-block-title">{t.chTitle}</h2>
      </div>

      {/* Table */}
      <div className="trf-card">
        <div className="trf-card-head">
          {TrfHelpTitle ? <TrfHelpTitle className="trf-card-title" help={help.channels}>{t.chTitle}</TrfHelpTitle> : <span className="trf-card-title">{t.chTitle}</span>}
        </div>
        <table className="trf-table">
          <thead>
            <tr>
              <th>{t.chTable.ch}</th>
              <th className="num">{t.chTable.s}</th>
              <th className="num">{t.chTable.u}</th>
              <th className="num">{t.chTable.new}</th>
              <th className="num">{t.chTable.avg}</th>
              <th className="num">{t.chTable.cr}</th>
              <th className="num">{t.chTable.rev}</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.ch}>
                <td>
                  <span className="trf-ch-row">
                    <span className="trf-dot" style={{ background: r.color }} />
                    <span>{r.ch}</span>
                  </span>
                </td>
                <td className="num">{fmtTrf(r.s)}</td>
                <td className="num">{fmtTrf(r.u)}</td>
                <td className="num">{r.newPct}%</td>
                <td className="num">{r.avg}s</td>
                <td className="num">
                  <span className="trf-bar-cell">
                    <span className="trf-bar-bg">
                      <span className="trf-bar-fg" style={{ width: `${Math.min(r.cr / 6 * 100, 100)}%`, background: r.color }} />
                    </span>
                    <span className="trf-bar-val">{r.cr.toFixed(2)}%</span>
                  </span>
                </td>
                <td className="num"><strong>€{fmtTrf(r.rev)}</strong></td>
              </tr>
            ))}
            <tr className="total">
              <td>Total</td>
              <td className="num">{fmtTrf(totalS)}</td>
              <td className="num">—</td>
              <td className="num">—</td>
              <td className="num">—</td>
              <td className="num">—</td>
              <td className="num"><strong>€{fmtTrf(totalRev)}</strong></td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Mix + scatter */}
      <div className="trf-2col">
        <div className="trf-card">
          <div className="trf-card-head">
            {TrfHelpTitle ? <TrfHelpTitle className="trf-card-title" help={help.channelMix}>{t.chMix}</TrfHelpTitle> : <span className="trf-card-title">{t.chMix}</span>}
          </div>
          <TrfStackedArea data={window.TRF.channelMix} />
          <div className="trf-legend">
            {[
              { k: 'org',  lbl: 'Organic',   c: '#10B981' },
              { k: 'dir',  lbl: 'Direct',    c: '#6366F1' },
              { k: 'paid', lbl: 'Paid',      c: '#F59E0B' },
              { k: 'soc',  lbl: 'Social',    c: '#EC4899' },
              { k: 'ref',  lbl: 'Referral',  c: '#06B6D4' },
              { k: 'em',   lbl: 'Email',     c: '#8B5CF6' },
              { k: 'dis',  lbl: 'Display',   c: '#EF4444' },
            ].map(l => (
              <span key={l.k} className="trf-legend-item">
                <span className="trf-dot" style={{ background: l.c }} /> {l.lbl}
              </span>
            ))}
          </div>
        </div>

        <div className="trf-card">
          <div className="trf-card-head">
            {TrfHelpTitle ? <TrfHelpTitle className="trf-card-title" help={help.channelQuality}>{t.chQuad}</TrfHelpTitle> : <span className="trf-card-title">{t.chQuad}</span>}
          </div>
          <TrfQuadrant data={rows.map(r => ({ x: r.s, y: r.cr, r: Math.sqrt(r.rev) / 4, label: r.ch, color: r.color }))} xLabel="Sessions" yLabel="CR %" />
        </div>
      </div>
    </div>
  );
}

/* ====== Stacked area chart ====== */
function TrfStackedArea({ data }) {
  const w = 580, h = 220, padL = 36, padR = 16, padT = 16, padB = 32;
  const keys = ['org', 'dir', 'paid', 'soc', 'ref', 'em', 'dis'];
  const colors = { org: '#10B981', dir: '#6366F1', paid: '#F59E0B', soc: '#EC4899', ref: '#06B6D4', em: '#8B5CF6', dis: '#EF4444' };
  const xs = data.map((_, i) => padL + i * (w - padL - padR) / (data.length - 1));
  const layers = [];
  let acc = data.map(() => 0);
  keys.forEach(k => {
    const top = data.map((d, i) => acc[i] + d[k]);
    const yTop = top.map(v => padT + (h - padT - padB) * (1 - v / 100));
    const yBot = acc.map(v => padT + (h - padT - padB) * (1 - v / 100));
    let path = `M ${xs[0]} ${yTop[0]}`;
    for (let i = 1; i < xs.length; i++) path += ` L ${xs[i]} ${yTop[i]}`;
    for (let i = xs.length - 1; i >= 0; i--) path += ` L ${xs[i]} ${yBot[i]}`;
    path += ' Z';
    layers.push({ k, path });
    acc = top;
  });
  return (
    <svg className="trf-svg" viewBox={`0 0 ${w} ${h}`}>
      {[0, 25, 50, 75, 100].map(p => {
        const y = padT + (h - padT - padB) * (1 - p / 100);
        return (
          <g key={p}>
            <line x1={padL} x2={w - padR} y1={y} y2={y} stroke="var(--border)" strokeDasharray={p === 0 ? '0' : '2 4'} />
            <text x={padL - 6} y={y + 3} textAnchor="end" fontSize="10" fill="var(--text-3)">{p}%</text>
          </g>
        );
      })}
      {layers.map(l => (
        <path key={l.k} d={l.path} fill={colors[l.k]} opacity="0.85" />
      ))}
      {data.map((d, i) => (
        <text key={i} x={xs[i]} y={h - padB + 14} textAnchor="middle" fontSize="10" fill="var(--text-3)">{d.w}</text>
      ))}
    </svg>
  );
}

/* ====== Bubble quadrant ====== */
function TrfQuadrant({ data, xLabel, yLabel }) {
  const w = 580, h = 240, padL = 44, padR = 24, padT = 16, padB = 36;
  const xMin = 0, xMax = Math.max(...data.map(d => d.x)) * 1.1;
  const yMin = 0, yMax = Math.max(...data.map(d => d.y)) * 1.15;
  const xMid = (xMin + xMax) / 2, yMid = (yMin + yMax) / 2;
  const X = (v) => padL + (w - padL - padR) * (v - xMin) / (xMax - xMin);
  const Y = (v) => padT + (h - padT - padB) * (1 - (v - yMin) / (yMax - yMin));
  return (
    <svg className="trf-svg" viewBox={`0 0 ${w} ${h}`}>
      {/* quadrant lines */}
      <line x1={X(xMid)} x2={X(xMid)} y1={padT} y2={h - padB} stroke="var(--border)" strokeDasharray="3 3"/>
      <line x1={padL} x2={w - padR} y1={Y(yMid)} y2={Y(yMid)} stroke="var(--border)" strokeDasharray="3 3"/>
      {/* axes */}
      <line x1={padL} x2={w - padR} y1={h - padB} y2={h - padB} stroke="var(--border-strong)"/>
      <line x1={padL} x2={padL} y1={padT} y2={h - padB} stroke="var(--border-strong)"/>
      <text x={(w + padL - padR) / 2} y={h - 6} textAnchor="middle" fontSize="10" fill="var(--text-3)">{xLabel}</text>
      <text x={12} y={(h + padT - padB) / 2} textAnchor="middle" fontSize="10" fill="var(--text-3)" transform={`rotate(-90 12 ${(h + padT - padB) / 2})`}>{yLabel}</text>
      {/* bubbles */}
      {data.map((d, i) => (
        <g key={i}>
          <circle cx={X(d.x)} cy={Y(d.y)} r={Math.max(d.r || 8, 4)} fill={d.color} opacity="0.7" stroke={d.color}/>
          <text x={X(d.x)} y={Y(d.y) - (d.r || 8) - 4} textAnchor="middle" fontSize="10" fill="var(--text-2)">{d.label}</text>
        </g>
      ))}
    </svg>
  );
}

/* ============== SECTION 3 — Pages ============== */
function TrfPages({ lang }) {
  const t = window.TRF_T[lang];
  const help = window.TRF_HELP[lang];
  const rows = window.TRF.pages;
  return (
    <div className="trf-block">
      <div className="trf-block-head">
        <h2 className="trf-block-title">{t.pgTitle}</h2>
      </div>

      <div className="trf-card">
        <div className="trf-card-head">
          {TrfHelpTitle ? <TrfHelpTitle className="trf-card-title" help={help.pages}>{t.pgTitle}</TrfHelpTitle> : <span className="trf-card-title">{t.pgTitle}</span>}
        </div>
        <table className="trf-table">
          <thead>
            <tr>
              <th>{t.pgTable.url}</th>
              <th className="num">{t.pgTable.s}</th>
              <th className="num">{t.pgTable.u}</th>
              <th className="num">{t.pgTable.t}</th>
              <th className="num">{t.pgTable.e}</th>
              <th className="num">{t.pgTable.cr}</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.url}>
                <td><code className="trf-url">{r.url}</code></td>
                <td className="num">{fmtTrf(r.s)}</td>
                <td className="num">{fmtTrf(r.u)}</td>
                <td className="num">{r.t}s</td>
                <td className="num">
                  <span className={`trf-pill ${r.exit > 50 ? 'warn' : ''}`}>{r.exit}%</span>
                </td>
                <td className="num">
                  <strong className={r.cr >= 5 ? 'pos' : r.cr < 1 ? 'neg' : ''}>{r.cr.toFixed(2)}%</strong>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="trf-2col">
        <div className="trf-card">
          <div className="trf-card-head">
            {TrfHelpTitle ? <TrfHelpTitle className="trf-card-title" help={help.pageQuality}>{t.pgQuad}</TrfHelpTitle> : <span className="trf-card-title">{t.pgQuad}</span>}
          </div>
          <TrfQuadrant
            data={rows.slice(0, 8).map((r, i) => ({
              x: r.t, y: r.cr,
              r: Math.sqrt(r.s) / 6,
              label: r.url.length > 18 ? r.url.slice(0, 16) + '…' : r.url,
              color: r.cr >= 5 ? '#10B981' : r.cr < 1 ? '#EF4444' : '#F59E0B',
            }))}
            xLabel="Avg time, s"
            yLabel="CR %"
          />
        </div>

        <div className="trf-card">
          <div className="trf-card-head">
            {TrfHelpTitle ? <TrfHelpTitle className="trf-card-title" help={help.paths}>{t.pgPaths}</TrfHelpTitle> : <span className="trf-card-title">{t.pgPaths}</span>}
          </div>
          <div className="trf-paths">
            {window.TRF.paths.map((p, i) => {
              const cr = p.count > 0 ? (p.conv / p.count * 100) : 0;
              return (
                <div key={i} className="trf-path-row">
                  <div className="trf-path-flow">
                    {p.path.map((u, j) => (
                      <React.Fragment key={j}>
                        <span className="trf-path-node"><code>{u}</code></span>
                        {j < p.path.length - 1 && <span className="trf-path-arrow">→</span>}
                      </React.Fragment>
                    ))}
                  </div>
                  <div className="trf-path-stats">
                    <span className="trf-path-count">{fmtTrf(p.count)}</span>
                    <span className={`trf-path-cr ${cr >= 10 ? 'pos' : cr < 2 ? 'neg' : ''}`}>CR {cr.toFixed(1)}%</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

window.TrfSnapshot = TrfSnapshot;
window.TrfChannels = TrfChannels;
window.TrfPages = TrfPages;
window.TrfStackedArea = TrfStackedArea;
window.TrfQuadrant = TrfQuadrant;
