/* ═══════════════════════════════════════════════════════════════════
   MigPage.jsx — Migrations overview. v1.0.0 — ported from the Claude
   Design v2 package
   (_CLAUDE-DESIGN/_2026-06-12-v2-SaaS-Redesign/migrations-page.jsx) —
   port, not redesign. Action bar + active-migration card (host→host,
   9-stage rail, live --term-* log, throughput, counters) + recent
   migrations zebra table. Reuses Sessions 1–3 primitives via the app's
   namespaced ports: Seg ← WPSB.SeoTracker, Sparkline ← WPSB.SeoCharts,
   NoticeCard bare global, plus WPSB.MigCharts / WPSB.MigData
   (bare-global design refs rewritten to the namespaces — the only
   port delta in this file).
   Load order: THIRD of the five Mig modules.
   Registers: window.WPSB.MigPage = { MigrationsOverview,
   ActiveMigrationCard, ThroughputCard, RecentRow }.
   ═══════════════════════════════════════════════════════════════════ */
(function () {
const { useState: useStateMg } = React;
const tx = (k, v, f) => (window.WPSB && window.WPSB.t) ? window.WPSB.t(k, v, f) : (f != null ? f : k);
const { MigStatusChip, HostBreadcrumb, StepRail, LogConsole, CounterTile, RollbackManifest } = window.WPSB.MigCharts;
const { MIG_STEPS, ACTIVE, MIG_LOG, MIG_LOG_FAIL, MIG_RECENT, ROLLBACK } = window.WPSB.MigData;
const Seg = window.WPSB.SeoTracker.Seg;
const Sparkline = window.WPSB.SeoCharts.Sparkline;

/* ── active / in-progress migration card ──────────────────────────── */
function ThroughputCard({ data }) {
  return React.createElement('div', { className: 'wiz-card', style: { background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 'var(--sp-4)' } },
    React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 } },
      React.createElement('span', { className: 'wiz-eyebrow', style: { fontSize: '.56rem' } }, tx('page.migration.page.throughput', null, 'Throughput')),
      React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: '.62rem', color: 'var(--muted)' } }, tx('page.migration.page.unit_mbps', null, 'MB/s'))),
    React.createElement('div', { style: { display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8 } },
      React.createElement('span', { style: { fontFamily: 'var(--font-brand)', fontWeight: 'var(--fw-bold)', fontSize: '1.5rem', color: 'var(--text)', lineHeight: 1 } }, data[data.length - 1]),
      React.createElement(Sparkline, { data, w: 120, h: 34, color: 'var(--viz-1)', area: true })));
}

function ActiveMigrationCard({ state, onToast }) {
  const m = ACTIVE;
  const failedAt = 5;
  const current = state === 'failed' ? failedAt : m.current;
  const log = state === 'failed' ? MIG_LOG_FAIL : MIG_LOG;
  const live = state === 'running';
  const stepTitle = MIG_STEPS[current].title;
  const stageText = state === 'failed' ? tx('page.migration.page.stage_failed', { n: failedAt + 1, title: stepTitle }, 'Failed at stage {n} · {title} — rolled back')
                  : state === 'paused' ? tx('page.migration.page.stage_paused', { n: current + 1, title: stepTitle }, 'Paused at stage {n} · {title}')
                  : tx('page.migration.page.stage_running', { n: current + 1, total: MIG_STEPS.length, title: stepTitle }, 'Stage {n} of {total} · {title}');
  const statusKey = state === 'failed' ? 'failed' : state === 'paused' ? 'paused' : 'running';

  return React.createElement('div', { className: 'wiz-card', style: { background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-xl)', overflow: 'hidden', boxShadow: 'var(--shadow-md)' } },
    // header band
    React.createElement('div', { style: { padding: 'var(--sp-5) var(--sp-5) var(--sp-4)', borderBottom: '1px solid var(--border)' } },
      React.createElement('div', { style: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 'var(--sp-4)', flexWrap: 'wrap', marginBottom: 'var(--sp-4)' } },
        React.createElement('div', { style: { minWidth: 0 } },
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 'var(--sp-3)', flexWrap: 'wrap' } },
            React.createElement('span', { style: { fontFamily: 'var(--font-mono)', fontSize: '.8rem', color: 'var(--text)', fontWeight: 'var(--fw-mono)' } }, m.site),
            React.createElement(MigStatusChip, { status: statusKey })),
          React.createElement(HostBreadcrumb, { source: m.source, dest: m.dest })),
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 'var(--sp-3)', flexWrap: 'wrap' } },
          live && React.createElement('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: 'var(--font-mono)', fontSize: '.74rem', color: 'var(--muted)' } },
            React.createElement(WIcon, { name: 'clock', size: 14 }), m.eta),
          state === 'running' && React.createElement(React.Fragment, null,
            React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-secondary wiz-focusable', style: { fontSize: '.72rem', padding: '7px 13px' }, onClick: () => onToast({ kind: 'success', text: tx('page.migration.page.toast_paused', null, 'Migration paused — safe to resume or roll back.') }) },
              React.createElement(WIcon, { name: 'pause', size: 13 }), tx('page.migration.page.pause', null, 'Pause')),
            React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-ghost wiz-focusable', style: { fontSize: '.72rem', padding: '7px 13px', color: 'var(--red)' }, onClick: () => onToast({ kind: 'upsell', text: tx('page.migration.page.toast_abort', null, 'Abort — confirm to roll back both sides.') }) }, tx('page.migration.page.abort', null, 'Abort'))),
          state === 'paused' && React.createElement(React.Fragment, null,
            React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-primary wiz-focusable', style: { fontSize: '.72rem', padding: '7px 13px' }, onClick: () => onToast({ kind: 'success', text: tx('page.migration.page.toast_resuming', null, 'Resuming migration…') }) },
              React.createElement(WIcon, { name: 'play', size: 13 }), tx('page.migration.page.resume', null, 'Resume')),
            React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-ghost wiz-focusable', style: { fontSize: '.72rem', padding: '7px 13px', color: 'var(--red)' }, onClick: () => onToast({ kind: 'upsell', text: tx('page.migration.page.toast_abort', null, 'Abort — confirm to roll back both sides.') }) }, tx('page.migration.page.abort', null, 'Abort'))),
          state === 'failed' && React.createElement(React.Fragment, null,
            React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-primary wiz-focusable', style: { fontSize: '.72rem', padding: '7px 13px' }, onClick: () => onToast({ kind: 'success', text: tx('page.migration.page.toast_retrying', null, 'Retrying migration from last safe stage…') }) },
              React.createElement(WIcon, { name: 'rotate-ccw', size: 13 }), tx('page.migration.page.retry', null, 'Retry')),
            React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-secondary wiz-focusable', style: { fontSize: '.72rem', padding: '7px 13px' }, onClick: () => onToast({ kind: 'success', text: tx('page.migration.page.toast_downloading_log', null, 'Downloading full migration log…') }) },
              React.createElement(WIcon, { name: 'download', size: 13 }), tx('page.migration.page.log', null, 'Log'))))),
      // stage line + rail
      React.createElement('div', { style: { fontFamily: 'var(--font-mono)', fontSize: '.72rem', color: state === 'failed' ? 'var(--red)' : state === 'paused' ? 'var(--warn)' : 'var(--beam)', marginBottom: 'var(--sp-4)', fontWeight: 'var(--fw-mono-small)' } }, stageText),
      React.createElement(StepRail, { steps: MIG_STEPS, current, state: statusKey })),

    // body
    React.createElement('div', { style: { padding: 'var(--sp-5)', display: 'flex', flexDirection: 'column', gap: 'var(--sp-5)' } },
      // state notice (paused / failed)
      state === 'paused' && React.createElement(window.NoticeCard, { accent: 'var(--warn)', icon: 'pause', title: tx('page.migration.page.notice_paused_title', null, 'Migration paused'),
        body: tx('page.migration.page.notice_paused_body', null, 'The destination is in a consistent state. Resume to continue from stage 5, or roll back both sides from the manifest below.'), tag: tx('page.migration.page.tag_safe', null, 'Safe') }),
      state === 'failed' && React.createElement(window.NoticeCard, { accent: 'var(--red)', icon: 'alert-triangle', title: tx('page.migration.page.notice_failed_title', null, 'Migration failed — automatically rolled back'),
        body: tx('page.migration.page.notice_failed_body', null, 'Media sync hit the destination disk quota at stage 6. Both sides were restored to their pre-migration state, so the live site was never touched.'), tag: tx('page.migration.page.tag_no_data_lost', null, 'No data lost') }),
      // log + side column
      React.createElement('div', { style: { display: 'flex', gap: 'var(--sp-5)', flexWrap: 'wrap', alignItems: 'stretch' } },
        React.createElement('div', { style: { flex: '1.6 1 340px', minWidth: 300 } },
          React.createElement(LogConsole, { lines: log, live, height: 250 })),
        React.createElement('div', { style: { flex: '1 1 240px', minWidth: 220, display: 'flex', flexDirection: 'column', gap: 'var(--sp-3)' } },
          live && React.createElement(ThroughputCard, { data: m.throughput }),
          React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--sp-3)' } },
            m.counters.map(c => React.createElement(CounterTile, { key: c.key, icon: c.icon, label: c.label, value: c.value, color: c.color, warn: c.warn }))))),
      // rollback manifest (paused / failed)
      (state === 'paused' || state === 'failed') && React.createElement(RollbackManifest, { rows: ROLLBACK, onToast, tone: state === 'failed' ? 'err' : 'warn' }))
  );
}

/* ── recent migrations zebra table ────────────────────────────────── */
const MR_COLS = 'minmax(150px,1.4fr) minmax(180px,1.3fr) 100px 92px 132px 78px';
function RecentHead() {
  return React.createElement('div', { style: { display: 'grid', gridTemplateColumns: MR_COLS, gap: 'var(--sp-3)', minWidth: 840,
    padding: '11px var(--sp-5)', background: 'var(--surface-2)', borderBottom: '1px solid var(--border)' } },
    [tx('page.migration.page.col_site', null, 'Site'), tx('page.migration.page.col_route', null, 'Route'), tx('page.migration.page.col_duration', null, 'Duration'), tx('page.migration.page.col_files', null, 'Files'), tx('page.migration.page.col_status', null, 'Status'), tx('page.migration.page.col_date', null, 'Date')].map((h, i) => React.createElement('span', { key: i, className: 'wiz-eyebrow', style: { fontSize: '.56rem', letterSpacing: '.1em' } }, h)));
}
function RecentRow({ row, idx }) {
  const [hover, setHover] = useStateMg(false);
  const zebra = idx % 2 === 1;
  const bg = hover ? 'var(--surface-3)' : (zebra ? 'var(--surface-2)' : 'var(--surface)');
  const cell = { display: 'flex', alignItems: 'center', minWidth: 0 };
  const mono = { fontFamily: 'var(--font-mono)', fontSize: '.78rem', color: 'var(--text-2)' };
  return React.createElement('div', { onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),
    style: { display: 'grid', gridTemplateColumns: MR_COLS, gap: 'var(--sp-3)', minWidth: 840, alignItems: 'center', padding: '12px var(--sp-5)', background: bg, borderBottom: '1px solid var(--border)' } },
    React.createElement('div', { style: { ...cell, gap: 9 } },
      React.createElement('span', { style: { width: 26, height: 26, borderRadius: 'var(--r-sm)', flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--surface-3)', color: 'var(--muted)', border: '1px solid var(--border)' } }, React.createElement(WIcon, { name: 'globe', size: 13 })),
      React.createElement('span', { style: { fontWeight: 'var(--fw-medium)', fontSize: '.85rem', color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, row.site)),
    React.createElement('div', { style: { ...cell, gap: 7 } },
      React.createElement('span', { style: mono }, row.from),
      React.createElement('span', { style: { color: 'var(--dim)', display: 'flex', flex: 'none' } }, React.createElement(WIcon, { name: 'arrow-right', size: 13 })),
      React.createElement('span', { style: { ...mono, color: 'var(--text)' } }, row.to)),
    React.createElement('div', { style: cell }, React.createElement('span', { style: mono }, row.dur)),
    React.createElement('div', { style: cell }, React.createElement('span', { style: mono }, row.files)),
    React.createElement('div', { style: cell }, React.createElement(MigStatusChip, { status: row.status, size: 'sm' })),
    React.createElement('div', { style: cell }, React.createElement('span', { style: { ...mono, color: 'var(--muted)' } }, row.date)));
}

function MigrationsOverview({ filter, setFilter, migStatus, onNew, onToast }) {
  const showActive = filter === 'progress';
  const rows = filter === 'completed' ? MIG_RECENT.filter(r => r.status === 'completed')
            : filter === 'scheduled' ? []
            : MIG_RECENT;
  return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 'var(--sp-5)' } },
    // header
    React.createElement('div', { style: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 'var(--sp-4)', flexWrap: 'wrap' } },
      React.createElement('div', null,
        React.createElement('div', { className: 'wiz-eyebrow', style: { marginBottom: 6 } }, tx('page.migration.page.eyebrow', null, 'Overview · Migrations')),
        React.createElement('h1', { className: 'wiz-title', style: { margin: 0, fontSize: '1.6rem' } }, tx('page.migration.page.title', null, 'Migrations')),
        React.createElement('p', { style: { margin: '6px 0 0', color: 'var(--text-2)', fontSize: '.9rem' } }, tx('page.migration.page.subtitle', null, 'Move WordPress sites host-to-host — with snapshots, dry runs, and dual-side rollback'))),
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 'var(--sp-3)', flexWrap: 'wrap' } },
        React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-tool wiz-focusable', style: { fontSize: '.74rem' }, onClick: () => onToast({ kind: 'success', text: tx('page.migration.page.toast_syncing', null, 'Syncing migration status from all hosts…') }) },
          React.createElement(WIcon, { name: 'refresh', size: 14 }), tx('page.migration.page.sync_status', null, 'Sync status')),
        React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-primary wiz-focusable', style: { fontSize: '.74rem' }, onClick: onNew },
          React.createElement(WIcon, { name: 'plus', size: 15 }), tx('page.migration.page.new_migration', null, 'New migration')))),

    // status segmented
    React.createElement(Seg, { options: [{ key: 'progress', label: tx('page.migration.page.seg_progress', null, 'In progress') }, { key: 'scheduled', label: tx('page.migration.page.seg_scheduled', null, 'Scheduled') }, { key: 'completed', label: tx('page.migration.page.seg_completed', null, 'Completed') }], value: filter, onChange: setFilter }),

    // active migration
    showActive && React.createElement(ActiveMigrationCard, { state: migStatus, onToast }),

    // recent migrations table
    React.createElement('div', { className: 'wiz-card', style: { background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-xl)', overflow: 'hidden' } },
      React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--sp-4)', flexWrap: 'wrap', padding: 'var(--sp-5) var(--sp-5) var(--sp-4)' } },
        React.createElement('div', null,
          React.createElement('div', { style: { fontWeight: 'var(--fw-label)', fontSize: '1rem', color: 'var(--text)' } }, filter === 'scheduled' ? tx('page.migration.page.table_title_scheduled', null, 'Scheduled migrations') : tx('page.migration.page.table_title_recent', null, 'Recent migrations')),
          React.createElement('div', { style: { fontFamily: 'var(--font-mono)', fontSize: '.72rem', color: 'var(--muted)', marginTop: 3 } }, rows.length === 1 ? tx('page.migration.page.count_one', { n: rows.length }, '{n} migration · last 30 days') : tx('page.migration.page.count_many', { n: rows.length }, '{n} migrations · last 30 days'))),
        React.createElement('button', { type: 'button', className: 'wiz-btn wiz-btn-tool wiz-focusable', style: { fontSize: '.74rem' }, onClick: () => onToast({ kind: 'success', text: tx('page.migration.page.toast_exporting', null, 'Exporting migration history (CSV)…') }) },
          React.createElement(WIcon, { name: 'download', size: 14 }), tx('common.export', null, 'Export'))),
      React.createElement('div', { style: { overflowX: 'auto' } },
        React.createElement(RecentHead),
        rows.length
          ? React.createElement('div', null, rows.map((r, i) => React.createElement(RecentRow, { key: i, row: r, idx: i })))
          : React.createElement('div', { style: { padding: 'var(--sp-7)', textAlign: 'center', color: 'var(--muted)', fontSize: '.86rem' } }, tx('page.migration.page.empty_scheduled', null, 'No scheduled migrations. Use “New migration” to plan one.'))))
  );
}

window.WPSB = window.WPSB || {};
window.WPSB.MigPage = { MigrationsOverview, ActiveMigrationCard, ThroughputCard, RecentRow };
console.log('[WPSB] MigPage v1.0.0 loaded');
})();
