/* Dwarf — encode/compress workflow */

const DWARF_JOBS = [
  { id: 'd_001', name: 'cam-04 / east-perimeter / 2026-01-15.mp4', input: '14.0 GB', output: '364 MB', ratio: 38.4, status: 'ready', psnr: 42.1, time: '8m 12s', gpu: 'A100' },
  { id: 'd_002', name: 'cam-12 / north-gate / 2026-01-15.mp4', input: '12.6 GB', output: '316 MB', ratio: 39.8, status: 'ready', psnr: 41.8, time: '7m 24s', gpu: 'A100' },
  { id: 'd_003', name: 'sports-broadcast-2025-finals.mkv', input: '88.4 GB', output: '—', ratio: null, status: 'encoding', progress: 0.42, psnr: null, time: 'eta 18m', gpu: 'A100×4' },
  { id: 'd_004', name: 'cam-07 / parking-lot / 2026-01-15.mp4', input: '11.2 GB', output: '—', ratio: null, status: 'queued', progress: 0, psnr: null, time: '—', gpu: '—' },
  { id: 'd_005', name: 'product-launch-keynote.mp4', input: '4.2 GB', output: '108 MB', ratio: 38.9, status: 'ready', psnr: 43.2, time: '2m 41s', gpu: 'A100' },
];

function DwarfPage() {
  const [tab, setTab] = React.useState('encode');
  const [config, setConfig] = React.useState({
    bitrate: 800,
    gop: 32,
    preset: 'balanced',
    container: 'dwarf',
    decoderTarget: 'mp4',
    multiGpu: true,
    hwAccel: true,
  });

  return (
    <div className="page-content">
      <div className="page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span className="badge badge-accent">DCVC-RT</span>
            <span className="badge badge-neutral">PROPRIETARY</span>
          </div>
          <h1 className="page-title">Dwarf</h1>
          <p className="page-subtitle">
            Neural video compression. Encode video into <span className="mono" style={{ background: 'var(--bg-inset)', padding: '1px 6px', borderRadius: 3, fontSize: 12 }}>.dwarf</span> at 30–40× compression with perceptual quality intact.
          </p>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-secondary"><Icon.Book size={14} /> Encode docs</button>
          <button className="btn btn-primary"><Icon.Plus size={14} /> New encode job</button>
        </div>
      </div>

      {/* Hero stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 24 }}>
        {[
          { label: 'Avg compression', val: '38.4×', sub: 'lossless target', accent: true },
          { label: 'Avg PSNR', val: '42.1 dB', sub: 'visually lossless' },
          { label: 'Encode throughput', val: '6.2 hrs/min', sub: 'on A100×4' },
          { label: 'Storage saved (30d)', val: '186 TB', sub: '$3,422 / mo' },
        ].map((s, i) => (
          <div key={i} className="card card-padded">
            <div className="eyebrow">{s.label}</div>
            <div className="mono" style={{ fontSize: 26, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 8, color: s.accent ? 'var(--accent)' : 'var(--text-primary)' }}>
              {s.val}
            </div>
            <div style={{ marginTop: 6, fontSize: 11, color: 'var(--text-tertiary)' }}>{s.sub}</div>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div style={{ borderBottom: '1px solid var(--border-default)', marginBottom: 24, display: 'flex', gap: 4 }}>
        {[
          { id: 'encode', label: 'Encode', icon: 'Compress' },
          { id: 'jobs', label: `Jobs · ${DWARF_JOBS.length}`, icon: 'Activity' },
          { id: 'compare', label: 'Quality compare', icon: 'Layers' },
        ].map(t => {
          const Comp = Icon[t.icon];
          return (
            <button key={t.id} onClick={() => setTab(t.id)}
              style={{
                padding: '12px 14px',
                fontSize: 13, color: tab === t.id ? 'var(--text-primary)' : 'var(--text-secondary)',
                fontWeight: tab === t.id ? 500 : 400,
                borderBottom: `2px solid ${tab === t.id ? 'var(--accent)' : 'transparent'}`,
                marginBottom: -1,
                display: 'flex', alignItems: 'center', gap: 6,
              }}>
              <Comp size={13} /> {t.label}
            </button>
          );
        })}
      </div>

      {tab === 'encode' && <EncodeBuilder config={config} setConfig={setConfig} />}
      {tab === 'jobs' && <DwarfJobs />}
      {tab === 'compare' && <QualityCompare />}
    </div>
  );
}

function EncodeBuilder({ config, setConfig }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20, alignItems: 'start' }}>
      <div className="card card-padded">
        <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 16px' }}>Source</h3>

        <div style={{
          border: '2px dashed var(--border-default)', borderRadius: 'var(--radius-lg)',
          padding: '32px 24px', textAlign: 'center', cursor: 'pointer',
          background: 'var(--bg-inset)', marginBottom: 16,
        }}>
          <Icon.Upload size={24} color="var(--text-tertiary)" />
          <div style={{ marginTop: 10, fontSize: 13, fontWeight: 500 }}>Upload video files</div>
          <div style={{ marginTop: 4, fontSize: 11, color: 'var(--text-tertiary)' }}>
            MP4, MKV, MOV, Y4M · or paste storage URLs
          </div>
        </div>

        <h3 style={{ fontSize: 14, fontWeight: 600, margin: '24px 0 16px' }}>Configuration</h3>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          {/* Preset */}
          <div style={{ gridColumn: '1 / -1' }}>
            <label className="label">Encoding preset</label>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
              {[
                { id: 'fast', name: 'Fast', sub: '~25× · faster' },
                { id: 'balanced', name: 'Balanced', sub: '~38× · default' },
                { id: 'quality', name: 'Quality', sub: '~42× · slower' },
              ].map(p => (
                <button key={p.id} onClick={() => setConfig({ ...config, preset: p.id })}
                  style={{
                    padding: 10, textAlign: 'center',
                    border: `1px solid ${config.preset === p.id ? 'var(--accent)' : 'var(--border-default)'}`,
                    background: config.preset === p.id ? 'var(--accent-subtle)' : 'var(--bg-surface)',
                    borderRadius: 'var(--radius-md)',
                  }}>
                  <div style={{ fontSize: 12, fontWeight: 500, color: config.preset === p.id ? 'var(--accent-text)' : 'var(--text-primary)' }}>{p.name}</div>
                  <div style={{ fontSize: 10, color: 'var(--text-tertiary)', marginTop: 2 }}>{p.sub}</div>
                </button>
              ))}
            </div>
          </div>

          {/* Bitrate */}
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
              <label className="label" style={{ marginBottom: 0 }}>Target bitrate</label>
              <span className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>{config.bitrate} kbps</span>
            </div>
            <input type="range" min="200" max="3000" step="100"
              value={config.bitrate}
              onChange={(e) => setConfig({ ...config, bitrate: +e.target.value })}
              style={{ accentColor: 'var(--accent)' }} />
          </div>

          {/* GOP */}
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
              <label className="label" style={{ marginBottom: 0 }}>GOP size</label>
              <span className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>{config.gop} frames</span>
            </div>
            <input type="range" min="8" max="128" step="8"
              value={config.gop}
              onChange={(e) => setConfig({ ...config, gop: +e.target.value })}
              style={{ accentColor: 'var(--accent)' }} />
          </div>

          {/* Decoder target */}
          <div>
            <label className="label">Decode output</label>
            <select className="input" value={config.decoderTarget}
              onChange={(e) => setConfig({ ...config, decoderTarget: e.target.value })}>
              <option value="mp4">MP4 (H.264)</option>
              <option value="mkv">MKV (H.265)</option>
              <option value="y4m">Y4M (raw)</option>
              <option value="none">No decode (.dwarf only)</option>
            </select>
          </div>

          <div>
            <label className="label">Container</label>
            <select className="input" value={config.container}
              onChange={(e) => setConfig({ ...config, container: e.target.value })}>
              <option value="dwarf">.dwarf (default)</option>
              <option value="dwarf-stream">.dwarf streaming index</option>
            </select>
          </div>

          {/* Toggles */}
          <div style={{ gridColumn: '1 / -1', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 4 }}>
            <Toggle label="Multi-GPU distribution"
              sub="Split GOPs across available GPUs"
              checked={config.multiGpu}
              onChange={(v) => setConfig({ ...config, multiGpu: v })} />
            <Toggle label="NVENC hardware acceleration"
              sub="Use FFmpeg + NVENC for transcode"
              checked={config.hwAccel}
              onChange={(v) => setConfig({ ...config, hwAccel: v })} />
          </div>
        </div>
      </div>

      {/* Preview / CLI */}
      <div style={{ position: 'sticky', top: 80, display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div className="card">
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span className="eyebrow">Estimated output</span>
            <Icon.Cpu size={13} color="var(--text-tertiary)" />
          </div>
          <div style={{ padding: 18 }}>
            {[
              ['Compression ratio', config.preset === 'fast' ? '~25×' : config.preset === 'quality' ? '~42×' : '~38×'],
              ['Output size (per 1 GB)', config.preset === 'fast' ? '~40 MB' : config.preset === 'quality' ? '~24 MB' : '~26 MB'],
              ['Predicted PSNR', config.preset === 'fast' ? '40.2 dB' : config.preset === 'quality' ? '43.6 dB' : '42.1 dB'],
              ['Encode time (per hr video)', config.preset === 'fast' ? '4 min' : config.preset === 'quality' ? '14 min' : '8 min'],
              ['Cost', '~12 credits / hr'],
            ].map(([k, v], i) => (
              <div key={i} style={{
                display: 'flex', justifyContent: 'space-between',
                padding: '8px 0', fontSize: 12,
                borderTop: i > 0 ? '1px solid var(--border-subtle)' : 'none',
              }}>
                <span style={{ color: 'var(--text-secondary)' }}>{k}</span>
                <span className="mono" style={{ color: 'var(--text-primary)', fontWeight: 500 }}>{v}</span>
              </div>
            ))}
          </div>
        </div>

        {/* CLI */}
        <div className="card" style={{ overflow: 'hidden' }}>
          <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span className="eyebrow">CLI equivalent</span>
            <button className="btn btn-ghost btn-sm"><Icon.Copy size={12} /></button>
          </div>
          <pre style={{
            padding: 16, margin: 0,
            background: 'var(--bg-code)',
            fontFamily: 'var(--font-mono)', fontSize: 11.5,
            color: 'var(--text-primary)', lineHeight: 1.7,
            overflowX: 'auto', whiteSpace: 'pre-wrap',
          }}>
{`dwarf-encode \\
  --input source.mp4 \\
  --output source.dwarf \\
  --preset ${config.preset} \\
  --bitrate ${config.bitrate} \\
  --gop ${config.gop} \\
${config.multiGpu ? '  --multi-gpu \\\n' : ''}${config.hwAccel ? '  --nvenc \\\n' : ''}  --decode-to ${config.decoderTarget}`}
          </pre>
        </div>

        <button className="btn btn-primary btn-lg" style={{ width: '100%' }}>
          <Icon.Compress size={14} /> Start encoding
        </button>
      </div>
    </div>
  );
}

function Toggle({ label, sub, checked, onChange }) {
  return (
    <button onClick={() => onChange(!checked)}
      style={{
        display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 12px',
        border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)',
        background: 'var(--bg-surface)', textAlign: 'left',
      }}>
      <div style={{
        width: 28, height: 16, borderRadius: 8,
        background: checked ? 'var(--accent)' : 'var(--border-strong)',
        position: 'relative', flexShrink: 0, marginTop: 2,
        transition: 'background var(--duration-fast)',
      }}>
        <div style={{
          position: 'absolute', top: 2, left: checked ? 14 : 2, width: 12, height: 12,
          borderRadius: '50%', background: 'white',
          transition: 'left var(--duration-fast) var(--ease-out)',
        }} />
      </div>
      <div>
        <div style={{ fontSize: 12, fontWeight: 500 }}>{label}</div>
        {sub && <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>{sub}</div>}
      </div>
    </button>
  );
}

function DwarfJobs() {
  return (
    <div className="card">
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 90px 90px 80px 100px 110px 80px 30px',
        gap: 12, padding: '12px 20px',
        borderBottom: '1px solid var(--border-default)', background: 'var(--bg-inset)',
      }}>
        {['File', 'Input', 'Output', 'Ratio', 'PSNR', 'Status', 'Time', ''].map((h, i) => (
          <span key={i} className="eyebrow" style={{ fontSize: 10 }}>{h}</span>
        ))}
      </div>
      {DWARF_JOBS.map((j, i) => (
        <div key={j.id} style={{
          display: 'grid', gridTemplateColumns: '1fr 90px 90px 80px 100px 110px 80px 30px',
          gap: 12, padding: '14px 20px', alignItems: 'center',
          borderBottom: i < DWARF_JOBS.length - 1 ? '1px solid var(--border-subtle)' : 'none',
        }}>
          <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{j.name}</span>
          <span className="mono" style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{j.input}</span>
          <span className="mono" style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{j.output}</span>
          {j.ratio
            ? <span className="badge badge-accent">{j.ratio}×</span>
            : <span className="badge badge-neutral">—</span>}
          <span className="mono" style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{j.psnr ? j.psnr + ' dB' : '—'}</span>
          <StatusPill status={j.status} progress={j.progress} />
          <span className="mono" style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{j.time}</span>
          <Icon.More size={14} color="var(--text-tertiary)" />
        </div>
      ))}
    </div>
  );
}

function QualityCompare() {
  const [hover, setHover] = React.useState(50);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: 20, alignItems: 'start' }}>
      <div className="card">
        <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span className="eyebrow">Frame 14,228 · cam-04 / east-perimeter</span>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn-secondary btn-sm">Original</button>
            <button className="btn btn-ghost btn-sm">H.265</button>
            <button className="btn btn-ghost btn-sm">.dwarf</button>
          </div>
        </div>
        {/* Slider compare */}
        <div onMouseMove={(e) => {
          const r = e.currentTarget.getBoundingClientRect();
          setHover(Math.min(100, Math.max(0, ((e.clientX - r.left) / r.width) * 100)));
        }}
          style={{
            position: 'relative', aspectRatio: '16 / 9', overflow: 'hidden',
            background: 'linear-gradient(135deg, #1e1e1c, #3c3a36)',
            cursor: 'ew-resize',
          }}>
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 60% 50%, rgba(255, 200, 150, 0.15), transparent 50%)' }} />
          {/* Right side overlay (simulated artifact) */}
          <div style={{
            position: 'absolute', top: 0, right: 0, bottom: 0, left: `${hover}%`,
            background: 'linear-gradient(135deg, #1e1e1c, #3c3a36)',
            backgroundImage: `radial-gradient(circle at 60% 50%, rgba(255, 200, 150, 0.13), transparent 50%), repeating-linear-gradient(45deg, rgba(255,255,255,0.02) 0 2px, transparent 2px 4px)`,
          }} />
          {/* Divider */}
          <div style={{
            position: 'absolute', top: 0, bottom: 0, left: `${hover}%`,
            width: 2, background: 'var(--accent)',
          }}>
            <div style={{
              position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
              width: 32, height: 32, borderRadius: '50%', background: 'var(--accent)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon.ChevronLeft size={12} color="white" />
              <Icon.ChevronRight size={12} color="white" style={{ marginLeft: -4 }} />
            </div>
          </div>
          {/* Labels */}
          <div style={{ position: 'absolute', top: 12, left: 12, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'white', background: 'rgba(0,0,0,0.7)', padding: '4px 8px', borderRadius: 3 }}>
            ORIGINAL · 14.0 GB · H.265
          </div>
          <div style={{ position: 'absolute', top: 12, right: 12, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'white', background: 'var(--accent)', padding: '4px 8px', borderRadius: 3 }}>
            .DWARF · 364 MB · 38.4×
          </div>
        </div>
      </div>

      <div className="card">
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border-subtle)' }}>
          <span className="eyebrow">Quality metrics</span>
        </div>
        <div style={{ padding: 18 }}>
          {[
            ['File size', '14.0 GB', '364 MB', 'var(--accent)'],
            ['Bitrate', '3,840 kbps', '98 kbps'],
            ['PSNR', '∞', '42.1 dB'],
            ['SSIM', '1.000', '0.987'],
            ['VMAF', '100.0', '94.2'],
            ['Decode FPS', '120', '86'],
          ].map(([k, a, b, color], i) => (
            <div key={i} style={{ padding: '10px 0', borderTop: i > 0 ? '1px solid var(--border-subtle)' : 'none' }}>
              <div className="eyebrow" style={{ fontSize: 9, marginBottom: 4 }}>{k}</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, fontFamily: 'var(--font-mono)' }}>
                <span style={{ color: 'var(--text-tertiary)' }}>{a}</span>
                <span style={{ color: color || 'var(--text-primary)', fontWeight: 500 }}>→ {b}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DwarfPage });
