// cust-parts.jsx — Customer Insights sections 1 & 2
const { HelpIcon: CustHelpIcon, HelpTitle: CustHelpTitle } = window.OV2_UI || {};

const fmtCust = (n) => {
  if (n == null) return '—';
  if (Math.abs(n) >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M';
  if (Math.abs(n) >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'k';
  return n.toLocaleString('ru-RU');
};

function CustAvatar({ name, size = 32, privacyMode }) {
  const init = window.initialsOf(name);
  const color = window.avatarColor(name);
  return (
    <span className="cust-avatar" style={{ width: size, height: size, background: color, fontSize: size * 0.42 }}>
      {init}
    </span>
  );
}

function CustGuestName({ name, privacyMode }) {
  return <span className="cust-guest-name">{privacyMode ? window.maskName(name) : name}</span>;
}

/* ============ SECTION 1 — Snapshot ============ */
function CustSnapshot({ state, lang }) {
  const t = window.CUST_T[lang];
  const help = t.snapInfo || window.CUST_T.en.snapInfo || {};
  const data = window.CUST.snapshot[state] || window.CUST.snapshot.default;
  const baseDef = window.CUST.snapshot.default;

  const cards = [
    { k: 'total',      lbl: t.snap.total,      sub: t.snap.totalSub },
    { k: 'active',     lbl: t.snap.active,     sub: t.snap.activeSub },
    { k: 'newG',       lbl: t.snap.newG,       sub: t.snap.newSub },
    { k: 'repeat',     lbl: t.snap.repeat,     sub: t.snap.repeatSub },
    { k: 'repeatRate', lbl: t.snap.repeatRate, sub: t.snap.repeatRateSub },
    { k: 'ltv',        lbl: t.snap.ltv,        sub: null },
    { k: 'bpg',        lbl: t.snap.bpg,        sub: t.snap.bpgSub },
    { k: 'tbv',        lbl: t.snap.tbv,        sub: t.snap.tbvSub },
    { k: 'conc',       lbl: t.snap.conc,       sub: t.snap.concSub },
    { k: 'review',     lbl: t.snap.review,     sub: t.snap.reviewSub },
  ];

  const fmtVal = (k, v) => {
    const def = baseDef[k];
    const fmt = def.fmt;
    if (fmt === 'int')  return fmtCust(v);
    if (fmt === 'pct')  return v.toFixed(1) + '%';
    if (fmt === 'eur')  return '€' + fmtCust(v);
    if (fmt === 'dec1') return v.toFixed(1);
    if (fmt === 'mo')   return v.toFixed(1) + ' мес';
    return v;
  };
  const fmtDelta = (k, d) => {
    const def = baseDef[k];
    const f = def.deltaFmt;
    const sign = d > 0 ? '+' : d < 0 ? '−' : '';
    const abs = Math.abs(d);
    if (f === 'abs')  return sign + abs;
    if (f === 'abs1') return sign + abs.toFixed(1);
    if (f === 'pp')   return sign + abs.toFixed(1) + ' п.п.';
    if (f === 'eur')  return sign + '€' + abs;
    if (f === 'mo')   return sign + abs.toFixed(1) + ' мес';
    return sign + abs;
  };

  return (
    <div className="cust-snapshot">
      {cards.map(c => {
        const d = data[c.k];
        const def = baseDef[c.k];
        const positiveDir = !def.invert;
        const isPositive = d.delta === 0 ? null : positiveDir ? d.delta > 0 : d.delta < 0;
        const sub = c.k === 'ltv' ? `${t.snap.ltvSub} €${d.median}` : c.sub;
        return (
          <div key={c.k} className={`cust-snap-card ${d.alert ? 'alert' : ''}`}>
            <div className="cust-snap-label">
              <span>{c.lbl}</span>
              {CustHelpIcon && <CustHelpIcon help={help[c.k]} />}
            </div>
            <div className="cust-snap-value">{fmtVal(c.k, d.value)}</div>
            <div className="cust-snap-meta">
              {d.delta !== 0 && (
                <span className={`cust-snap-delta ${isPositive ? 'up' : 'down'}`}>
                  {d.delta > 0 ? '↑' : '↓'} {fmtDelta(c.k, d.delta)}
                </span>
              )}
              {d.delta === 0 && <span className="cust-snap-delta flat">→</span>}
              <span className="cust-snap-sub">{sub}</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ============ SECTION 2 — RFM ============ */
function CustRfm({ lang, onOpenSegment, emptyMigration }) {
  const t = window.CUST_T[lang];
  const help = t.help || {};
  const matrix = window.CUST.rfmMatrix;
  const segs = window.CUST.segments;
  const totalRev = segs.reduce((s, x) => s + x.rev, 0);
  const rfmRows = matrix.map((row, idx) => ({ label: t.rfm.yLabels[idx], row })).reverse();

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

      {/* Matrix */}
      <div className="cust-card">
        <div className="cust-card-head">{CustHelpTitle ? <CustHelpTitle className="cust-card-title" help={help.rfmMatrix}>{t.rfm.title}</CustHelpTitle> : <span className="cust-card-title">{t.rfm.title}</span>}</div>
        <div className="cust-rfm-wrap">
          <div className="cust-rfm-grid-wrap">
            <span className="cust-rfm-axis-lbl">{t.rfm.y}</span>
            <div className="cust-rfm-grid">
              {rfmRows.map((rowData) => (
                <React.Fragment key={rowData.label}>
                  <div className="cust-rfm-y">{rowData.label}</div>
                  <div className="cust-rfm-row">
                  {rowData.row.map((cell, colIdx) => {
                    const seg = cell.seg;
                    const empty = cell.n === 0;
                    const segName = seg !== 'empty' && seg !== 'newSeg' ? t.seg[seg] : (seg === 'newSeg' ? t.seg.newSeg : '');
                    return (
                      <button
                        key={colIdx}
                        type="button"
                        className={`cust-rfm-cell ${empty ? 'empty' : ''}`}
                        style={{ background: empty ? 'transparent' : window.SEG_COLORS[seg] }}
                        title={empty ? '' : `${segName} · ${cell.n} guests`}
                        onClick={() => !empty && onOpenSegment && onOpenSegment(seg)}
                        disabled={empty}
                      >
                        {!empty && <span className="cust-rfm-n">{cell.n}</span>}
                      </button>
                    );
                  })}
                  </div>
                </React.Fragment>
              ))}
            </div>
            <div className="cust-rfm-xaxis">
              <span></span>
              <div className="cust-rfm-xgrid">
                {t.rfm.xLabels.map((x, i) => (
                  <div key={i} className="cust-rfm-x">{x}</div>
                ))}
              </div>
              <span className="cust-rfm-axis-lbl x">{t.rfm.x}</span>
            </div>
          </div>
        </div>
        {/* legend */}
        <div className="cust-rfm-legend">
          {['champions', 'loyal', 'promising', 'atrisk', 'hibernating', 'lost'].map(s => (
            <span key={s} className="cust-rfm-legend-item" title={t.legend[s]}>
              <span className="cust-rfm-legend-sw" style={{ background: window.SEG_COLORS[s] }} />
              {t.seg[s]}
            </span>
          ))}
        </div>
      </div>

      {/* Segment overview table */}
      <div className="cust-card">
        <div className="cust-card-head">{CustHelpTitle ? <CustHelpTitle className="cust-card-title" help={help.segmentSummary}>{t.rfm.summaryTitle}</CustHelpTitle> : <span className="cust-card-title">{t.rfm.summaryTitle}</span>}</div>
        <table className="cust-table">
          <thead>
            <tr>
              <th>{t.rfm.cols.seg}</th>
              <th className="num">{t.rfm.cols.g}</th>
              <th className="num">{t.rfm.cols.basePct}</th>
              <th className="num">{t.rfm.cols.avgLTV}</th>
              <th className="num">{t.rfm.cols.rev}</th>
              <th className="num">{t.rfm.cols.revPct}</th>
            </tr>
          </thead>
          <tbody>
            {segs.map(s => (
              <tr key={s.id} className="clickable" onClick={() => onOpenSegment && onOpenSegment(s.id)}>
                <td>
                  <span className="cust-seg-row">
                    <span className="cust-seg-dot" style={{ background: window.SEG_COLORS[s.id] }} />
                    <span>{t.seg[s.id]}</span>
                  </span>
                </td>
                <td className="num">{s.guests}</td>
                <td className="num">
                  <span className="cust-bar-cell">
                    <span className="cust-mini-bar" style={{ width: `${s.basePct * 2}px`, background: window.SEG_COLORS[s.id], opacity: 0.5 }} />
                    {s.basePct}%
                  </span>
                </td>
                <td className="num">€{fmtCust(s.ltv)}</td>
                <td className="num">€{fmtCust(s.rev)}</td>
                <td className="num">
                  <span className="cust-bar-cell">
                    <span className="cust-mini-bar" style={{ width: `${s.revPct * 2}px`, background: window.SEG_COLORS[s.id] }} />
                    <strong>{s.revPct}%</strong>
                  </span>
                </td>
              </tr>
            ))}
            <tr className="total">
              <td>Total</td>
              <td className="num">{segs.reduce((s,x) => s + x.guests, 0)}</td>
              <td className="num">100%</td>
              <td className="num">—</td>
              <td className="num">€{fmtCust(totalRev)}</td>
              <td className="num">100%</td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Migration sankey */}
      <div className="cust-card">
        <div className="cust-card-head">{CustHelpTitle ? <CustHelpTitle className="cust-card-title" help={help.segmentMigration}>{t.rfm.migrationTitle}</CustHelpTitle> : <span className="cust-card-title">{t.rfm.migrationTitle}</span>}</div>
        {emptyMigration ? (
          <div className="cust-empty">{t.rfm.migrationEmpty}</div>
        ) : (
          <CustSankey data={window.CUST.migration} lang={lang} />
        )}
      </div>
    </div>
  );
}

/* ====== Mini Sankey for migration ====== */
function CustSankey({ data, lang }) {
  const t = window.CUST_T[lang];
  const w = 880, h = 260, padL = 110, padR = 110, padT = 16, padB = 16;
  // Collect from/to nodes
  const fromKeys = [...new Set(data.map(d => d.from))];
  const toKeys = [...new Set(data.map(d => d.to))];
  const fromTotal = (k) => data.filter(d => d.from === k).reduce((s, d) => s + d.n, 0);
  const toTotal   = (k) => data.filter(d => d.to === k).reduce((s, d) => s + d.n, 0);
  const totalAll = data.reduce((s, d) => s + d.n, 0);
  const innerH = h - padT - padB;
  const gap = 6;
  // y positions for from nodes
  let cum = 0;
  const fromPos = {};
  fromKeys.forEach(k => {
    const tot = fromTotal(k);
    const ph = (tot / totalAll) * (innerH - gap * (fromKeys.length - 1));
    fromPos[k] = { y: padT + cum, h: ph, total: tot };
    cum += ph + gap;
  });
  cum = 0;
  const toPos = {};
  toKeys.forEach(k => {
    const tot = toTotal(k);
    const ph = (tot / totalAll) * (innerH - gap * (toKeys.length - 1));
    toPos[k] = { y: padT + cum, h: ph, total: tot };
    cum += ph + gap;
  });
  // Compute flow ribbons with offsets within nodes
  const fromOff = {}; const toOff = {};
  fromKeys.forEach(k => fromOff[k] = 0);
  toKeys.forEach(k => toOff[k] = 0);
  const flows = data.map(d => {
    const fp = fromPos[d.from];
    const tp = toPos[d.to];
    const fH = (d.n / fp.total) * fp.h;
    const tH = (d.n / tp.total) * tp.h;
    const y0 = fp.y + fromOff[d.from]; fromOff[d.from] += fH;
    const y1 = tp.y + toOff[d.to];     toOff[d.to] += tH;
    return { ...d, y0, y0e: y0 + fH, y1, y1e: y1 + tH };
  });
  const xL = padL, xR = w - padR;
  const path = (f) => {
    const cx = (xL + xR) / 2;
    return `M ${xL} ${f.y0} C ${cx} ${f.y0}, ${cx} ${f.y1}, ${xR} ${f.y1} L ${xR} ${f.y1e} C ${cx} ${f.y1e}, ${cx} ${f.y0e}, ${xL} ${f.y0e} Z`;
  };
  return (
    <svg className="cust-svg" viewBox={`0 0 ${w} ${h}`}>
      {flows.map((f, i) => (
        <path key={i} d={path(f)} fill={window.SEG_COLORS[f.from]} opacity="0.35">
          <title>{t.seg[f.from]} → {t.seg[f.to]}: {f.n}</title>
        </path>
      ))}
      {fromKeys.map(k => (
        <g key={'f'+k}>
          <rect x={xL - 14} y={fromPos[k].y} width={14} height={fromPos[k].h} fill={window.SEG_COLORS[k]} />
          <text x={xL - 20} y={fromPos[k].y + fromPos[k].h / 2 + 4} textAnchor="end" fontSize="11" fill="var(--text-2)">
            {t.seg[k]} ({fromPos[k].total})
          </text>
        </g>
      ))}
      {toKeys.map(k => (
        <g key={'t'+k}>
          <rect x={xR} y={toPos[k].y} width={14} height={toPos[k].h} fill={window.SEG_COLORS[k]} />
          <text x={xR + 20} y={toPos[k].y + toPos[k].h / 2 + 4} textAnchor="start" fontSize="11" fill="var(--text-2)">
            {t.seg[k]} ({toPos[k].total})
          </text>
        </g>
      ))}
    </svg>
  );
}

window.CustAvatar = CustAvatar;
window.CustGuestName = CustGuestName;
window.CustSnapshot = CustSnapshot;
window.CustRfm = CustRfm;
window.CustSankey = CustSankey;
window.fmtCust = fmtCust;
