// Simple Power-BI style widgets for WXG simplified dashboard.
// Same brand palette as v1 but cleaner, more data-direct shapes.

const D2W = {
  // Page background — very light warm grey, like the PDF
  page:    '#F4F2EF',
  card:    '#FFFFFF',
  ink:     '#1F1F1F',
  inkSoft: '#3F3F3F',
  grey:    '#6B6B6B',
  greyMid: '#8A8A8A',
  greyLight:'#BDBDBD',
  rule:    '#E2DFD9',
  ruleSoft:'#EEEBE5',

  amber:   '#FCAF17',
  amberDark:'#E89E0F',
  amberSoft:'rgba(252,175,23,0.14)',

  // Power-BI-ish but pulled from WXG secondary palette
  green:   '#61CAA0',   // promoters
  greenSoft:'#B0E5D0',
  gold:    '#CABE61',   // passives
  goldSoft:'#E5DEB0',
  wine:    '#B0303B',   // detractors
  wineSoft:'#E5B2B0',
  blue:    '#5A8FBF',
  grey2:   '#C4BFB6',
};

const D2W_FONT = "'Calibri', 'Carlito', 'Segoe UI', 'Helvetica Neue', Helvetica, Arial, sans-serif";
const D2W_MONO = "'JetBrains Mono', 'Geist Mono', ui-monospace, monospace";

// Color name → hex
const D2W_COLOR = {
  amber: D2W.amber, green: D2W.green, gold: D2W.gold, wine: D2W.wine,
  grey: D2W.grey2, blue: D2W.blue,
};

// ─────────────────────────────────────────────────────────────
// Card — flat white with a thin top accent rule, no shadow.
// Power-BI style. Title sits inside, padded.
// ─────────────────────────────────────────────────────────────
function D2Card({ title, action, children, pad = 16, style = {} }) {
  return (
    <div style={{
      background: D2W.card, padding: pad,
      border: `1px solid ${D2W.rule}`,
      display: 'flex', flexDirection: 'column', minHeight: 0,
      ...style,
    }}>
      {(title || action) && (
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 10, marginBottom: 10,
        }}>
          {title && <div style={{
            fontFamily: D2W_FONT, fontWeight: 700, fontSize: 13,
            color: D2W.ink, letterSpacing: 0.1,
          }}>{title}</div>}
          {action}
        </div>
      )}
      <div style={{ flex: 1, minHeight: 0 }}>{children}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Big counter — flat card, huge number, small caption underneath
// Matches the reference's "סקרים 90" / "אנשי קשר 75" blocks.
// ─────────────────────────────────────────────────────────────
function CounterCard({ label, value, suffix, accent = D2W.amber, align = 'center' }) {
  return (
    <div style={{
      background: D2W.card, border: `1px solid ${D2W.rule}`,
      padding: '14px 16px', display: 'flex', flexDirection: 'column',
      gap: 6, alignItems: align === 'center' ? 'center' : 'flex-start',
      justifyContent: 'center', minHeight: 92,
    }}>
      <div style={{
        fontFamily: D2W_FONT, fontWeight: 700, fontSize: 12,
        color: D2W.inkSoft, letterSpacing: 0.2,
        textAlign: align === 'center' ? 'center' : 'right',
      }}>{label}</div>
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 4,
        fontFamily: D2W_FONT, fontWeight: 300, lineHeight: 1,
        color: D2W.ink, letterSpacing: '-0.01em',
      }}>
        <span style={{ fontSize: 38 }}>{value}</span>
        {suffix && <span style={{ fontSize: 16, color: D2W.greyMid }}>{suffix}</span>}
      </div>
      <div style={{
        width: 28, height: 2, background: accent, marginTop: 2,
      }} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Donut chart — slices with center label, legend on right
// ─────────────────────────────────────────────────────────────
function DonutChart({ data, size = 160, centerLabel, centerValue, showLegend = true }) {
  const total = data.reduce((s, d) => s + d.v, 0);
  const r = size / 2, ir = r * 0.62;
  const cx = r, cy = r;
  let acc = 0;
  const arcs = data.map((d, i) => {
    const start = acc / total * Math.PI * 2 - Math.PI / 2;
    acc += d.v;
    const end = acc / total * Math.PI * 2 - Math.PI / 2;
    const large = end - start > Math.PI ? 1 : 0;
    const x1 = cx + Math.cos(start) * r, y1 = cy + Math.sin(start) * r;
    const x2 = cx + Math.cos(end)   * r, y2 = cy + Math.sin(end)   * r;
    const x3 = cx + Math.cos(end)   * ir,y3 = cy + Math.sin(end)   * ir;
    const x4 = cx + Math.cos(start) * ir,y4 = cy + Math.sin(start) * ir;
    // Label position
    const mid = (start + end) / 2;
    const lr = (r + ir) / 2;
    const lx = cx + Math.cos(mid) * lr, ly = cy + Math.sin(mid) * lr;
    return {
      d: `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} L ${x3} ${y3} A ${ir} ${ir} 0 ${large} 0 ${x4} ${y4} Z`,
      color: D2W_COLOR[d.c] || d.c || D2W.amber,
      label: `${d.v}%`,
      lx, ly,
      raw: d,
    };
  });

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: showLegend ? 18 : 0,
      flex: 1, minHeight: 0,
    }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ flexShrink: 0 }}>
        {arcs.map((a, i) => (
          <g key={i}>
            <path d={a.d} fill={a.color} />
            <text x={a.lx} y={a.ly} textAnchor="middle" dominantBaseline="middle"
              fontFamily={D2W_FONT} fontWeight="700" fontSize="11"
              fill={D2W.ink}>{a.label}</text>
          </g>
        ))}
        {(centerLabel || centerValue) && (
          <>
            <text x={cx} y={cy - 5} textAnchor="middle" dominantBaseline="middle"
              fontFamily={D2W_FONT} fontWeight="300" fontSize={size * 0.18}
              fill={D2W.ink}>{centerValue}</text>
            <text x={cx} y={cy + 13} textAnchor="middle" dominantBaseline="middle"
              fontFamily={D2W_MONO} fontSize="9" letterSpacing="1"
              fill={D2W.greyMid}>{centerLabel}</text>
          </>
        )}
      </svg>
      {showLegend && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
          {arcs.map((a, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 8,
              fontFamily: D2W_FONT, fontSize: 12, color: D2W.inkSoft,
            }}>
              <span style={{
                width: 10, height: 10, background: a.color, flexShrink: 0,
              }} />
              <span style={{ whiteSpace: 'nowrap' }}>{a.raw.k}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Bar chart — vertical bars with value labels on top
// Used for per-question NPS distributions (scores 6-10).
// ─────────────────────────────────────────────────────────────
function BarChart({ data, height = 130, color = D2W.amber, maxOverride }) {
  const max = maxOverride || Math.max(...data.map(d => d.v), 1);
  const padL = 28, padR = 8, padT = 18, padB = 24;
  const W = 320;
  const innerW = W - padL - padR;
  const innerH = height - padT - padB;
  const barGap = 8;
  const barW = (innerW - barGap * (data.length - 1)) / data.length;

  return (
    <svg width="100%" viewBox={`0 0 ${W} ${height}`} preserveAspectRatio="xMidYMid meet"
      style={{ display: 'block' }}>
      {/* Y axis baseline */}
      <line x1={padL} y1={padT + innerH} x2={W - padR} y2={padT + innerH}
        stroke={D2W.rule} strokeWidth="1" />
      {/* Y-axis simple ticks */}
      {[0, 0.5, 1].map((p, i) => {
        const y = padT + innerH - p * innerH;
        const v = Math.round(max * p);
        return (
          <g key={i}>
            <line x1={padL - 4} y1={y} x2={padL} y2={y} stroke={D2W.greyLight} />
            <text x={padL - 6} y={y + 3} textAnchor="end"
              fontFamily={D2W_MONO} fontSize="9" fill={D2W.greyMid}>{v}</text>
          </g>
        );
      })}
      {data.map((d, i) => {
        const x = padL + i * (barW + barGap);
        const h = (d.v / max) * innerH;
        const y = padT + innerH - h;
        return (
          <g key={i}>
            <rect x={x} y={y} width={barW} height={h} fill={color} />
            {d.v > 0 && (
              <text x={x + barW / 2} y={y - 4} textAnchor="middle"
                fontFamily={D2W_FONT} fontWeight="700" fontSize="11"
                fill={D2W.ink}>{d.v}</text>
            )}
            <text x={x + barW / 2} y={padT + innerH + 14}
              textAnchor="middle" fontFamily={D2W_FONT} fontWeight="400" fontSize="11"
              fill={D2W.inkSoft}>{d.x}</text>
          </g>
        );
      })}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Grouped bar — methods × statuses (Page 2)
// ─────────────────────────────────────────────────────────────
function GroupedBarChart({ data, height = 200 }) {
  // data: { status, digital, manual }
  const W = 560, padL = 36, padR = 16, padT = 24, padB = 36;
  const innerW = W - padL - padR;
  const innerH = height - padT - padB;
  const groupGap = 20;
  const groupW = (innerW - groupGap * (data.length - 1)) / data.length;
  const barW = (groupW - 4) / 2;
  const max = Math.max(...data.flatMap(d => [d.digital, d.manual]));
  const niceMax = Math.ceil(max / 25) * 25;

  return (
    <svg width="100%" viewBox={`0 0 ${W} ${height}`} preserveAspectRatio="xMidYMid meet"
      style={{ display: 'block' }}>
      {/* Y gridlines */}
      {[0, 25, 50, 75, 100].filter(v => v <= niceMax).map(v => {
        const y = padT + innerH - (v / niceMax) * innerH;
        return (
          <g key={v}>
            <line x1={padL} y1={y} x2={W - padR} y2={y}
              stroke={D2W.rule} strokeWidth="0.5" strokeDasharray={v === 0 ? '0' : '2 3'} />
            <text x={padL - 6} y={y + 3} textAnchor="end"
              fontFamily={D2W_MONO} fontSize="9" fill={D2W.greyMid}>{v}</text>
          </g>
        );
      })}
      {data.map((d, i) => {
        const x = padL + i * (groupW + groupGap);
        const hD = (d.digital / niceMax) * innerH;
        const hM = (d.manual  / niceMax) * innerH;
        return (
          <g key={d.status}>
            <rect x={x} y={padT + innerH - hD} width={barW} height={hD} fill={D2W.amber} />
            <text x={x + barW / 2} y={padT + innerH - hD - 4}
              textAnchor="middle" fontFamily={D2W_FONT} fontWeight="700" fontSize="11"
              fill={D2W.ink}>{d.digital}</text>
            <rect x={x + barW + 4} y={padT + innerH - hM} width={barW} height={hM} fill={D2W.grey2} />
            <text x={x + barW + 4 + barW / 2} y={padT + innerH - hM - 4}
              textAnchor="middle" fontFamily={D2W_FONT} fontWeight="700" fontSize="11"
              fill={D2W.ink}>{d.manual}</text>
            <text x={x + groupW / 2} y={padT + innerH + 16}
              textAnchor="middle" fontFamily={D2W_FONT} fontSize="11"
              fill={D2W.inkSoft}>{d.status}</text>
          </g>
        );
      })}
      {/* Legend at the top */}
      <g transform={`translate(${padL}, 8)`}>
        <rect x="0" y="0" width="10" height="10" fill={D2W.amber} />
        <text x="14" y="9" fontFamily={D2W_FONT} fontSize="11" fill={D2W.inkSoft}>Digital</text>
        <rect x="80" y="0" width="10" height="10" fill={D2W.grey2} />
        <text x="94" y="9" fontFamily={D2W_FONT} fontSize="11" fill={D2W.inkSoft}>Manual</text>
      </g>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Multi-line trend chart (Page 1)
// ─────────────────────────────────────────────────────────────
function MultiLineChart({ months, series, height = 220 }) {
  const W = 560, padL = 36, padR = 16, padT = 16, padB = 30;
  const innerW = W - padL - padR;
  const innerH = height - padT - padB;
  const min = -100, max = 100;
  const xs = months.map((_, i) =>
    months.length === 1 ? padL + innerW / 2 :
    padL + (i / (months.length - 1)) * innerW);
  const yOf = v => padT + (1 - (v - min) / (max - min)) * innerH;
  const yGrid = [-100, -50, 0, 50, 100];

  return (
    <svg width="100%" viewBox={`0 0 ${W} ${height}`} preserveAspectRatio="xMidYMid meet"
      style={{ display: 'block', overflow: 'visible' }}>
      {yGrid.map(v => (
        <g key={v}>
          <line x1={padL} y1={yOf(v)} x2={W - padR} y2={yOf(v)}
            stroke={v === 0 ? D2W.greyLight : D2W.rule}
            strokeWidth={v === 0 ? 0.8 : 0.5}
            strokeDasharray={v === 0 ? '0' : '2 3'} />
          <text x={padL - 6} y={yOf(v) + 3} textAnchor="end"
            fontFamily={D2W_MONO} fontSize="9" fill={D2W.greyMid}>{v}</text>
        </g>
      ))}
      {series.map((s, si) => {
        const color = D2W_COLOR[s.c] || s.c || D2W.amber;
        const path = s.v.reduce((acc, v, i) =>
          acc + (i === 0 ? `M ${xs[i]} ${yOf(v)}` : ` L ${xs[i]} ${yOf(v)}`), '');
        return (
          <g key={si}>
            <path d={path} fill="none" stroke={color} strokeWidth="2" />
            {s.v.map((v, i) => (
              <circle key={i} cx={xs[i]} cy={yOf(v)} r="3"
                fill={D2W.card} stroke={color} strokeWidth="1.5" />
            ))}
          </g>
        );
      })}
      {months.map((m, i) => (
        <text key={i} x={xs[i]} y={height - 8} textAnchor="middle"
          fontFamily={D2W_MONO} fontSize="9" fill={D2W.greyMid}>{m}</text>
      ))}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Funnel — Power-BI style vertical funnel
// ─────────────────────────────────────────────────────────────
function FunnelChart({ data, height = 220 }) {
  const max = Math.max(...data.map(d => d.v));
  const W = 360, padX = 16;
  const rowH = (height - 16) / data.length;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${height}`} preserveAspectRatio="xMidYMid meet">
      {data.map((d, i) => {
        const pct = d.v / max;
        const w = pct * (W - padX * 2);
        const x = (W - w) / 2;
        const y = 8 + i * rowH;
        const color = D2W_COLOR[d.c] || D2W.amber;
        return (
          <g key={d.k}>
            <rect x={x} y={y + 4} width={w} height={rowH - 10}
              fill={color} />
            <text x={W / 2} y={y + rowH / 2}
              textAnchor="middle" dominantBaseline="middle"
              fontFamily={D2W_FONT} fontWeight="700" fontSize="14"
              fill="#fff">{d.v}</text>
            <text x={x - 8} y={y + rowH / 2}
              textAnchor="end" dominantBaseline="middle"
              fontFamily={D2W_FONT} fontSize="12" fill={D2W.inkSoft}>{d.k}</text>
          </g>
        );
      })}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Filter dropdown chip — same as the reference's filter row
// ─────────────────────────────────────────────────────────────
function FilterChip({ label, value }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: '7px 12px', background: D2W.card, border: `1px solid ${D2W.rule}`,
      minWidth: 160, justifyContent: 'space-between',
      fontFamily: D2W_FONT, fontSize: 12, color: D2W.ink,
    }}>
      <span style={{
        display: 'inline-flex', alignItems: 'baseline', gap: 6,
      }}>
        <span style={{ color: D2W.greyMid, fontWeight: 400, fontSize: 11 }}>{label}</span>
        <span style={{ fontWeight: 400 }}>{value}</span>
      </span>
      <span style={{
        width: 0, height: 0,
        borderLeft: '4px solid transparent',
        borderRight: '4px solid transparent',
        borderTop: `5px solid ${D2W.greyMid}`,
      }} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Pagination footer (table)
// ─────────────────────────────────────────────────────────────
function PaginationFooter({ from, to, total }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'flex-start', gap: 12,
      paddingTop: 8, borderTop: `1px solid ${D2W.ruleSoft}`,
      fontFamily: D2W_MONO, fontSize: 10, color: D2W.greyMid, letterSpacing: 0.6,
    }}>
      <span>{from} - {to} / {total}</span>
      <span style={{ flex: 1 }} />
      <button style={{
        background: 'transparent', border: 'none', cursor: 'pointer',
        padding: 4, color: D2W.greyMid, fontSize: 12,
      }}>‹</button>
      <button style={{
        background: 'transparent', border: 'none', cursor: 'pointer',
        padding: 4, color: D2W.greyMid, fontSize: 12,
      }}>›</button>
    </div>
  );
}

Object.assign(window, {
  D2W, D2W_FONT, D2W_MONO, D2W_COLOR,
  D2Card, CounterCard, DonutChart, BarChart, GroupedBarChart,
  MultiLineChart, FunnelChart, FilterChip, PaginationFooter,
});
