// mkt-metric-drawer.jsx — Reusable drawer for snapshot metric drill-down

const CH_META_M = {
  google:  { name: 'Google',  color: '#4285F4' },
  meta:    { name: 'Meta',    color: '#1877F2' },
  tiktok:  { name: 'TikTok',  color: '#111111' },
  organic: { name: 'Organic', color: '#16A34A' },
  direct:  { name: 'Direct',  color: '#64748B' },
};

function MChDot({ ch }) {
  const m = CH_META_M[ch] || { name: ch, color: '#888' };
  return <span className="md-chdot"><span className="md-chdot-bullet" style={{ background: m.color }}></span>{m.name}</span>;
}

function fmtNum(v, fmt) {
  if (typeof fmt === 'function') return fmt(v);
  if (v >= 1000) return v.toLocaleString();
  return String(v);
}

/* Stacked bar timeline */
function StackedTimeline({ bins, series, unit }) {
  const w = 432, h = 130, pad = { l: 28, r: 12, t: 14, b: 22 };
  const innerW = w - pad.l - pad.r;
  const innerH = h - pad.t - pad.b;
  const totals = bins.map((_, i) => series.reduce((s, srs) => s + srs.vals[i], 0));
  const maxT = Math.max(...totals) * 1.1;
  const colW = (innerW / bins.length) * 0.7;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} className="md-chart">
      {[0.5, 1].map((p, i) => (
        <line key={i} x1={pad.l} x2={w - pad.r} y1={pad.t + (1 - p) * innerH} y2={pad.t + (1 - p) * innerH} stroke="var(--border)" strokeDasharray="2 3" />
      ))}
      {bins.map((b, i) => {
        const x = pad.l + (i + 0.5) * (innerW / bins.length);
        let yCursor = pad.t + innerH;
        return (
          <g key={i}>
            {series.map((srs, j) => {
              const v = srs.vals[i];
              const barH = (v / maxT) * innerH;
              yCursor -= barH;
              return <rect key={j} x={x - colW / 2} y={yCursor} width={colW} height={barH} fill={CH_META_M[srs.ch].color} opacity="0.85" />;
            })}
            <text x={x} y={h - pad.b + 12} fontSize="10" textAnchor="middle" fill="var(--text-3)">{b}</text>
          </g>
        );
      })}
      <text x={pad.l - 4} y={pad.t + 4} fontSize="9" textAnchor="end" fill="var(--text-3)">{unit ? `${Math.round(maxT)}${unit}` : Math.round(maxT)}</text>
    </svg>
  );
}

/* Line timeline (for CPC, CR — non-stackable) */
function LineTimeline({ bins, series, unit }) {
  const w = 432, h = 130, pad = { l: 32, r: 12, t: 14, b: 22 };
  const innerW = w - pad.l - pad.r;
  const innerH = h - pad.t - pad.b;
  const allVals = series.flatMap(s => s.vals);
  const max = Math.max(...allVals) * 1.15;
  const min = Math.min(...allVals) * 0.85;
  const x = (i) => pad.l + (i / (bins.length - 1)) * innerW;
  const y = (v) => pad.t + (1 - (v - min) / (max - min)) * innerH;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} className="md-chart">
      {[0.5, 1].map((p, i) => (
        <line key={i} x1={pad.l} x2={w - pad.r} y1={pad.t + (1 - p) * innerH} y2={pad.t + (1 - p) * innerH} stroke="var(--border)" strokeDasharray="2 3" />
      ))}
      {series.map((s, i) => {
        const path = s.vals.map((v, j) => `${j === 0 ? 'M' : 'L'}${x(j).toFixed(1)},${y(v).toFixed(1)}`).join(' ');
        return <path key={i} d={path} fill="none" stroke={CH_META_M[s.ch].color} strokeWidth="2" />;
      })}
      {bins.map((b, i) => (
        <text key={i} x={x(i)} y={h - pad.b + 12} fontSize="10" textAnchor="middle" fill="var(--text-3)">{b}</text>
      ))}
      <text x={pad.l - 4} y={pad.t + 4} fontSize="9" textAnchor="end" fill="var(--text-3)">{unit === '€' ? `€${max.toFixed(2)}` : unit === '%' ? `${max.toFixed(1)}%` : max.toFixed(2)}</text>
      <text x={pad.l - 4} y={pad.t + innerH} fontSize="9" textAnchor="end" fill="var(--text-3)">{unit === '€' ? `€${min.toFixed(2)}` : unit === '%' ? `${min.toFixed(1)}%` : min.toFixed(2)}</text>
    </svg>
  );
}

/* Channel breakdown rows */
function ChBreakdown({ rows, format }) {
  const max = Math.max(...rows.map(r => r.value));
  return (
    <div className="md-chbreakdown">
      {rows.map((r, i) => (
        <div key={i} className="md-chbreak-row">
          <div className="md-chbreak-lbl"><MChDot ch={r.ch} /></div>
          <div className="md-chbreak-bar-wrap">
            <div className="md-chbreak-bar" style={{ width: `${(r.value / max) * 100}%`, background: CH_META_M[r.ch].color }}></div>
          </div>
          <div className="md-chbreak-val">{fmtNum(r.value, format)}</div>
          {r.share != null && <div className="md-chbreak-share">{r.share}%</div>}
          <div className={`md-chbreak-delta ${r.sign}`}>{r.delta}</div>
        </div>
      ))}
    </div>
  );
}

function MetricDrawer({ d, onClose }) {
  return (
    <div className="md-drawer">
      <div className="md-head">
        <div className="md-head-main">
          <div className="md-head-title">{d.header}</div>
          <div className="md-head-path">{d.path.join(' › ')}</div>
          <div className="md-head-period">{d.period}</div>
        </div>
        <button className="md-close" onClick={onClose}>×</button>
      </div>

      <div className="md-body">
        {/* Hero KPI */}
        <div className="md-kpi-hero">
          <div className="md-kpi-val">{d.kpi.value}</div>
          <div className="md-kpi-meta">
            <span className={`md-kpi-delta ${d.kpi.sign}`}>{d.kpi.delta}</span>
            {d.kpi.sub && <span className="md-kpi-sub">{d.kpi.sub}</span>}
          </div>
        </div>

        {/* Stats row */}
        <div className="md-stats">
          {d.stats.map((s, i) => (
            <div key={i} className="md-stat">
              <div className="md-stat-lbl">{s.label}</div>
              <div className="md-stat-val">{s.value}</div>
              <div className="md-stat-meta">
                <span className={`md-stat-delta ${s.sign}`}>{s.delta}</span>
                {s.sub && <span className="md-stat-sub">{s.sub}</span>}
              </div>
            </div>
          ))}
        </div>

        {/* Insight */}
        {d.insight && (
          <>
            <div className="md-section-h">{d.insightTitle}</div>
            <div className="md-insight"><span>↳</span>{d.insight}</div>
          </>
        )}

        {/* Channel breakdown */}
        {d.breakdown && (
          <>
            <div className="md-section-h">{d.breakdown.title}</div>
            <div className="md-card">
              <ChBreakdown rows={d.breakdown.rows} format={d.breakdown.format} />
            </div>
          </>
        )}

        {/* Timeline */}
        {d.timeline && (
          <>
            <div className="md-section-h">{d.timeline.title}</div>
            <div className="md-card">
              {d.timeline.unit === '€' || d.timeline.unit === '%' ? (
                <LineTimeline {...d.timeline} />
              ) : (
                <StackedTimeline {...d.timeline} />
              )}
              <div className="md-legend">
                {d.timeline.series.map((s, i) => (
                  <span key={i} className="md-legend-item">
                    <span className="md-legend-dot" style={{ background: CH_META_M[s.ch].color }}></span>
                    {CH_META_M[s.ch].name}
                  </span>
                ))}
              </div>
            </div>
          </>
        )}

        {/* CTR by channel (clicks drawer) */}
        {d.ctrChannel && (
          <>
            <div className="md-section-h">{d.ctrChannel.title}</div>
            <div className="md-card md-tbl-card">
              <table className="md-tbl">
                <thead><tr><th>Channel</th><th className="r">CTR</th><th className="r">Δ</th></tr></thead>
                <tbody>
                  {d.ctrChannel.rows.map((r, i) => (
                    <tr key={i}>
                      <td><MChDot ch={r.ch} /></td>
                      <td className="r"><strong>{r.ctr}</strong></td>
                      <td className={`r md-delta ${r.sign}`}>{r.delta}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}

        {/* Bounce / traffic quality (clicks) */}
        {d.bounce && (
          <>
            <div className="md-section-h">{d.bounce.title}</div>
            <div className="md-card md-tbl-card">
              <table className="md-tbl">
                <thead><tr><th>Channel</th><th className="r">Bounce</th><th className="r">Avg session</th></tr></thead>
                <tbody>
                  {d.bounce.rows.map((r, i) => (
                    <tr key={i}>
                      <td><MChDot ch={r.ch} /></td>
                      <td className={`r md-bench-cell ${r.tone}`}>{r.bounce}</td>
                      <td className="r">{r.avg}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}

        {/* Placement (impr) */}
        {d.placement && (
          <>
            <div className="md-section-h">{d.placement.title}</div>
            <div className="md-card">
              {d.placement.rows.map((r, i) => (
                <div key={i} className="md-place-row">
                  <span className="md-place-lbl">{r.lbl}</span>
                  <div className="md-place-bar-wrap"><div className="md-place-bar" style={{ width: r.pct + '%' }}></div></div>
                  <span className="md-place-val">{r.pct}%</span>
                </div>
              ))}
            </div>
          </>
        )}

        {/* Frequency (impr) */}
        {d.freq && (
          <>
            <div className="md-section-h">{d.freq.title}</div>
            <div className="md-card md-tbl-card">
              <table className="md-tbl">
                <thead><tr><th>Channel</th><th className="r">Freq</th><th>Status</th></tr></thead>
                <tbody>
                  {d.freq.rows.map((r, i) => (
                    <tr key={i}>
                      <td><MChDot ch={r.ch} /></td>
                      <td className={`r md-bench-cell ${r.status === 'warn' ? 'warn' : 'good'}`}><strong>{r.freq}</strong></td>
                      <td className="md-stat-sub">{r.note}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}

        {/* Pacing (spend) */}
        {d.pacing && (
          <>
            <div className="md-section-h">{d.pacing.title}</div>
            <div className="md-card md-pacing">
              <div className="md-pacing-bar-wrap">
                <div className="md-pacing-bar" style={{ width: `${(d.pacing.spent / d.pacing.budget) * 100}%` }}></div>
                <div className="md-pacing-marker" style={{ left: `${((d.pacing.budget - 0) / d.pacing.budget) * 100}%` }}>
                  <div className="md-pacing-marker-line"></div>
                  <div className="md-pacing-marker-lbl">€{d.pacing.budget.toLocaleString()}</div>
                </div>
              </div>
              <div className="md-pacing-stats">
                <div className="md-pacing-stat"><div className="md-pacing-stat-lbl">Spent</div><div className="md-pacing-stat-val">€{d.pacing.spent.toLocaleString()}</div></div>
                <div className="md-pacing-stat"><div className="md-pacing-stat-lbl">Forecast EoM</div><div className="md-pacing-stat-val neg">€{d.pacing.forecastEoM.toLocaleString()} <span>{d.pacing.overBy}</span></div></div>
                <div className="md-pacing-stat"><div className="md-pacing-stat-lbl">Days left</div><div className="md-pacing-stat-val">{d.pacing.daysLeft}</div></div>
              </div>
            </div>
          </>
        )}

        {/* Conversions by type (conv) */}
        {d.breakdown2 && (
          <>
            <div className="md-section-h">{d.breakdown2.title}</div>
            <div className="md-card">
              {d.breakdown2.rows.map((r, i) => {
                const max = Math.max(...d.breakdown2.rows.map(x => x.value));
                return (
                  <div key={i} className="md-place-row">
                    <span className="md-place-lbl" style={{ minWidth: 140 }}>{r.lbl}</span>
                    <div className="md-place-bar-wrap"><div className="md-place-bar" style={{ width: `${(r.value / max) * 100}%` }}></div></div>
                    <span className="md-place-val">{r.value} · {r.share}%</span>
                  </div>
                );
              })}
            </div>
          </>
        )}

        {/* Funnel (cr) */}
        {d.funnel && d.funnel.rows && (
          <>
            <div className="md-section-h">{d.funnel.title}</div>
            <div className="md-card md-tbl-card">
              <table className="md-tbl">
                <thead><tr><th>Stage</th><th className="r">CR</th><th className="r">Drop</th></tr></thead>
                <tbody>
                  {d.funnel.rows.map((r, i) => (
                    <tr key={i}>
                      <td>{r.stage}</td>
                      <td className="r"><strong>{r.rate}</strong></td>
                      <td className="r md-stat-sub">{r.drop}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}

        {/* Top campaigns */}
        {d.campaigns && (
          <>
            <div className="md-section-h">{d.campaigns.title}</div>
            <div className="md-card md-tbl-card">
              <table className="md-tbl">
                <thead>
                  <tr>
                    <th>Campaign</th>
                    <th>Channel</th>
                    {d.campaigns.rows[0].spend && <th className="r">Spend</th>}
                    {d.campaigns.rows[0].conv != null && <th className="r">Conv</th>}
                    {d.campaigns.rows[0].cpc && <th className="r">CPC</th>}
                    {d.campaigns.rows[0].cac && <th className="r">CAC</th>}
                    {d.campaigns.rows[0].roas && <th className="r">ROAS</th>}
                    {d.campaigns.rows[0].ctr && <th className="r">CTR</th>}
                  </tr>
                </thead>
                <tbody>
                  {d.campaigns.rows.map((r, i) => (
                    <tr key={i}>
                      <td>{r.name}</td>
                      <td><MChDot ch={r.ch} /></td>
                      {r.spend && <td className="r">{r.spend}</td>}
                      {r.conv != null && <td className="r"><strong>{r.conv}</strong></td>}
                      {r.cpc && <td className="r">{r.cpc}</td>}
                      {r.cac && <td className="r">{r.cac}</td>}
                      {r.roas && <td className="r">{r.roas}</td>}
                      {r.ctr && <td className="r">{r.ctr}</td>}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}

        {/* Benchmarks (cpc, cr) */}
        {d.bench && (
          <>
            <div className="md-section-h">{d.bench.title}</div>
            <div className="md-card md-tbl-card">
              <table className="md-tbl md-bench-tbl">
                <thead>
                  <tr>
                    <th></th>
                    {(d.bench.rows[0].cols || ['Вы', 'Бенчмарк']).map((c, i) => <th key={i} className={`r ${i === 0 ? 'self' : ''}`}>{c}</th>)}
                  </tr>
                </thead>
                <tbody>
                  {d.bench.rows.map((r, i) => (
                    <tr key={i}>
                      <td>{r.metric}</td>
                      {r.vals.map((v, j) => <td key={j} className={`r md-bench-cell ${r.tone[j] || ''} ${j === 0 ? 'self' : ''}`}>{v}</td>)}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}

        {/* Recommendation */}
        {d.reco && (
          <div className="md-reco">
            <div className="md-reco-h">💡 {d.reco.title}</div>
            <div className="md-reco-body">{d.reco.body}</div>
          </div>
        )}
      </div>

      <div className="md-actions">
        {d.actions.primary && (
          <button className="md-btn primary">
            {d.actions.primary.label}
            <span className="md-ext">↗</span>
          </button>
        )}
        {d.actions.export && (
          <button className="md-btn ghost">{d.actions.export}</button>
        )}
      </div>
    </div>
  );
}

function MktMetricDrawerHost({ openKey, onClose, lang }) {
  if (!openKey) return null;
  const data = (window.MKT_METRIC_DRAWERS[lang] || window.MKT_METRIC_DRAWERS.ru)[openKey];
  if (!data) return null;
  return (
    <>
      <div className="md-overlay" onClick={onClose}></div>
      <MetricDrawer d={data} onClose={onClose} />
    </>
  );
}

window.MktMetricDrawerHost = MktMetricDrawerHost;
