// cust-parts2.jsx — Customer Insights sections 3 & 4
const { HelpTitle: CustHelpTitle2 } = window.OV2_UI || {};

/* ============ SECTION 3 — LTV & Cohorts ============ */
function CustLtvCohorts({ state, lang, onOpenCohort, emptyEvolution }) {
  const t = window.CUST_T[lang];
  const help = t.help || {};
  const dist = window.CUST.ltvDist;
  const ratio = window.CUST.ltvCac[state] || window.CUST.ltvCac.default;
  const isAlert = state === 'alert';

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

      <div className="cust-2col">
        {/* LTV distribution */}
        <div className="cust-card">
          <div className="cust-card-head">{CustHelpTitle2 ? <CustHelpTitle2 className="cust-card-title" help={help.ltvDist}>{t.ltv.distTitle}</CustHelpTitle2> : <span className="cust-card-title">{t.ltv.distTitle}</span>}</div>
          <CustLtvDist data={dist} mean={620} median={280} t={t} />
          <p className="cust-note">{t.ltv.distNote}</p>
        </div>

        {/* LTV / CAC */}
        <div className="cust-card">
          <div className="cust-card-head">{CustHelpTitle2 ? <CustHelpTitle2 className="cust-card-title" help={help.ltvCac}>{t.ltv.ratioTitle}</CustHelpTitle2> : <span className="cust-card-title">{t.ltv.ratioTitle}</span>}</div>
          <div className="cust-ratio-wrap">
            <div className="cust-ratio-stats">
              <div className="cust-ratio-stat">
                <div className="cust-ratio-lbl">{t.ltv.ratioAvgLtv}</div>
                <div className="cust-ratio-val">€{ratio.ltv}</div>
              </div>
              <div className="cust-ratio-divide">÷</div>
              <div className="cust-ratio-stat">
                <div className="cust-ratio-lbl">{t.ltv.ratioAvgCac}</div>
                <div className="cust-ratio-val">€{ratio.cac}</div>
              </div>
              <div className="cust-ratio-divide">=</div>
              <div className="cust-ratio-stat hero">
                <div className="cust-ratio-lbl">{t.ltv.ratioRatio}</div>
                <div className={`cust-ratio-val big ${ratio.ratio >= 3 ? 'pos' : 'neg'}`}>{ratio.ratio.toFixed(1)}×</div>
              </div>
            </div>
            <div className={`cust-ratio-status ${ratio.ratio >= 3 ? 'pos' : 'neg'} ${ratio.marginal ? 'mid' : ''}`}>
              {ratio.ratio >= 3 ? '✓' : '⚠'} {ratio.ratio >= 3 ? t.ltv.ratioHealthy : t.ltv.ratioUnhealthy}
            </div>
            <p className="cust-ratio-interp">{isAlert ? t.ltv.ratioInterpAlert : t.ltv.ratioInterp}</p>
          </div>
        </div>
      </div>

      {/* Cohort heatmap */}
      <div className="cust-card">
        <div className="cust-card-head">{CustHelpTitle2 ? <CustHelpTitle2 className="cust-card-title" help={help.cohorts}>{t.ltv.cohortTitle}</CustHelpTitle2> : <span className="cust-card-title">{t.ltv.cohortTitle}</span>}</div>
        <CustCohortHeat data={window.CUST.cohorts} cols={window.CUST.cohortCols} onOpen={onOpenCohort} />
        <p className="cust-insight">💡 {isAlert ? t.ltv.cohortInsightAlert : t.ltv.cohortInsight}</p>
      </div>

      {/* LTV evolution */}
      <div className="cust-card">
        <div className="cust-card-head">{CustHelpTitle2 ? <CustHelpTitle2 className="cust-card-title" help={help.ltvEvolution}>{t.ltv.ltvEvoTitle}</CustHelpTitle2> : <span className="cust-card-title">{t.ltv.ltvEvoTitle}</span>}</div>
        {emptyEvolution ? (
          <div className="cust-empty">{t.ltv.ltvEvoEmpty}</div>
        ) : (
          <>
            <CustCohortLtvLines data={window.CUST.cohortLtv} />
            <p className="cust-note">{t.ltv.ltvEvoCaption}</p>
          </>
        )}
      </div>
    </div>
  );
}

function CustLtvDist({ data, mean, median, t }) {
  const w = 580, h = 220, padL = 36, padR = 16, padT = 16, padB = 36;
  const max = Math.max(...data.map(d => d.n));
  const barW = (w - padL - padR) / data.length - 8;
  const meanX = padL + (mean / 2200) * (w - padL - padR);
  const medianX = padL + (median / 2200) * (w - padL - padR);
  return (
    <svg className="cust-svg" viewBox={`0 0 ${w} ${h}`}>
      {[0, .5, 1].map(p => {
        const y = padT + (h - padT - padB) * (1 - p);
        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)">{Math.round(p * max)}</text>
          </g>
        );
      })}
      {data.map((d, i) => {
        const bh = (d.n / max) * (h - padT - padB);
        const x = padL + i * ((w - padL - padR) / data.length) + 4;
        const y = h - padB - bh;
        return (
          <g key={i}>
            <rect x={x} y={y} width={barW} height={bh} fill="#6366F1" opacity="0.85" rx="3" />
            <text x={x + barW/2} y={y - 4} textAnchor="middle" fontSize="11" fill="var(--text-2)" fontWeight="600">{d.n}</text>
            <text x={x + barW/2} y={h - padB + 14} textAnchor="middle" fontSize="10" fill="var(--text-3)">
              {d.lo === 0 ? `<€${d.hi}` : d.hi >= 9999 ? `€${d.lo}+` : `€${d.lo}–${d.hi}`}
            </text>
            <text x={x + barW/2} y={h - padB + 26} textAnchor="middle" fontSize="9" fill="var(--text-3)">{d.pct}%</text>
          </g>
        );
      })}
      {/* Mean and median markers */}
      <line x1={medianX} x2={medianX} y1={padT - 4} y2={h - padB} stroke="#10B981" strokeWidth="2" strokeDasharray="4 3" />
      <text x={medianX} y={padT - 8} textAnchor="middle" fontSize="10" fill="#10B981" fontWeight="600">{t.ltv.medianLbl} €{median}</text>
      <line x1={meanX} x2={meanX} y1={padT - 4} y2={h - padB} stroke="#F59E0B" strokeWidth="2" strokeDasharray="4 3" />
      <text x={meanX} y={padT - 8} textAnchor="middle" fontSize="10" fill="#F59E0B" fontWeight="600">{t.ltv.meanLbl} €{mean}</text>
    </svg>
  );
}

function CustCohortHeat({ data, cols, onOpen }) {
  return (
    <div className="cust-cohort-wrap">
      <table className="cust-cohort">
        <thead>
          <tr>
            <th className="cohort-c">Cohort</th>
            <th className="num size">Size</th>
            {cols.map(c => <th key={c} className="num">{c}</th>)}
          </tr>
        </thead>
        <tbody>
          {data.map((row, i) => (
            <tr key={i} className="clickable" onClick={() => onOpen && onOpen(row.c)}>
              <td className="cohort-c">{row.c}</td>
              <td className="num size">{row.size}</td>
              {row.m.map((v, j) => {
                if (v == null) return <td key={j} className="cohort-cell future">·</td>;
                const intensity = j === 0 ? 1 : Math.min(v / 50, 1);
                const bg = `rgba(99, 102, 241, ${0.08 + intensity * 0.6})`;
                return (
                  <td key={j} className="cohort-cell" style={{ background: bg, color: intensity > 0.5 ? 'white' : 'var(--text)' }}>
                    {v}%
                  </td>
                );
              })}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function CustCohortLtvLines({ data }) {
  const w = 880, h = 240, padL = 44, padR = 16, padT = 20, padB = 32;
  const months = [0, 1, 3, 6, 12, 18, 24, 36];
  const allVals = data.flatMap(d => d.m.filter(v => v != null));
  const yMax = Math.ceil(Math.max(...allVals) / 100) * 100;
  const X = (i) => padL + (i / (months.length - 1)) * (w - padL - padR);
  const Y = (v) => padT + (1 - v / yMax) * (h - padT - padB);
  return (
    <svg className="cust-svg" viewBox={`0 0 ${w} ${h}`}>
      {[0, 0.25, 0.5, 0.75, 1].map(p => {
        const y = padT + (1 - p) * (h - padT - padB);
        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)">€{Math.round(yMax * p)}</text>
          </g>
        );
      })}
      {months.map((m, i) => (
        <text key={i} x={X(i)} y={h - padB + 14} textAnchor="middle" fontSize="10" fill="var(--text-3)">M{m}</text>
      ))}
      {data.map((row, ri) => {
        const pts = row.m.map((v, i) => v == null ? null : `${X(i)},${Y(v)}`).filter(Boolean).join(' ');
        return (
          <g key={ri}>
            <polyline points={pts} fill="none" stroke={row.color} strokeWidth="2" strokeLinejoin="round" />
            {row.m.map((v, i) => v != null && <circle key={i} cx={X(i)} cy={Y(v)} r="3" fill={row.color} />)}
          </g>
        );
      })}
      {/* Legend */}
      <g transform={`translate(${padL + 12}, ${padT + 8})`}>
        {data.map((row, ri) => (
          <g key={ri} transform={`translate(${ri * 92}, 0)`}>
            <line x1="0" y1="0" x2="14" y2="0" stroke={row.color} strokeWidth="2" />
            <text x="18" y="3" fontSize="10" fill="var(--text-2)">{row.c}</text>
          </g>
        ))}
      </g>
    </svg>
  );
}

/* ============ SECTION 4 — Acquisition & Retention ============ */
function CustAcqRetention({ state, lang, onOpenSource, onOpenAtRisk }) {
  const t = window.CUST_T[lang];
  const help = t.help || {};
  const isAlert = state === 'alert';

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

      <div className="cust-2col-wide">
        {/* New vs Returning area */}
        <div className="cust-card">
          <div className="cust-card-head">{CustHelpTitle2 ? <CustHelpTitle2 className="cust-card-title" help={help.acqFlow}>{t.acq.flowTitle}</CustHelpTitle2> : <span className="cust-card-title">{t.acq.flowTitle}</span>}</div>
          <p className="cust-insight">💡 {isAlert ? t.acq.flowInsightAlert : t.acq.flowInsight}</p>
          <CustAcqArea data={window.CUST.acqFlow} t={t} />
          <div className="cust-legend-row">
            <span className="cust-legend-item"><span className="cust-dot" style={{ background: '#A5B4FC' }} /> {t.acq.flowNew}</span>
            <span className="cust-legend-item"><span className="cust-dot" style={{ background: '#4F46E5' }} /> {t.acq.flowReturn}</span>
          </div>
        </div>

        {/* Repeat timing histogram */}
        <div className="cust-card">
          <div className="cust-card-head">{CustHelpTitle2 ? <CustHelpTitle2 className="cust-card-title" help={help.repeatTiming}>{t.acq.timingTitle}</CustHelpTitle2> : <span className="cust-card-title">{t.acq.timingTitle}</span>}</div>
          <CustRepeatTiming data={window.CUST.repeatTiming} />
          <p className="cust-note">
            {t.acq.timingCaption} <strong>{window.CUST.repeatTiming.find(d => d.peak).lbl}</strong> {t.acq.timingCaption2}
          </p>
        </div>
      </div>

      {/* Acquisition source quality */}
      <div className="cust-card">
        <div className="cust-card-head">{CustHelpTitle2 ? <CustHelpTitle2 className="cust-card-title" help={help.sourceQuality}>{t.acq.sourceTitle}</CustHelpTitle2> : <span className="cust-card-title">{t.acq.sourceTitle}</span>}</div>
        <table className="cust-table">
          <thead>
            <tr>
              <th>{t.acq.sourceCols.src}</th>
              <th className="num">{t.acq.sourceCols.n}</th>
              <th className="num">{t.acq.sourceCols.ltv}</th>
              <th className="num">{t.acq.sourceCols.rep}</th>
              <th className="num">{t.acq.sourceCols.cross}</th>
            </tr>
          </thead>
          <tbody>
            {window.CUST.acqSources.map(s => (
              <tr key={s.src} className={`clickable ${s.hot ? 'hot' : ''}`} onClick={() => onOpenSource && onOpenSource(s.src)}>
                <td>
                  {s.src} {s.hot && <span className="cust-badge pos">★</span>}
                </td>
                <td className="num">{s.n}</td>
                <td className="num"><strong>€{s.ltv}</strong></td>
                <td className="num">{s.repeat}%</td>
                <td className="num">{s.cross}%</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Churn signal */}
      <div className="cust-card cust-churn">
        <div className="cust-card-head">{CustHelpTitle2 ? <CustHelpTitle2 className="cust-card-title" help={help.churnSignals}>{t.acq.churnTitle}</CustHelpTitle2> : <span className="cust-card-title">{t.acq.churnTitle}</span>}</div>
        <div className="cust-churn-row">
          {window.CUST.churn.map((c, i) => (
            <button key={i} type="button" className={`cust-churn-stat clickable ${c.kind === 'highVal' ? 'highlight' : ''}`}
              onClick={() => onOpenAtRisk && onOpenAtRisk(c.kind)}>
              <span className="cust-churn-num">{c.n}</span>
              <span className="cust-churn-lbl">{t.acq[c.keyTok]}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function CustAcqArea({ data, t }) {
  const w = 580, h = 200, padL = 36, padR = 16, padT = 16, padB = 28;
  const tot = (d) => d.n + d.r;
  const max = Math.max(...data.map(tot));
  const X = (i) => padL + (i / (data.length - 1)) * (w - padL - padR);
  const Y = (v) => padT + (1 - v / max) * (h - padT - padB);
  // returning bottom layer
  const rTop = data.map((d, i) => `${X(i)},${Y(d.r)}`).join(' ');
  const rBot = `${X(data.length - 1)},${h - padB} ${X(0)},${h - padB}`;
  // new on top of returning
  const nTop = data.map((d, i) => `${X(i)},${Y(d.r + d.n)}`).join(' ');
  const nBot = data.slice().reverse().map((d, i) => {
    const idx = data.length - 1 - i;
    return `${X(idx)},${Y(data[idx].r)}`;
  }).join(' ');
  return (
    <svg className="cust-svg" viewBox={`0 0 ${w} ${h}`}>
      {[0, 0.5, 1].map(p => {
        const y = padT + (1 - p) * (h - padT - padB);
        return <line key={p} x1={padL} x2={w - padR} y1={y} y2={y} stroke="var(--border)" strokeDasharray="2 4" />;
      })}
      <polygon points={`${rTop} ${rBot}`} fill="#4F46E5" opacity="0.85" />
      <polygon points={`${nTop} ${nBot}`} fill="#A5B4FC" opacity="0.85" />
      {data.map((d, i) => (
        <text key={i} x={X(i)} y={h - padB + 14} textAnchor="middle" fontSize="10" fill="var(--text-3)">{d.m}</text>
      ))}
    </svg>
  );
}

function CustRepeatTiming({ data }) {
  const w = 480, h = 200, padL = 28, padR = 16, padT = 14, padB = 36;
  const max = Math.max(...data.map(d => d.n));
  const barW = (w - padL - padR) / data.length - 6;
  return (
    <svg className="cust-svg" viewBox={`0 0 ${w} ${h}`}>
      {data.map((d, i) => {
        const bh = (d.n / max) * (h - padT - padB);
        const x = padL + i * ((w - padL - padR) / data.length) + 3;
        const y = h - padB - bh;
        return (
          <g key={i}>
            <rect x={x} y={y} width={barW} height={bh} fill={d.peak ? '#10B981' : '#94A3B8'} opacity={d.peak ? 1 : 0.5} rx="3" />
            <text x={x + barW/2} y={y - 4} textAnchor="middle" fontSize="11" fill="var(--text-2)" fontWeight={d.peak ? 600 : 500}>{d.n}</text>
            <text x={x + barW/2} y={h - padB + 14} textAnchor="middle" fontSize="10" fill="var(--text-3)">{d.lbl}</text>
          </g>
        );
      })}
    </svg>
  );
}

window.CustLtvCohorts = CustLtvCohorts;
window.CustAcqRetention = CustAcqRetention;
