// WXG MOVEO — simplified Power-BI-style dashboard frame (5 tabs)
// Mirrors the live dashboard provided as reference: filter row +
// per-page widgets in a 4-column grid. Brand-aligned (Calibri,
// amber accents, secondary pastels).

// ─────────────────────────────────────────────────────────────
// Top bar — WXG logo, page title, filter row, tab strip
// ─────────────────────────────────────────────────────────────
function D2TopBar({ activeTab, onTab }) {
  return (
    <div style={{
      background: D2W.card, borderBottom: `1px solid ${D2W.rule}`,
      flexShrink: 0, position: 'relative',
    }}>
      {/* Logo row */}
      <div style={{
        padding: '14px 24px 12px', display: 'flex', alignItems: 'center',
        justifyContent: 'space-between', gap: 20,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <WXGOfficial height={28} color={D2W.grey} accent={D2W.amber} />
          <div style={{
            paddingInlineStart: 14, borderInlineStart: `1px solid ${D2W.ruleSoft}`,
          }}>
            <div style={{
              fontFamily: D2W_FONT, fontWeight: 700, fontSize: 13,
              color: D2W.ink, letterSpacing: 0.4,
            }}>MOVEO · דאשבורד סקרים</div>
            <div style={{
              fontFamily: D2W_MONO, fontSize: 9, color: D2W.greyMid,
              letterSpacing: 1.2, textTransform: 'uppercase', marginTop: 2,
            }}>NPS · CUSTOMER SATISFACTION</div>
          </div>
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          fontFamily: D2W_FONT, fontSize: 11, color: D2W.greyMid,
        }}>
          <span>עודכן: 01/01/2026 09:14</span>
          <button style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '6px 10px', background: 'transparent',
            border: `1px solid ${D2W.rule}`, color: D2W.inkSoft,
            fontFamily: D2W_FONT, fontSize: 11, cursor: 'pointer',
          }}>↓ ייצוא</button>
        </div>
      </div>

      {/* Filter row */}
      <div style={{
        padding: '0 24px 12px', display: 'flex', gap: 12, flexWrap: 'wrap',
      }}>
        {D2.filters.map((f, i) => (
          <FilterChip key={i} label={f.k} value={f.v} />
        ))}
      </div>

      {/* Tabs */}
      <div style={{
        padding: '0 24px', display: 'flex', gap: 0,
        borderTop: `1px solid ${D2W.ruleSoft}`,
      }}>
        {D2.tabs.map(t => {
          const active = t.id === activeTab;
          return (
            <div key={t.id} onClick={() => onTab(t.id)} style={{
              padding: '11px 16px', cursor: 'pointer',
              borderBottom: `2px solid ${active ? D2W.amber : 'transparent'}`,
              color: active ? D2W.ink : D2W.greyMid,
              fontFamily: D2W_FONT, fontWeight: active ? 700 : 400, fontSize: 12.5,
              transition: 'color .15s',
              marginBottom: -1,
            }}>{t.label}</div>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Page 1 — סקירה כללית
// ─────────────────────────────────────────────────────────────
function D2Page1() {
  const { counters, distribution, statusDonut, milestoneDonut, trend } = D2.p1;
  return (
    <div style={{
      padding: 16, display: 'grid', flex: 1,
      gridTemplateColumns: 'repeat(4, 1fr)',
      gridAutoRows: 'minmax(0, auto)',
      gap: 12, alignContent: 'start',
    }}>
      {/* Top row — 4 counters */}
      <CounterCard label="NPS Score" value={counters.nps.toFixed(2)} accent={D2W.amber} />
      <CounterCard label="תגובות" value={counters.surveys} accent={D2W.green} />
      <CounterCard label="% Promoters" value={counters.promotersPct.toFixed(2)} accent={D2W.green} />
      <CounterCard label="% Detractors" value={counters.detractorsPct} accent={D2W.wine} />

      {/* Row 2 — NPS distribution donut + status donut + counters block */}
      <div style={{ gridColumn: 'span 2' }}>
        <D2Card title="התפלגות NPS">
          <DonutChart data={distribution} size={150} showLegend />
        </D2Card>
      </div>
      <D2Card title="סקרים לפי סטטוס">
        <DonutChart data={statusDonut} size={130} showLegend />
      </D2Card>
      <D2Card title="סקרים לפי אבן-דרך">
        <DonutChart data={milestoneDonut} size={130} showLegend />
      </D2Card>

      {/* Row 3 — trend chart (spans 3) + 2 counter stack (span 1) */}
      <div style={{ gridColumn: 'span 3' }}>
        <D2Card title="מגמות NPS — לאורך זמן"
          action={
            <div style={{
              display: 'flex', gap: 14, fontFamily: D2W_FONT, fontSize: 11,
            }}>
              {trend.series.map((s, i) => (
                <div key={i} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  color: D2W.inkSoft,
                }}>
                  <span style={{
                    width: 12, height: 2,
                    background: D2W_COLOR[s.c] || D2W.amber,
                  }} />
                  <span>{s.k}</span>
                </div>
              ))}
            </div>
          }>
          <MultiLineChart months={trend.months} series={trend.series} height={220} />
        </D2Card>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <CounterCard label="סקרים" value={counters.surveys} accent={D2W.amber} />
        <CounterCard label="אנשי קשר" value={counters.contacts} accent={D2W.green} />
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Page 2 — שיטות איסוף
// ─────────────────────────────────────────────────────────────
function D2Page2() {
  const { completedSurveys, methodStatus, platform, digitalStatus, meaningfulText } = D2.p2;
  return (
    <div style={{
      padding: 16, display: 'grid', flex: 1,
      gridTemplateColumns: 'repeat(4, 1fr)', gridAutoRows: 'minmax(0, auto)',
      gap: 12, alignContent: 'start',
    }}>
      {/* Top counter */}
      <CounterCard label="סקרים שהושלמו" value={completedSurveys} accent={D2W.amber} />
      {/* Status by collection method - grouped bar (spans 3) */}
      <div style={{ gridColumn: 'span 3' }}>
        <D2Card title="סטטוס סקרים לפי שיטת איסוף">
          <GroupedBarChart data={methodStatus.data} height={200} />
        </D2Card>
      </div>

      {/* Row 2 — three half-width charts */}
      <div style={{ gridColumn: 'span 2' }}>
        <D2Card title="סקרים שהושלמו לפי פלטפורמה">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, padding: '4px 0 8px' }}>
            {platform.map(p => {
              const max = Math.max(...platform.map(x => x.v));
              const pct = (p.v / max) * 100;
              return (
                <div key={p.k}>
                  <div style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                    marginBottom: 5, fontFamily: D2W_FONT,
                  }}>
                    <span style={{ fontSize: 13, color: D2W.ink }}>{p.k}</span>
                    <span style={{ fontSize: 18, fontWeight: 300, color: D2W.ink }}>{p.v}</span>
                  </div>
                  <div style={{ height: 18, background: D2W.ruleSoft, position: 'relative' }}>
                    <div style={{
                      position: 'absolute', insetInlineStart: 0, top: 0, bottom: 0,
                      width: `${pct}%`,
                      background: D2W_COLOR[p.c] || D2W.amber,
                    }} />
                  </div>
                </div>
              );
            })}
          </div>
        </D2Card>
      </div>
      <D2Card title="סקרים דיגיטליים לפי סטטוס">
        <DonutChart data={digitalStatus} size={120} showLegend />
      </D2Card>
      <D2Card title="סקרים דיגיטליים שהושלמו · עם טקסט משמעותי">
        <DonutChart data={meaningfulText} size={120} showLegend />
      </D2Card>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Page 3 — ניתוח תגובות (response table + project × milestone matrix)
// ─────────────────────────────────────────────────────────────
function D2Page3() {
  const { rows, pagination, matrix } = D2.p3;
  return (
    <div style={{
      padding: 16, display: 'grid', flex: 1, gridTemplateColumns: '1.4fr 1fr',
      gap: 12, alignContent: 'start',
    }}>
      {/* Response detail table */}
      <D2Card title="תגובות סקר · פירוט נסקרים" pad={0}>
        <div style={{
          display: 'grid', gridTemplateColumns: '32px 1fr 1fr 2fr 70px',
          gap: 0, padding: '10px 14px', background: D2W.ruleSoft,
          borderBottom: `1px solid ${D2W.rule}`,
          fontFamily: D2W_FONT, fontWeight: 700, fontSize: 11.5, color: D2W.ink,
        }}>
          <div>#</div><div>נסקר</div><div>אבן-דרך</div><div>הערות לשיפור</div>
          <div style={{ textAlign: 'left' }}>NPS Score</div>
        </div>
        {rows.map((r, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '32px 1fr 1fr 2fr 70px', gap: 0,
            padding: '9px 14px', borderBottom: `1px solid ${D2W.ruleSoft}`,
            fontFamily: D2W_FONT, fontSize: 12, color: D2W.inkSoft,
            background: i % 2 === 1 ? '#FBFAF8' : D2W.card,
            alignItems: 'center',
          }}>
            <div style={{ fontFamily: D2W_MONO, fontSize: 10, color: D2W.greyMid }}>{r.i}.</div>
            <div style={{ color: D2W.ink }}>{r.name}</div>
            <div>{r.milestone}</div>
            <div style={{
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              fontWeight: 300,
            }}>{r.note || '—'}</div>
            <div style={{
              textAlign: 'left', fontFamily: D2W_MONO, fontWeight: 700, fontSize: 12,
              color: r.nps == null ? D2W.greyLight
                : r.nps >= 60  ? D2W.green
                : r.nps >= 0   ? D2W.gold
                : D2W.wine,
            }}>{r.nps == null ? '—' : r.nps}</div>
          </div>
        ))}
        <div style={{ padding: '8px 14px' }}>
          <PaginationFooter {...pagination} />
        </div>
      </D2Card>

      {/* Project × milestone NPS matrix */}
      <D2Card title="ניתוח תגובות אל מול ציוני NPS" pad={0}>
        <div style={{
          padding: '10px 14px', background: D2W.ruleSoft,
          borderBottom: `1px solid ${D2W.rule}`,
          display: 'grid', gridTemplateColumns: '1.4fr repeat(3, 60px)',
          gap: 8, fontFamily: D2W_FONT, fontWeight: 700, fontSize: 10,
          color: D2W.ink,
        }}>
          <div style={{ fontSize: 11 }}>שם הפרויקט</div>
          {matrix.milestones.map(m => (
            <div key={m} style={{
              textAlign: 'center', fontSize: 10, lineHeight: 1.2,
            }}>{m}</div>
          ))}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {matrix.projects.map((p, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '1.4fr repeat(3, 60px)',
              gap: 8, padding: '7px 14px',
              borderBottom: `1px solid ${D2W.ruleSoft}`,
              background: i % 2 === 1 ? '#FBFAF8' : D2W.card,
              alignItems: 'center', fontFamily: D2W_FONT, fontSize: 11.5,
            }}>
              <div style={{
                color: D2W.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              }}>{p.name}</div>
              {p.vals.map((v, j) => (
                <div key={j} style={{
                  textAlign: 'center', fontFamily: D2W_MONO,
                  fontSize: 11, fontWeight: v == null ? 400 : 700,
                  color: v == null ? D2W.greyLight
                    : v >= 50  ? D2W.green
                    : v >= 0   ? D2W.gold
                    : D2W.wine,
                  background: v == null ? 'transparent'
                    : v >= 50 ? D2W.greenSoft + '44'
                    : v >= 0  ? D2W.goldSoft + '55'
                    : D2W.wineSoft + '44',
                  padding: '3px 4px',
                }}>{v == null ? '—' : v}</div>
              ))}
            </div>
          ))}
          {/* Grand total */}
          <div style={{
            display: 'grid', gridTemplateColumns: '1.4fr repeat(3, 60px)',
            gap: 8, padding: '10px 14px', background: D2W.ink,
            fontFamily: D2W_FONT, fontWeight: 700,
          }}>
            <div style={{ color: D2W.amber, fontSize: 12 }}>Grand total</div>
            {matrix.total.vals.map((v, j) => (
              <div key={j} style={{
                textAlign: 'center', color: D2W.amber, fontFamily: D2W_MONO,
                fontSize: 12,
              }}>{v}</div>
            ))}
          </div>
        </div>
      </D2Card>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Page 4 — אנליטיקס משובים
// ─────────────────────────────────────────────────────────────
function D2Page4() {
  const { surveysCreated, surveysViewed, surveysSent, funnel, progress, progressTotal, progressPagination } = D2.p4;
  return (
    <div style={{
      padding: 16, display: 'grid', flex: 1, gridTemplateColumns: 'repeat(4, 1fr)',
      gridAutoRows: 'minmax(0, auto)', gap: 12, alignContent: 'start',
    }}>
      {/* Counters */}
      <CounterCard label="סקרים שנוצרו" value={surveysCreated} accent={D2W.amber} />
      <CounterCard label="סקרים שנשלחו" value={surveysSent} accent={D2W.grey} />
      <CounterCard label="סקרים שנצפו" value={surveysViewed} accent={D2W.grey} />
      <CounterCard label="סקרים שהושלמו" value="90" accent={D2W.green} />

      {/* Funnel + progression table */}
      <div style={{ gridColumn: 'span 2' }}>
        <D2Card title="התקדמות משפך">
          <FunnelChart data={funnel} height={220} />
        </D2Card>
      </div>
      <div style={{ gridColumn: 'span 2' }}>
        <D2Card title="טבלת התקדמות סקרים" pad={0}>
          <div style={{
            display: 'grid', gridTemplateColumns: '1.2fr 60px 60px 80px 1.4fr 90px',
            padding: '8px 14px', background: D2W.ruleSoft,
            borderBottom: `1px solid ${D2W.rule}`,
            fontFamily: D2W_FONT, fontWeight: 700, fontSize: 10, color: D2W.ink,
            gap: 6,
          }}>
            <div>ContactName</div>
            <div>furthest_page</div>
            <div>progression_stage</div>
            <div>progression_status</div>
            <div>Created</div>
            <div style={{ textAlign: 'left' }}>min_to_complete</div>
          </div>
          {progress.slice(0, 10).map((r, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '1.2fr 60px 60px 80px 1.4fr 90px', gap: 6,
              padding: '7px 14px', borderBottom: `1px solid ${D2W.ruleSoft}`,
              background: i % 2 === 1 ? '#FBFAF8' : D2W.card,
              fontFamily: D2W_FONT, fontSize: 11, color: D2W.inkSoft,
            }}>
              <div style={{ color: D2W.ink }}>
                <span style={{ fontFamily: D2W_MONO, fontSize: 10, color: D2W.greyMid }}>{i+1}. </span>
                {r.name}
              </div>
              <div style={{ fontFamily: D2W_MONO, fontSize: 10, color: D2W.greyLight }}>{r.furthest}</div>
              <div style={{ fontFamily: D2W_MONO, fontSize: 10 }}>{r.stage}</div>
              <div>{r.status}</div>
              <div style={{ fontFamily: D2W_MONO, fontSize: 10, color: D2W.greyMid }}>{r.created}</div>
              <div style={{ fontFamily: D2W_MONO, fontSize: 10, textAlign: 'left' }}>{r.ms.toLocaleString()}</div>
            </div>
          ))}
          <div style={{
            display: 'grid', gridTemplateColumns: '1.2fr 60px 60px 80px 1.4fr 90px', gap: 6,
            padding: '9px 14px', background: D2W.ink, color: D2W.amber,
            fontFamily: D2W_FONT, fontWeight: 700, fontSize: 11,
          }}>
            <div>Grand total</div><div></div><div></div><div></div><div></div>
            <div style={{ fontFamily: D2W_MONO, textAlign: 'left' }}>{progressTotal.toLocaleString()}</div>
          </div>
          <div style={{ padding: '8px 14px' }}>
            <PaginationFooter {...progressPagination} />
          </div>
        </D2Card>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Page 5 — ניתוח לפי שאלה
// ─────────────────────────────────────────────────────────────
function D2Page5() {
  const { counters, questions } = D2.p5;
  return (
    <div style={{
      padding: 16, display: 'grid', flex: 1, gridTemplateColumns: 'repeat(4, 1fr)',
      gridAutoRows: 'minmax(0, auto)', gap: 12, alignContent: 'start',
    }}>
      {/* Counters */}
      <CounterCard label="לקוחות"     value={counters.customers} accent={D2W.amber} />
      <CounterCard label="פרויקטים"   value={counters.projects}  accent={D2W.green} />
      <CounterCard label="סקרים"      value={counters.surveys}   accent={D2W.gold} />
      <CounterCard label="אנשי קשר"   value={counters.contacts}  accent={D2W.blue} />

      {/* 5 per-question cards */}
      {questions.map((q, i) => {
        // Big one (the overall NPS Score) spans 2 cols
        const wide = q.npsLabel === 'NPS Score';
        return (
          <div key={i} style={{ gridColumn: wide ? 'span 2' : 'span 1' }}>
            <D2Card pad={14}
              title={
                <span style={{
                  fontFamily: D2W_FONT, fontWeight: 700, fontSize: 12,
                  color: D2W.ink, display: 'inline-block', textWrap: 'pretty',
                  lineHeight: 1.35, maxWidth: '95%',
                }}>{q.text}</span>
              }
              action={
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                  <span style={{
                    fontFamily: D2W_MONO, fontSize: 9, color: D2W.greyMid, letterSpacing: 0.6,
                  }}>{q.npsLabel}</span>
                  <span style={{
                    fontFamily: D2W_FONT, fontWeight: 700, fontSize: 18,
                    color: q.nps >= 60 ? D2W.green : q.nps >= 40 ? D2W.gold : D2W.wine,
                  }}>{q.nps.toFixed(2)}</span>
                </div>
              }>
              <BarChart data={q.bars} height={140} color={D2W.amber} />
            </D2Card>
          </div>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Main desktop dashboard
// ─────────────────────────────────────────────────────────────
function MoveoDashboard({ initialTab = 'p1' }) {
  const [tab, setTab] = React.useState(initialTab);
  const pages = {
    p1: <D2Page1 />,
    p2: <D2Page2 />,
    p3: <D2Page3 />,
    p4: <D2Page4 />,
    p5: <D2Page5 />,
  };
  return (
    <div dir="rtl" style={{
      width: '100%', height: '100%', display: 'flex', flexDirection: 'column',
      background: D2W.page, fontFamily: D2W_FONT, color: D2W.ink, overflow: 'hidden',
    }}>
      <D2TopBar activeTab={tab} onTab={setTab} />
      <div style={{ flex: 1, overflow: 'auto', minHeight: 0, display: 'flex', flexDirection: 'column' }}>
        {pages[tab]}
      </div>
    </div>
  );
}

window.MoveoDashboard = MoveoDashboard;
Object.assign(window, { D2TopBar, D2Page1, D2Page2, D2Page3, D2Page4, D2Page5 });
