(function () {
    const { createElement: h, useState, useEffect, Fragment } = wp.element;
  const { Spinner, Button } = wp.components;
  const apiFetch = wp.apiFetch;

  function formatGoal(goal) {
    const map = {
      clicks: 'Click',
      click: 'Click',
      form: 'Form submission',
      add_to_cart: 'Add to cart',
      purchase: 'Orders (Revenue)',
    };
    return map[goal] || (goal ? String(goal).replace(/[_-]+/g, ' ') : '—');
  }

  function formatDecision(rule, mode) {
    if (mode === 'manual' || rule === 'manual') {
      return 'Manual';
    }
    if (!rule) return 'Balanced';
    return String(rule).charAt(0).toUpperCase() + String(rule).slice(1);
  }

  function formatDate(ts) {
    if (!ts) return '—';
    const d = new Date(ts * 1000);
    return d.toLocaleString();
  }

  function sumTimeline(timeline, variant, key) {
    return (timeline || []).reduce((total, row) => {
      return total + (((row[variant] || {})[key]) || 0);
    }, 0);
  }

  function maxValue(series) {
    let max = 0;
    (series || []).forEach((n) => {
      if (n > max) max = n;
    });
    return max;
  }

  function formatBucketDate(bucket) {
    if (!bucket) return '—';
    const d = new Date(bucket + 'T00:00:00');
    return d.toLocaleDateString('en-GB');
  }
  
  function SimpleLineChart(props) {
    const {
      title,
      labels,
      seriesA,
      seriesB,
      yLabelA,
      yLabelB,
    } = props;

    const [hoverIndex, setHoverIndex] = useState(null);

    const width = 900;
    const height = 280;
    const padLeft = 44;
    const padRight = 16;
    const padTop = 18;
    const padBottom = 36;

    const innerW = width - padLeft - padRight;
    const innerH = height - padTop - padBottom;

    const maxY = Math.max(1, maxValue(seriesA), maxValue(seriesB));
    const count = Math.max(labels.length, 1);

    const pointX = (index) => {
      if (count === 1) return padLeft + innerW / 2;
      return padLeft + (index * innerW) / (count - 1);
    };

    const pointY = (value) => {
      const ratio = value / maxY;
      return padTop + innerH - ratio * innerH;
    };

    const toPath = (series) =>
      (series || [])
        .map((value, index) => `${index === 0 ? 'M' : 'L'} ${pointX(index)} ${pointY(value)}`)
        .join(' ');

    const gridLines = [0, 0.25, 0.5, 0.75, 1].map((r, i) => {
      const y = padTop + innerH - innerH * r;
      const label = Math.round(maxY * r);
      return h(
        Fragment,
        { key: `grid-${i}` },
        [
          h('line', {
            x1: padLeft,
            y1: y,
            x2: width - padRight,
            y2: y,
            stroke: '#e5e7eb',
            strokeWidth: 1,
          }),
          h(
            'text',
            {
              x: padLeft - 8,
              y: y + 4,
              textAnchor: 'end',
              fontSize: 11,
              fill: '#6b7280',
            },
            String(label)
          ),
        ]
      );
    });

    const xLabels = labels.map((label, i) =>
      h(
        'text',
        {
          key: `xlabel-${i}`,
          x: pointX(i),
          y: height - 12,
          textAnchor: 'middle',
          fontSize: 11,
          fill: '#6b7280',
        },
        label
      )
    );

    const pointsA = (seriesA || []).map((value, i) =>
      h('circle', {
        key: `a-${i}`,
        cx: pointX(i),
        cy: pointY(value),
        r: hoverIndex === i ? 5 : 3,
        fill: '#79caf5',
      })
    );

    const pointsB = (seriesB || []).map((value, i) =>
      h('circle', {
        key: `b-${i}`,
        cx: pointX(i),
        cy: pointY(value),
        r: hoverIndex === i ? 5 : 3,
        fill: '#fc510b',
      })
    );

    const hoverRegions = labels.map((label, i) => {
      const x = pointX(i);
      const prevX = i > 0 ? pointX(i - 1) : padLeft;
      const nextX = i < labels.length - 1 ? pointX(i + 1) : width - padRight;
      const regionX = i === 0 ? padLeft : (prevX + x) / 2;
      const regionNextX = i === labels.length - 1 ? (width - padRight) : (x + nextX) / 2;
      const regionWidth = Math.max(12, regionNextX - regionX);

      return h('rect', {
        key: `hover-${i}`,
        x: regionX,
        y: padTop,
        width: regionWidth,
        height: innerH,
        fill: 'transparent',
        onMouseEnter: () => setHoverIndex(i),
        onMouseMove: () => setHoverIndex(i),
        onMouseLeave: () => setHoverIndex(null),
      });
    });

    const tooltip = hoverIndex !== null
      ? h(
          'div',
          {
            style: {
              position: 'absolute',
              top: '16px',
              left: '16px',
              background: '#fff',
              border: '1px solid #dcdcde',
              borderRadius: '6px',
              boxShadow: '0 4px 14px rgba(0,0,0,0.08)',
              padding: '10px 12px',
              fontSize: '12px',
              lineHeight: '1.4',
              zIndex: 5,
              pointerEvents: 'none',
              minWidth: '100px',
            },
          },
          [
            h(
              'div',
              {
                key: 'label',
                style: {
                  fontWeight: '700',
                  marginBottom: '6px',
                },
              },
              labels[hoverIndex] || ''
            ),
            h(
              'div',
              {
                key: 'a',
                style: {
                  color: '#79caf5',
                  marginBottom: '4px',
                },
              },
              `${yLabelA || 'Version A'}: ${((seriesA || [])[hoverIndex]) || 0}`
            ),
            h(
              'div',
              {
                key: 'b',
                style: {
                  color: '#fc510b',
                },
              },
              `${yLabelB || 'Version B'}: ${((seriesB || [])[hoverIndex]) || 0}`
            ),
          ]
        )
      : null;

    return h(
      'div',
      {
        style: {
          background: '#fff',
          border: '1px solid #dcdcde',
          borderRadius: '8px',
          padding: '16px',
          marginTop: '16px',
          position: 'relative',
        },
      },
      [
        tooltip,
        h(
          'div',
          {
            key: 'header',
            style: {
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '10px',
            },
          },
          [
            h(
              'h2',
              {
                style: {
                  margin: 0,
                  fontSize: '16px',
                },
              },
              title
            ),
            h(
              'div',
              {
                style: {
                  display: 'flex',
                  gap: '16px',
                  fontSize: '12px',
                },
              },
              [
                h(
                  'span',
                  { style: { display: 'inline-flex', alignItems: 'center', gap: '6px' } },
                  [
                    h('span', {
                      style: {
                        width: '10px',
                        height: '10px',
                        borderRadius: '999px',
                        background: '#79caf5',
                        display: 'inline-block',
                      },
                    }),
                    yLabelA || 'Version A',
                  ]
                ),
                h(
                  'span',
                  { style: { display: 'inline-flex', alignItems: 'center', gap: '6px' } },
                  [
                    h('span', {
                      style: {
                        width: '10px',
                        height: '10px',
                        borderRadius: '999px',
                        background: '#fc510b',
                        display: 'inline-block',
                      },
                    }),
                    yLabelB || 'Version B',
                  ]
                ),
              ]
            ),
          ]
        ),
        h(
          'svg',
          {
            width: '100%',
            viewBox: `0 0 ${width} ${height}`,
            style: {
              display: 'block',
              overflow: 'visible',
            },
          },
          [
            ...gridLines,
            hoverIndex !== null &&
              h('line', {
                x1: pointX(hoverIndex),
                y1: padTop,
                x2: pointX(hoverIndex),
                y2: padTop + innerH,
                stroke: '#c3c4c7',
                strokeWidth: 1,
                strokeDasharray: '4 4',
              }),
            h('path', {
              d: toPath(seriesA),
              fill: 'none',
              stroke: '#79caf5',
              strokeWidth: 3,
              strokeLinecap: 'round',
              strokeLinejoin: 'round',
            }),
            h('path', {
              d: toPath(seriesB),
              fill: 'none',
              stroke: '#fc510b',
              strokeWidth: 3,
              strokeLinecap: 'round',
              strokeLinejoin: 'round',
            }),
            ...pointsA,
            ...pointsB,
            ...xLabels,
            ...hoverRegions,
          ]
        ),
      ]
    );
  }

  function PerformanceApp() {
    const [range, setRange] = useState('day');
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [payload, setPayload] = useState(null);
    const [isEditingTitle, setIsEditingTitle] = useState(false);
    const [draftTitle, setDraftTitle] = useState('');
    const [openHelp, setOpenHelp] = useState(null);
    const [isActionsOpen, setIsActionsOpen] = useState(false);
    const [rowsPerPage, setRowsPerPage] = useState(10);
    const [currentPage, setCurrentPage] = useState(1);
    const [showHttpNotice, setShowHttpNotice] = useState(true);

    const testId =
    (window.location.hash ? window.location.hash.replace(/^#/, '') : '') ||
    ((abtestkitTestPerformance && abtestkitTestPerformance.testId) || '');

    const loadData = (selectedRange) => {
      setLoading(true);
      setError(null);

      apiFetch({
        url:
          abtestkitTestPerformance.rest.replace(/\/$/, '') +
          '/pt/performance',
        method: 'POST',
        headers: {
          'X-WP-Nonce': abtestkitTestPerformance.nonce,
          'Content-Type': 'application/json',
        },
        data: {
          test_id: testId,
          range: selectedRange,
        },
      })
        .then((data) => {
          if (!data || !data.ok || !data.test) {
            throw new Error('Unable to load performance data.');
          }
          setPayload(data.test);
          setCurrentPage(1);
          setLoading(false);
        })
        .catch((err) => {
          console.error('abtestkit performance error', err);
          setError('Failed to load performance data.');
          setLoading(false);
        });
    };

    useEffect(() => {
      if (!testId) {
        setError('Missing test ID.');
        setLoading(false);
        return;
      }

      loadData(range);
    }, [testId]);

    const changeRange = (nextRange) => {
      setRange(nextRange);
      setCurrentPage(1);
      loadData(nextRange);
    };

    useEffect(() => {
      setDraftTitle((payload && payload.title) ? payload.title : '');
    }, [payload && payload.title]);

    useEffect(() => {
      const handleDocumentClick = () => {
        setOpenHelp(null);
        setIsActionsOpen(false);
      };

      document.addEventListener('click', handleDocumentClick);
      return () => document.removeEventListener('click', handleDocumentClick);
    }, []);

    const helpTip = (id, content, side = 'right') =>
    h(
      'span',
      {
        style: {
          position: 'relative',
          display: 'inline-flex',
          alignItems: 'center',
          justifyContent: 'center',
          marginLeft: '6px',
          flex: '0 0 auto',
          verticalAlign: 'middle',
        },
      },
      [
        h(
          'span',
          {
            onClick: (e) => {
              e.stopPropagation();
              setOpenHelp(openHelp === id ? null : id);
            },
            style: {
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '16px',
              height: '16px',
              minWidth: '16px',
              minHeight: '16px',
              borderRadius: '999px',
              border: '1px solid #c3c4c7',
              color: '#50575e',
              fontSize: '11px',
              fontWeight: '700',
              lineHeight: '1',
              cursor: 'pointer',
              userSelect: 'none',
              background: '#fff',
              boxSizing: 'border-box',
            },
            'aria-label': content,
            title: content,
          },
          '?'
        ),

        openHelp === id &&
          h(
            'div',
            {
              style: {
                position: 'absolute',
                top: '26px',
                left: side === 'left' ? 'auto' : '0',
                right: side === 'left' ? '0' : 'auto',
                transform: 'none',
                zIndex: 100000,
                width: '220px',
                padding: '8px 10px',
                background: '#fff',
                border: '1px solid #ccd0d4',
                borderRadius: '4px',
                boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
                fontSize: '12px',
                lineHeight: '1.4',
                color: '#1d2327',
                textAlign: 'left',
              },
            },
            content
          ),
      ]
    );

    const submitPtAction = (action, extraFields = {}) => {
      if (!payload || !payload.id) {
        return;
      }

      const form = document.createElement('form');
      form.method = 'POST';
      form.action = abtestkitTestPerformance.adminAction;

      const nonceInput = document.createElement('input');
      nonceInput.type = 'hidden';
      nonceInput.name = '_wpnonce';
      nonceInput.value = abtestkitTestPerformance.adminNonce;
      form.appendChild(nonceInput);

      const doInput = document.createElement('input');
      doInput.type = 'hidden';
      doInput.name = 'do';
      doInput.value = action;
      form.appendChild(doInput);

      const idInput = document.createElement('input');
      idInput.type = 'hidden';
      idInput.name = 'id';
      idInput.value = payload.id;
      form.appendChild(idInput);

      Object.entries(extraFields).forEach(([key, value]) => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = value;
        form.appendChild(input);
      });

      document.body.appendChild(form);
      form.submit();
    };

    const startTest = () => {
      setIsActionsOpen(false);
      submitPtAction('start', {
        return_url: window.location.href,
      });
    };

    const pauseTest = () => {
      setIsActionsOpen(false);
      submitPtAction('pause', {
        return_url: window.location.href,
      });
    };

    const deleteTest = () => {
      setIsActionsOpen(false);

      if (!payload || !payload.id) {
        return;
      }

      if (!window.confirm('Delete this test?')) {
        return;
      }

      const isPageLike =
        payload.kind === 'page' || payload.kind === 'post';

      const hasOutcome =
        !!payload.winner || payload.status === 'complete';

      if (isPageLike && !hasOutcome) {
        const alsoDeleteVariant = window.confirm('Would you like to delete Version B?');
        if (alsoDeleteVariant) {
          submitPtAction('delete', { trash_b: '1' });
          return;
        }
      }

      submitPtAction('delete');
    };

    const resetTest = () => {
      setIsActionsOpen(false);

      if (!payload || !payload.id) {
        return;
      }

      const confirmed = window.confirm(
        'Are you sure? Resetting the test will set all metrics to zero.'
      );

      if (!confirmed) {
        return;
      }

      apiFetch({
        url:
          abtestkitTestPerformance.rest.replace(/\/$/, '') +
          '/pt/reset-test',
        method: 'POST',
        headers: {
          'X-WP-Nonce': abtestkitTestPerformance.nonce,
          'Content-Type': 'application/json',
        },
        data: {
          test_id: payload.id,
        },
      })
        .then((res) => {
          if (!res || !res.ok) {
            throw new Error('Unable to reset test.');
          }
          loadData(range);
        })
        .catch((err) => {
          console.error('abtestkit reset test error', err);
          window.alert('Failed to reset test metrics.');
        });
    };

    const applyWinner = () => {
      setIsActionsOpen(false);

      if (!payload || !payload.id) {
        return;
      }

      const statsA = (payload.stats && payload.stats.A) ? payload.stats.A : {};
      const statsB = (payload.stats && payload.stats.B) ? payload.stats.B : {};
      const isRevenueTest = payload.goal === 'purchase';

      const impressionsA = Number(statsA.impressions || 0);
      const impressionsB = Number(statsB.impressions || 0);

      const conversionsA = Number(
        isRevenueTest ? (statsA.purchases || 0) : (statsA.clicks || 0)
      );
      const conversionsB = Number(
        isRevenueTest ? (statsB.purchases || 0) : (statsB.clicks || 0)
      );

      const revenueA = Number(statsA.revenue || 0);
      const revenueB = Number(statsB.revenue || 0);

      const metricA = isRevenueTest
        ? (impressionsA > 0 ? revenueA / impressionsA : 0)
        : (impressionsA > 0 ? conversionsA / impressionsA : 0);

      const metricB = isRevenueTest
        ? (impressionsB > 0 ? revenueB / impressionsB : 0)
        : (impressionsB > 0 ? conversionsB / impressionsB : 0);

      const fallbackLeader =
        metricB > metricA ? 'B' :
        metricA > metricB ? 'A' :
        null;

      const leader =
        payload.winner === 'A' || payload.winner === 'B'
          ? payload.winner
          : fallbackLeader;

      if (leader !== 'A' && leader !== 'B') {
        window.alert('There is no clear winner to apply yet.');
        return;
      }

      if (leader === 'B') {
        const confirmed = window.confirm(
          payload.kind === 'product'
            ? 'Apply Version B winner? This will apply Version B changes to the live product and complete the test.'
            : 'Apply Version B winner? This will replace Version A with Version B and complete the test.'
        );

        if (!confirmed) {
          return;
        }

        submitPtAction('apply_b_winner', {
          return_url: window.location.href,
        });
        return;
      }

      const keepAConfirmed = window.confirm(
        'Apply Version A winner? This will keep Version A as the winner and complete the test.'
      );

      if (!keepAConfirmed) {
        return;
      }

      let trashB = '0';

      if (payload.kind === 'page' || payload.kind === 'post') {
        const deleteBConfirmed = window.confirm(
          'Would you like to delete Version B?'
        );
        trashB = deleteBConfirmed ? '1' : '0';
      }

      submitPtAction('keep_a_winner', {
        trash_b: trashB,
        return_url: window.location.href,
      });
    };

    const saveTitle = () => {
      const trimmed = String(draftTitle || '').trim();

      if (!payload || !payload.id) {
        setIsEditingTitle(false);
        return;
      }

      if (!trimmed) {
        setDraftTitle(payload.title || '');
        setIsEditingTitle(false);
        return;
      }

      apiFetch({
        url:
          abtestkitTestPerformance.rest.replace(/\/$/, '') +
          '/pt/update-title',
        method: 'POST',
        headers: {
          'X-WP-Nonce': abtestkitTestPerformance.nonce,
          'Content-Type': 'application/json',
        },
        data: {
          test_id: payload.id,
          title: trimmed,
        },
      })
        .then((res) => {
          if (!res || !res.ok) {
            throw new Error('Unable to update title.');
          }

          setPayload((current) => ({
            ...current,
            title: trimmed,
          }));
          setIsEditingTitle(false);
        })
        .catch((err) => {
          console.error('abtestkit title update error', err);
          window.alert('Failed to update test title.');
          setDraftTitle(payload.title || '');
          setIsEditingTitle(false);
        });
    };

if (loading) {
      return h(
        'div',
        { className: 'abtestkit-performance-loading' },
        h(Spinner, null),
        ' Loading performance…'
      );
    }

    if (error) {
      return h(
        'div',
        null,
        [
          h('div', { className: 'notice notice-error' }, h('p', null, error)),
          h(
            Button,
            {
              href: abtestkitTestPerformance.dashboardUrl,
              isSecondary: true,
            },
            'Back to Dashboard'
          ),
        ]
      );
    }

    const stats = payload.stats || { A: {}, B: {} };
    const timeline = payload.timeline || [];
    const isRevenueGoal = payload.goal === 'purchase';
    const previewA = payload.preview_a || '';
    const previewB = payload.preview_b || '';
    const httpExcludedCount = Number(payload.http_excluded_count || 0);
    const httpExcludedLast = payload.http_excluded_last || '';

    const labels = timeline.map((row) => {
      if (range === 'month') {
        const d = new Date(row.bucket + 'T00:00:00');
        return d.toLocaleDateString(undefined, { month: 'short', year: 'numeric' });
      }

      if (range === 'week') {
        const d = new Date(row.bucket + 'T00:00:00');
        return d.toLocaleDateString(undefined, { day: 'numeric', month: 'short' });
      }

      const d = new Date(row.bucket + 'T00:00:00');
      return d.toLocaleDateString(undefined, { day: 'numeric', month: 'short' });
    });

    const impressionSeriesA = timeline.map((row) => ((row.A || {}).impressions) || 0);
    const impressionSeriesB = timeline.map((row) => ((row.B || {}).impressions) || 0);

    const conversionKey = isRevenueGoal ? 'purchases' : 'clicks';
    const conversionSeriesA = timeline.map((row) => ((row.A || {})[conversionKey]) || 0);
    const conversionSeriesB = timeline.map((row) => ((row.B || {})[conversionKey]) || 0);
    const revenueSeriesA = timeline.map((row) => Number(((row.A || {}).revenue) || 0));
    const revenueSeriesB = timeline.map((row) => Number(((row.B || {}).revenue) || 0));

    const totalImpA = Number((stats.A && stats.A.impressions) || 0);
    const totalImpB = Number((stats.B && stats.B.impressions) || 0);
    const totalConvA = Number((stats.A && stats.A[conversionKey]) || 0);
    const totalConvB = Number((stats.B && stats.B[conversionKey]) || 0);

    const totalRevenueA = Number((stats.A && stats.A.revenue) || 0);
    const totalRevenueB = Number((stats.B && stats.B.revenue) || 0);
    const rpcA = Number((stats.A && stats.A.revenue_per_customer) || 0);
    const rpcB = Number((stats.B && stats.B.revenue_per_customer) || 0);

    const rpvA = totalImpA > 0 ? (totalRevenueA / totalImpA) : 0;
    const rpvB = totalImpB > 0 ? (totalRevenueB / totalImpB) : 0;

    const rateA = totalImpA > 0 ? ((totalConvA / totalImpA) * 100).toFixed(2) : '0.00';
    const rateB = totalImpB > 0 ? ((totalConvB / totalImpB) * 100).toFixed(2) : '0.00';

    const nowTs = Math.floor(Date.now() / 1000);
    const startedAt = Number(payload.started_at || 0);
    const elapsedDaysRaw = startedAt > 0 ? ((nowTs - startedAt) / 86400) : 0;
    const elapsedDays = elapsedDaysRaw > 0 ? Math.max(elapsedDaysRaw, 1) : 0;

    const totalTestVisitors = totalImpA + totalImpB;
    const visitorsPerDay = elapsedDays > 0 ? (totalTestVisitors / elapsedDays) : 0;
    const projectedMonthlyVisitors = visitorsPerDay * 30;

    const upliftPerVisitorA = rpvA - rpvB;
    const upliftPerVisitorB = rpvB - rpvA;

    const predictedMonthlyUpliftA = upliftPerVisitorA > 0
      ? upliftPerVisitorA * projectedMonthlyVisitors
      : 0;

    const predictedMonthlyUpliftB = upliftPerVisitorB > 0
      ? upliftPerVisitorB * projectedMonthlyVisitors
      : 0;

    const leaderMetricA = isRevenueGoal ? rpvA : (totalImpA > 0 ? (totalConvA / totalImpA) : 0);
    const leaderMetricB = isRevenueGoal ? rpvB : (totalImpB > 0 ? (totalConvB / totalImpB) : 0);

    let percentA = 50;
    let percentB = 50;

    if (leaderMetricA > 0 || leaderMetricB > 0) {
      const sum = leaderMetricA + leaderMetricB;
      percentA = Math.round((leaderMetricA / sum) * 100);
      percentB = 100 - percentA;
    }

    const currency = (value) =>
      new Intl.NumberFormat(undefined, {
        style: 'currency',
        currency: 'GBP',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(Number(value || 0));

    const winningVersion =
      leaderMetricB > leaderMetricA ? 'B' :
      leaderMetricA > leaderMetricB ? 'A' :
      null;

    const showUpliftA = isRevenueGoal && winningVersion === 'A';
    const showUpliftB = isRevenueGoal && winningVersion === 'B';

    const hasEnoughUpliftDataA = totalImpA >= 10;
    const hasEnoughUpliftDataB = totalImpB >= 10;

    const upliftDisplayA = !showUpliftA
      ? '-'
      : !hasEnoughUpliftDataA
      ? 'Calculating'
      : predictedMonthlyUpliftA > 0
      ? currency(predictedMonthlyUpliftA)
      : '-';

    const upliftDisplayB = !showUpliftB
      ? '-'
      : !hasEnoughUpliftDataB
      ? 'Calculating'
      : predictedMonthlyUpliftB > 0
      ? currency(predictedMonthlyUpliftB)
      : '-';

    const totalTimelineRows = timeline.length;
    const totalPages = Math.max(1, Math.ceil(totalTimelineRows / rowsPerPage));
    const safeCurrentPage = Math.min(currentPage, totalPages);
    const startRow = (safeCurrentPage - 1) * rowsPerPage;
    const endRow = startRow + rowsPerPage;
    const reversedTimeline = [...timeline].reverse();
    const paginatedTimeline = reversedTimeline.slice(startRow, endRow);

    const cardStyle = {
      background: '#fff',
      border: '1px solid #dcdcde',
      borderRadius: '8px',
      padding: '14px 16px',
    };

    const statLabelStyle = {
      fontSize: '12px',
      color: '#6b7280',
      marginBottom: '4px',
      display: 'inline-flex',
      alignItems: 'center',
      gap: '0',
      lineHeight: '1.2',
    };

    const statValueStyle = {
      fontSize: '18px',
      fontWeight: '700',
      color: '#111827',
      lineHeight: '1.2',
    };

    return h(
      'div',
      { className: 'abtestkit-test-performance-app' },
      [
        httpExcludedCount > 0 && showHttpNotice &&
        h(
          'div',
          {
            key: 'http-warning',
            className: 'notice notice-warning',
            style: {
              marginBottom: '16px',
              padding: '12px 14px',
              display: 'flex',
              alignItems: 'flex-start',
              justifyContent: 'space-between',
              gap: '12px',
            },
          },
          [
            h(
              'p',
              {
                style: {
                  margin: 0,
                  fontSize: '13px',
                  lineHeight: '1.5',
                  flex: '1 1 auto',
                },
              },
              `${httpExcludedCount} visit(s) were not tracked because they came through an insecure (HTTP) version of your site. This can lead to inaccurate results.

                      ${httpExcludedLast ? `Last seen: ${httpExcludedLast}. ` : ''}We recommend forcing HTTPS across your site to ensure reliable test data.`
            ),
            h(
              'button',
              {
                type: 'button',
                onClick: () => setShowHttpNotice(false),
                'aria-label': 'Dismiss HTTP warning',
                title: 'Dismiss',
                style: {
                  border: '0',
                  background: 'transparent',
                  padding: 0,
                  margin: 0,
                  width: '18px',
                  height: '18px',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                  color: '#50575e',
                  fontSize: '16px',
                  lineHeight: '1',
                  flex: '0 0 auto',
                },
              },
              '×'
            ),
          ]
        ),

        h(
          'div',
          {
            key: 'topbar',
            style: {
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              gap: '12px',
              marginBottom: '16px',
            },
          },
          [
            h(
              'div',
              null,
              [
              h(
                'div',
                {
                  style: {
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    marginBottom: '4px',
                  },
                },
                [
                  isEditingTitle
                    ? h('input', {
                        type: 'text',
                        value: draftTitle,
                        autoFocus: true,
                        onChange: (e) => setDraftTitle(e.target.value),
                        onBlur: saveTitle,
                        onKeyDown: (e) => {
                          if (e.key === 'Enter') {
                            e.preventDefault();
                            saveTitle();
                          }
                          if (e.key === 'Escape') {
                            setDraftTitle(payload.title || '');
                            setIsEditingTitle(false);
                          }
                        },
                        style: {
                          fontSize: '22px',
                          fontWeight: '700',
                          lineHeight: '1.2',
                          padding: '2px 8px',
                          border: '1px solid #8c8f94',
                          borderRadius: '4px',
                          minWidth: '280px',
                          background: '#fff',
                        },
                      })
                    : h(
                        'div',
                        {
                          style: {
                            fontSize: '22px',
                            fontWeight: '700',
                            lineHeight: '1.2',
                          },
                        },
                        payload.title || 'Untitled test'
                      ),

                  h(
                    'button',
                    {
                      type: 'button',
                      onClick: () => {
                        setDraftTitle(payload.title || '');
                        setIsEditingTitle(true);
                      },
                      style: {
                        border: '0',
                        background: 'transparent',
                        padding: 0,
                        margin: 0,
                        width: '18px',
                        height: '18px',
                        display: 'inline-flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        cursor: 'pointer',
                        color: '#2271b1',
                      },
                      'aria-label': 'Edit test title',
                      title: 'Edit test title',
                    },
                    h('span', {
                      className: 'dashicons dashicons-edit',
                      style: {
                        fontSize: '16px',
                        width: '16px',
                        height: '16px',
                      },
                    })
                  ),
                ]
              ),
                h(
                  'div',
                  {
                    style: {
                      display: 'flex',
                      flexDirection: 'column',
                      gap: '4px',
                      fontSize: '13px',
                      color: '#50575e',
                    },
                  },
                  [
                    h(
                      'div',
                      null,
                      `Test ID: ${payload.id}`
                    ),
                    payload.url
                      ? h(
                          'div',
                          {
                            style: {
                              display: 'flex',
                              alignItems: 'center',
                              gap: '6px',
                              flexWrap: 'wrap',
                            },
                          },
                          [
                            h(
                              'span',
                              {
                                style: {
                                  color: '#50575e',
                                },
                              },
                              'Test URL:'
                            ),
                            h(
                              'a',
                              {
                                href: payload.url,
                                target: '_blank',
                                rel: 'noopener noreferrer',
                                style: {
                                  color: '#2271b1',
                                  textDecoration: 'none',
                                  display: 'inline-flex',
                                  alignItems: 'center',
                                  gap: '4px',
                                  minWidth: 0,
                                },
                                title: 'Open test URL',
                              },
                              [
                                h(
                                  'span',
                                  {
                                    style: {
                                      overflow: 'hidden',
                                      textOverflow: 'ellipsis',
                                      whiteSpace: 'nowrap',
                                      maxWidth: '520px',
                                      display: 'inline-block',
                                      verticalAlign: 'bottom',
                                    },
                                  },
                                  payload.url
                                ),
                                h('span', {
                                  className: 'dashicons dashicons-external',
                                  style: {
                                    fontSize: '14px',
                                    width: '14px',
                                    height: '14px',
                                  },
                                }),
                              ]
                            ),
                          ]
                        )
                      : null,
                  ]
                ),
              ]
            ),
            h(
              'div',
              {
                style: {
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  flexWrap: 'wrap',
                  justifyContent: 'flex-end',
                },
              },
              [
                h(
                  'div',
                  {
                    style: {
                      position: 'relative',
                    },
                    onClick: (e) => e.stopPropagation(),
                  },
                  [
                  h(
                    Button,
                    {
                      isSecondary: true,
                      onClick: (e) => {
                        e.stopPropagation();
                        setIsActionsOpen(!isActionsOpen);
                      },
                      style: {
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '6px',
                      },
                    },
                    [
                      'Actions',
                      h(
                        'span',
                        {
                          style: {
                            display: 'inline-flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                          },
                        },
                        h(
                          'svg',
                          {
                            width: 14,
                            height: 25,
                            viewBox: '0 0 20 16',
                            fill: 'none',
                            style: {
                              transform: isActionsOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                              transition: 'transform 0.15s ease',
                            },
                          },
                          h('path', {
                            d: 'M5 7l5 5 5-5',
                            stroke: 'currentColor',
                            strokeWidth: 2,
                            strokeLinecap: 'round',
                            strokeLinejoin: 'round',
                          })
                        )
                      ),
                    ]
                  ),
                    isActionsOpen &&
                      h(
                        'div',
                        {
                          style: {
                            position: 'absolute',
                            top: 'calc(100% + 8px)',
                            right: 0,
                            minWidth: '180px',
                            background: '#fff',
                            border: '1px solid #dcdcde',
                            borderRadius: '6px',
                            boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
                            padding: '6px 0',
                            zIndex: 1000,
                          },
                        },
                        [
                          payload && payload.status !== 'complete'
                            ? (
                                payload.status === 'running'
                                  ? h(
                                      'button',
                                      {
                                        type: 'button',
                                        onClick: pauseTest,
                                        style: {
                                          display: 'block',
                                          width: '100%',
                                          textAlign: 'left',
                                          padding: '10px 14px',
                                          border: '0',
                                          background: '#fff',
                                          cursor: 'pointer',
                                          fontSize: '13px',
                                        },
                                      },
                                      'Pause'
                                    )
                                  : h(
                                      'button',
                                      {
                                        type: 'button',
                                        onClick: startTest,
                                        style: {
                                          display: 'block',
                                          width: '100%',
                                          textAlign: 'left',
                                          padding: '10px 14px',
                                          border: '0',
                                          background: '#fff',
                                          cursor: 'pointer',
                                          fontSize: '13px',
                                        },
                                      },
                                      'Resume'
                                    )
                              )
                            : null,

                          payload && payload.status !== 'complete'
                            ? h(
                                'button',
                                {
                                  type: 'button',
                                  onClick: applyWinner,
                                  style: {
                                    display: 'block',
                                    width: '100%',
                                    textAlign: 'left',
                                    padding: '10px 14px',
                                    border: '0',
                                    background: '#fff',
                                    cursor: 'pointer',
                                    fontSize: '13px',
                                  },
                                },
                                'Apply winner'
                              )
                            : null,

                          payload && payload.status !== 'complete'
                            ? h(
                                'button',
                                {
                                  type: 'button',
                                  onClick: resetTest,
                                  style: {
                                    display: 'block',
                                    width: '100%',
                                    textAlign: 'left',
                                    padding: '10px 14px',
                                    border: '0',
                                    background: '#fff',
                                    cursor: 'pointer',
                                    fontSize: '13px',
                                  },
                                },
                                'Reset'
                              )
                            : null,

                          h(
                            'button',
                            {
                              type: 'button',
                              onClick: deleteTest,
                              style: {
                                display: 'block',
                                width: '100%',
                                textAlign: 'left',
                                padding: '10px 14px',
                                border: '0',
                                background: '#fff',
                                cursor: 'pointer',
                                fontSize: '13px',
                                color: '#b32d2e',
                              },
                            },
                            'Delete'
                          ),
                        ].filter(Boolean)
                      ),
                  ]
                ),

                h(
                  Button,
                  {
                    href: abtestkitTestPerformance.dashboardUrl,
                    isSecondary: true,
                  },
                  'Back to Dashboard'
                ),
              ].filter(Boolean)
            ),
          ]
        ),

        h(
          'div',
          {
            key: 'meta-grid',
            style: {
              display: 'grid',
              gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
              gap: '12px',
              marginBottom: '16px',
            },
          },
          [
            h('div', { style: cardStyle }, [
              h('div', { style: statLabelStyle }, 'Type'),
              h('div', { style: statValueStyle }, payload.kind || '—'),
            ]),
            h('div', { style: cardStyle }, [
              h('div', { style: statLabelStyle }, 'Status'),
              h('div', { style: statValueStyle }, payload.status || '—'),
            ]),
            h('div', { style: cardStyle }, [
              h('div', { style: statLabelStyle }, 'Goal'),
              h('div', { style: statValueStyle }, formatGoal(payload.goal)),
            ]),
            h('div', { style: cardStyle }, [
              h('div', { style: statLabelStyle }, 'Decision Mode'),
              h('div', { style: statValueStyle }, formatDecision(payload.decision_rule, payload.decision_mode)),
            ]),
            h('div', { style: cardStyle }, [
              h('div', { style: statLabelStyle }, 'Min. Impressions'),
              h('div', { style: statValueStyle }, String(payload.min_impressions || 0)),
            ]),
            h('div', { style: cardStyle }, [
              h('div', { style: statLabelStyle }, 'Min. Conversions'),
              h('div', { style: statValueStyle }, String(payload.min_conversions || 0)),
            ]),
            h('div', { style: cardStyle }, [
              h('div', { style: statLabelStyle }, 'Started'),
              h('div', { style: { fontSize: '14px', fontWeight: '600' } }, formatDate(payload.started_at)),
            ]),
            h('div', { style: cardStyle }, [
              h('div', { style: statLabelStyle }, 'Finished'),
              h('div', { style: { fontSize: '14px', fontWeight: '600' } }, formatDate(payload.finished_at)),
            ]),
            h('div', { style: cardStyle }, [
              h('div', { style: statLabelStyle }, 'Winner'),
              h('div', { style: statValueStyle }, payload.winner ? String(payload.winner).toUpperCase() : '—'),
            ]),
          ]
        ),
        h(
          'div',
          {
            key: 'winner-summary',
            style: {
              background: '#fff',
              border: '1px solid #dcdcde',
              borderRadius: '8px',
              padding: '18px 20px',
              marginBottom: '16px'
            }
          },
          [
            h(
              'div',
              {
                style: {
                  maxWidth: '760px',
                  margin: '0 auto',
                }
              },
              [
                h(
                  'div',
                  {
                    style: {
                      textAlign: 'center',
                      marginBottom: '14px'
                    }
                  },
                  [
                    h(
                      'div',
                      {
                        style: {
                          fontSize: '14px',
                          color: '#6b7280',
                          marginBottom: '6px',
                          display: 'inline-flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          gap: '4px'
                        }
                      },
                      [
                        'Current test leader',
                        isRevenueGoal &&
                          helpTip(
                            'leader-rpv',
                            'For revenue tests, the current leader is based on Revenue per Visitor (RPV).',
                          )
                      ].filter(Boolean)
                    ),
                    h(
                      'div',
                      {
                        style: {
                          fontSize: '28px',
                          fontWeight: '700',
                          lineHeight: '1.15',
                          color: '#111827'
                        }
                      },
                      percentB > percentA
                        ? `Version B is winning (+${percentB - percentA}%)`
                        : percentA > percentB
                        ? `Version A is winning (+${percentA - percentB}%)`
                        : 'Versions are currently tied'
                    )
                  ]
                ),

                h(
                  'div',
                  {
                    style: {
                      display: 'grid',
                      gridTemplateColumns: '1fr 1fr',
                      columnGap: '24px',
                      alignItems: 'center',
                      marginBottom: '8px',
                      fontSize: '13px',
                      fontWeight: '600',
                      color: '#374151'
                    }
                  },
                  [
                    h(
                      'div',
                      {
                        style: {
                          textAlign: 'center',
                        }
                      },
                      `Version A — ${percentA}%`
                    ),
                    h(
                      'div',
                      {
                        style: {
                          textAlign: 'center',
                        }
                      },
                      `Version B — ${percentB}%`
                    )
                  ]
                ),

                h(
                  'div',
                  {
                    style: {
                      width: '100%',
                      height: '14px',
                      background: '#e5e7eb',
                      borderRadius: '999px',
                      overflow: 'hidden'
                    }
                  },
                  [
                    h('div', {
                      style: {
                        width: percentA + '%',
                        height: '100%',
                        background: '#79caf5',
                        float: 'left'
                      }
                    }),
                    h('div', {
                      style: {
                        width: percentB + '%',
                        height: '100%',
                        background: '#fc510b',
                        float: 'left'
                      }
                    })
                  ]
                )
              ]
            )
          ]
        ),
        h(
          'div',
          {
            key: 'stats-grid',
            style: {
              display: 'grid',
              gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
              gap: '12px',
              marginBottom: '16px',
            },
          },
          [
          h('div', { style: cardStyle }, [
            h(
              'div',
              {
                style: {
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: '12px',
                  marginTop: 0,
                  marginBottom: '14px',
                },
              },
              [
                h(
                  'h2',
                  {
                    style: {
                      margin: 0,
                      fontSize: '16px',
                    },
                  },
                  'Version A'
                ),
                previewA
                  ? h(
                      'a',
                      {
                        href: previewA,
                        target: '_blank',
                        rel: 'noopener noreferrer',
                        style: {
                          color: '#2271b1',
                          textDecoration: 'none',
                          display: 'inline-flex',
                          alignItems: 'center',
                          gap: '4px',
                          fontSize: '13px',
                          fontWeight: '500',
                          whiteSpace: 'nowrap',
                          flex: '0 0 auto',
                        },
                        title: 'Preview Version A',
                      },
                      [
                        'Preview',
                        h('span', {
                          className: 'dashicons dashicons-external',
                          style: {
                            fontSize: '14px',
                            width: '14px',
                            height: '14px',
                          },
                        }),
                      ]
                    )
                  : null,
              ]
            ),
            h(
              'div',
              {
                style: {
                  display: 'grid',
                  gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
                  gap: '16px 18px',
                },
              },
              [
                h('div', null, [
                  h('div', { style: statLabelStyle }, 'Impressions'),
                  h('div', { style: statValueStyle }, String(totalImpA)),
                ]),
                h('div', null, [
                  h('div', { style: statLabelStyle }, isRevenueGoal ? 'Orders' : 'Conversions'),
                  h('div', { style: statValueStyle }, String(totalConvA)),
                ]),
                h('div', null, [
                  h(
                    'div',
                    { style: statLabelStyle },
                    [
                      isRevenueGoal ? 'Order Rate' : 'Conversion Rate',
                      helpTip(
                        'order-rate',
                        isRevenueGoal
                          ? 'Order Rate is the percentage of visitors who placed an order.'
                          : 'Conversion Rate is the percentage of visitors who completed the selected conversion goal.'
                      ),
                    ]
                  ),
                  h('div', { style: statValueStyle }, `${rateA}%`),
                ]),
                isRevenueGoal &&
                  h('div', null, [
                    h(
                      'div',
                      { style: statLabelStyle },
                      [
                        'Revenue',
                        helpTip(
                          'revenue',
                          'Revenue is the total order value generated by this version.'
                        ),
                      ]
                    ),
                    h('div', { style: statValueStyle }, currency(totalRevenueA)),
                  ]),
                isRevenueGoal &&
                  h('div', null, [
                    h(
                      'div',
                      { style: statLabelStyle },
                      [
                        'RPC',
                        helpTip(
                          'rpc',
                          'Revenue per Customer is total revenue divided by the number of customers who ordered.'
                        ),
                      ]
                    ),
                    h('div', { style: statValueStyle }, currency(rpcA)),
                  ]),
                isRevenueGoal &&
                  h('div', null, [
                    h(
                      'div',
                      { style: statLabelStyle },
                      [
                        'RPV',
                        helpTip(
                          'rpv',
                          'Revenue per Visitor is total revenue divided by total visitors. This is usually the best overall e-commerce test metric.'
                        ),
                      ]
                    ),
                    h('div', { style: statValueStyle }, currency(rpvA)),
                  ]),
                isRevenueGoal &&
                  h('div', null, [
                    h(
                      'div',
                      { style: statLabelStyle },
                      [
                        'Pred. Monthly Uplift',
                        helpTip(
                          'predicted-uplift-a',
                          'Estimates extra monthly revenue based on Revenue per Visitor (RPV) and the test’s observed visitor pace.'
                        ),
                      ]
                    ),
                    h(
                      'div',
                      { style: statValueStyle },
                      upliftDisplayA
                    ),
                  ]),
              ].filter(Boolean)
            ),
          ]),
          h('div', { style: cardStyle }, [
            h(
              'div',
              {
                style: {
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: '12px',
                  marginTop: 0,
                  marginBottom: '14px',
                },
              },
              [
                h(
                  'h2',
                  {
                    style: {
                      margin: 0,
                      fontSize: '16px',
                    },
                  },
                  'Version B'
                ),
                previewB
                  ? h(
                      'a',
                      {
                        href: previewB,
                        target: '_blank',
                        rel: 'noopener noreferrer',
                        style: {
                          color: '#2271b1',
                          textDecoration: 'none',
                          display: 'inline-flex',
                          alignItems: 'center',
                          gap: '4px',
                          fontSize: '13px',
                          fontWeight: '500',
                          whiteSpace: 'nowrap',
                          flex: '0 0 auto',
                        },
                        title: 'Preview Version B',
                      },
                      [
                        'Preview',
                        h('span', {
                          className: 'dashicons dashicons-external',
                          style: {
                            fontSize: '14px',
                            width: '14px',
                            height: '14px',
                          },
                        }),
                      ]
                    )
                  : null,
              ]
            ),
            h(
              'div',
              {
                style: {
                  display: 'grid',
                  gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
                  gap: '16px 18px',
                },
              },
              [
                h('div', null, [
                  h('div', { style: statLabelStyle }, 'Impressions'),
                  h('div', { style: statValueStyle }, String(totalImpB)),
                ]),
                h('div', null, [
                  h('div', { style: statLabelStyle }, isRevenueGoal ? 'Orders' : 'Conversions'),
                  h('div', { style: statValueStyle }, String(totalConvB)),
                ]),
                h('div', null, [
                  h(
                    'div',
                    { style: statLabelStyle },
                    [
                      isRevenueGoal ? 'Order Rate' : 'Conversion Rate',
                      helpTip(
                        'order-rate-b',
                        isRevenueGoal
                          ? 'Order Rate is the percentage of visitors who placed an order.'
                          : 'Conversion Rate is the percentage of visitors who completed the selected conversion goal.',
                        'left'
                      )
                    ]
                  ),
                  h('div', { style: statValueStyle }, `${rateB}%`),
                ]),
                isRevenueGoal &&
                  h('div', null, [
                    h(
                      'div',
                      { style: statLabelStyle },
                      [
                        'Revenue',
                        helpTip(
                          'revenue-b',
                          'Revenue is the total order value generated by this version.',
                          'left'
                        ),
                      ]
                    ),
                    h('div', { style: statValueStyle }, currency(totalRevenueB)),
                  ]),
                isRevenueGoal &&
                  h('div', null, [
                    h(
                      'div',
                      { style: statLabelStyle },
                      [
                        'RPC',
                        helpTip(
                          'rpc-b',
                          'Revenue per Customer is total revenue divided by the number of customers who ordered.',
                          'left'
                        ),
                      ]
                    ),
                    h('div', { style: statValueStyle }, currency(rpcB)),
                  ]),
                isRevenueGoal &&
                  h('div', null, [
                    h(
                      'div',
                      { style: statLabelStyle },
                      [
                        'RPV',
                        helpTip(
                          'rpv-b',
                          'Revenue per Visitor is total revenue divided by total visitors. This is usually the best overall e-commerce test metric.',
                          'left'
                        ),
                      ]
                    ),
                    h('div', { style: statValueStyle }, currency(rpvB)),
                  ]),
                isRevenueGoal &&
                  h('div', null, [
                    h(
                      'div',
                      { style: statLabelStyle },
                      [
                        'Pred. Monthly Uplift',
                        helpTip(
                          'predicted-uplift-b',
                          'Estimates extra monthly revenue based on Revenue per Visitor (RPV) and the test’s observed visitor pace.',
                          'left'
                        ),
                      ]
                    ),
                    h(
                      'div',
                      { style: statValueStyle },
                      upliftDisplayB
                    ),
                  ]),
              ].filter(Boolean)
            ),
          ]),
          ]
        ),

        h(
          'div',
          {
            key: 'range-switcher',
            style: {
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              marginBottom: '12px',
            },
          },
          [
            h('strong', null, 'Timeline:'),
            h(
              Button,
              {
                isPrimary: range === 'day',
                isSecondary: range !== 'day',
                onClick: () => changeRange('day'),
              },
              'Day'
            ),
            h(
              Button,
              {
                isPrimary: range === 'week',
                isSecondary: range !== 'week',
                onClick: () => changeRange('week'),
              },
              'Week'
            ),
            h(
              Button,
              {
                isPrimary: range === 'month',
                isSecondary: range !== 'month',
                onClick: () => changeRange('month'),
              },
              'Month'
            ),
          ]
        ),

        timeline.length === 0
          ? h(
              'div',
              {
                style: {
                  ...cardStyle,
                  textAlign: 'center',
                  color: '#6b7280',
                },
              },
              'No timeline data has been recorded for this test yet.'
            )
          : h(
              Fragment,
              null,
              [
                h(SimpleLineChart, {
                  title: 'Impressions over time',
                  labels,
                  seriesA: impressionSeriesA,
                  seriesB: impressionSeriesB,
                  yLabelA: 'A impressions',
                  yLabelB: 'B impressions',
                }),
                h(SimpleLineChart, {
                  title: isRevenueGoal ? 'Orders over time' : 'Conversions over time',
                  labels,
                  seriesA: conversionSeriesA,
                  seriesB: conversionSeriesB,
                  yLabelA: isRevenueGoal ? 'A orders' : 'A conversions',
                  yLabelB: isRevenueGoal ? 'B orders' : 'B conversions',
                }),
                isRevenueGoal &&
                  h(SimpleLineChart, {
                    title: 'Revenue over time',
                    labels,
                    seriesA: revenueSeriesA,
                    seriesB: revenueSeriesB,
                    yLabelA: 'A revenue',
                    yLabelB: 'B revenue',
                  }),
              ]
            ),

        timeline.length > 0 &&
          h(
            'div',
            {
              key: 'table-wrap',
              style: {
                marginTop: '16px',
                background: '#fff',
                border: '1px solid #dcdcde',
                borderRadius: '8px',
                overflow: 'hidden',
              },
            },
            [
              h(
                'div',
                {
                  style: {
                    padding: '12px 16px',
                    borderBottom: '1px solid #e5e7eb',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    gap: '12px',
                    flexWrap: 'wrap',
                  },
                },
                [
                  h(
                    'div',
                    {
                      style: {
                        fontWeight: '700',
                      },
                    },
                    'Timeline Breakdown'
                  ),
                  h(
                    'div',
                    {
                      style: {
                        display: 'flex',
                        alignItems: 'center',
                        gap: '10px',
                        flexWrap: 'wrap',
                        fontSize: '13px',
                      },
                    },
                    [
                      h(
                        'label',
                        {
                          htmlFor: 'abtestkit-rows-per-page',
                          style: {
                            color: '#50575e',
                            fontWeight: '600',
                          },
                        },
                        'Rows per page'
                      ),
                      h(
                        'select',
                        {
                          id: 'abtestkit-rows-per-page',
                          value: String(rowsPerPage),
                          onChange: (e) => {
                            setRowsPerPage(Number(e.target.value) || 10);
                            setCurrentPage(1);
                          },
                          style: {
                            minWidth: '72px',
                          },
                        },
                        [
                          h('option', { value: '10' }, '10'),
                          h('option', { value: '25' }, '25'),
                          h('option', { value: '50' }, '50'),
                        ]
                      ),
                    ]
                  ),
                ]
              ),
              h(
                Fragment,
                null,
                [
                  h(
                    'table',
                    {
                      className: 'widefat striped',
                      style: { border: 0, margin: 0 },
                    },
                    [
                      h(
                        'thead',
                        null,
                        h(
                          'tr',
                          null,
                          [
                            h('th', null, 'Period'),
                            h('th', null, 'A Impressions'),
                            h('th', null, 'B Impressions'),
                            h('th', null, isRevenueGoal ? 'A Orders' : 'A Conversions'),
                            h('th', null, isRevenueGoal ? 'B Orders' : 'B Conversions'),
                            isRevenueGoal && h('th', null, 'A Revenue'),
                            isRevenueGoal && h('th', null, 'B Revenue'),
                          ].filter(Boolean)
                        )
                      ),
                      h(
                        'tbody',
                        null,
                        paginatedTimeline.map((row) =>
                          h(
                            'tr',
                            { key: row.bucket },
                            [
                              h('td', null, formatBucketDate(row.bucket)),
                              h('td', null, String(((row.A || {}).impressions) || 0)),
                              h('td', null, String(((row.B || {}).impressions) || 0)),
                              h('td', null, String(((row.A || {})[conversionKey]) || 0)),
                              h('td', null, String(((row.B || {})[conversionKey]) || 0)),
                              isRevenueGoal && h('td', null, currency(((row.A || {}).revenue) || 0)),
                              isRevenueGoal && h('td', null, currency(((row.B || {}).revenue) || 0)),
                            ].filter(Boolean)
                          )
                        )
                      ),
                    ]
                  ),
                  h(
                    'div',
                    {
                      style: {
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        gap: '12px',
                        padding: '12px 16px',
                        borderTop: '1px solid #e5e7eb',
                        flexWrap: 'wrap',
                      },
                    },
                    [
                      h(
                        'div',
                        {
                          style: {
                            fontSize: '13px',
                            color: '#50575e',
                          },
                        },
                        `Showing ${totalTimelineRows === 0 ? 0 : startRow + 1}–${Math.min(endRow, totalTimelineRows)} of ${totalTimelineRows}`
                      ),
                      h(
                        'div',
                        {
                          style: {
                            display: 'flex',
                            alignItems: 'center',
                            gap: '8px',
                          },
                        },
                        [
                          h(
                            Button,
                            {
                              isSecondary: true,
                              disabled: safeCurrentPage <= 1,
                              onClick: () => setCurrentPage(Math.max(1, safeCurrentPage - 1)),
                            },
                            'Previous'
                          ),
                          h(
                            'span',
                            {
                              style: {
                                fontSize: '13px',
                                color: '#50575e',
                                minWidth: '72px',
                                textAlign: 'center',
                              },
                            },
                            `Page ${safeCurrentPage} of ${totalPages}`
                          ),
                          h(
                            Button,
                            {
                              isSecondary: true,
                              disabled: safeCurrentPage >= totalPages,
                              onClick: () => setCurrentPage(Math.min(totalPages, safeCurrentPage + 1)),
                            },
                            'Next'
                          ),
                        ]
                      ),
                    ]
                  ),
                ]
              ),
            ]
          ),
      ]
    );
  }

  document.addEventListener('DOMContentLoaded', function () {
    var root = document.getElementById('abtestkit-test-performance-root');
    if (!root) return;
    wp.element.render(h(PerformanceApp), root);
  });
})();