const RELEASES = {
  windows: { system: 'Windows', arch: 'x64', format: '.exe', label: 'Download for Windows', sizeLabel: 'Windows 10/11', file: 'https://pub-0b73be44d0724d409857418989a4c787.r2.dev/Trace_0.1.0_x64-setup.exe', name: 'Trace_0.1.0_x64-setup.exe' },
  macos: { system: 'macOS', arch: 'arm64', format: '.dmg', label: 'Coming soon for Mac', sizeLabel: 'Apple Silicon', file: null, name: null },
  linux: { system: 'Linux', arch: 'amd64', format: '.deb', label: 'Download for Linux', sizeLabel: 'Debian / Ubuntu', file: 'https://pub-0b73be44d0724d409857418989a4c787.r2.dev/Trace_0.1.0_amd64.deb', name: 'Trace_0.1.0_amd64.deb' },
};

function detectOS() {
  if (typeof navigator === 'undefined') return 'linux';
  const ua = navigator.userAgent || '', platform = navigator.platform || '';
  if (/Win/i.test(platform) || /Windows/i.test(ua)) return 'windows';
  if (/Mac/i.test(platform) || /Macintosh/i.test(ua)) return 'macos';
  return 'linux';
}

function CopyCommand({ command, t }) {
  const [copied, setCopied] = React.useState(false);
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(command);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch (_) {}
  };
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
      padding: '11px 12px 11px 14px', border: `1px solid ${t.hair}`, borderRadius: 10, background: t.panel2,
    }}>
      <code style={{ fontFamily: t.mono, fontSize: 11.5, color: t.ink, overflowWrap: 'anywhere' }}>{command}</code>
      <button onClick={copy} style={{
        padding: '6px 10px', border: 'none', borderRadius: 7, background: t.ink, color: '#fff',
        fontFamily: t.mono, fontSize: 9.5, cursor: 'pointer', flexShrink: 0,
      }}>{copied ? 'Copied ✓' : 'Copy'}</button>
    </div>
  );
}

const TraceFinalCTA = () => {
  const t = window.TRACE;
  const [os, setOs] = React.useState('linux');
  React.useEffect(() => { setOs(detectOS()); }, []);
  const r = RELEASES[os];

  return (
    <section id="download" className="trace-finalcta" style={{ padding: '40px 48px 120px', fontFamily: t.sans }}>
      <div style={{ maxWidth: 900, margin: '0 auto', textAlign: 'center' }}>
        <Eyebrow style={{ justifyContent: 'center', display: 'flex', marginBottom: 18 }}>Download</Eyebrow>
        <h2 style={{
          fontFamily: t.sans, fontSize: 'clamp(32px, 4.4vw, 54px)',
          letterSpacing: '-0.03em', fontWeight: 700, color: t.ink,
          margin: '0 0 16px', textWrap: 'balance',
        }}>
          Stop reconstructing your day.<br />Let it track itself.
        </h2>
        <p style={{ fontSize: 16, color: t.dim, maxWidth: 460, margin: '0 auto 36px' }}>
          Unsigned beta, available now for Windows and Linux. macOS is coming soon. On-device,
          private, and built for people who bill by the hour.
        </p>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, flexWrap: 'wrap', marginBottom: 20 }}>
          <a href={r.file || undefined} download={r.file ? r.name : undefined} aria-disabled={!r.file} onClick={r.file ? undefined : e => e.preventDefault()} style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            padding: '13px 24px', background: t.ink, color: '#fff',
            borderRadius: 999, fontSize: 13, fontWeight: 500, textDecoration: 'none',
          }}>{r.label}{r.file ? ' ↓' : ''}</a>
          <span style={{ fontSize: 12, color: t.faint }}>{r.sizeLabel}</span>
        </div>
      </div>

      <div style={{ maxWidth: 900, margin: '0 auto' }}>
        <div className="trace-platform-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 40 }}>
          {['windows', 'macos', 'linux'].map(key => {
            const rel = RELEASES[key];
            const active = key === os;
            return (
              <Card key={key} padding={22} style={{
                textAlign: 'left', background: active ? t.ink : t.panel,
                color: active ? '#fff' : t.ink, borderColor: active ? t.ink : t.hair,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
                  <Eyebrow color={active ? 'rgba(255,255,255,0.6)' : t.faint}>{rel.system}</Eyebrow>
                  <span style={{
                    fontFamily: t.mono, fontSize: 8.5, letterSpacing: '0.1em', textTransform: 'uppercase',
                    padding: '4px 7px', border: `1px solid ${active ? 'rgba(255,255,255,0.4)' : t.hair}`, borderRadius: 999,
                    opacity: 0.7,
                  }}>{rel.file ? 'Available' : 'Coming soon'}</span>
                </div>
                <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>{rel.sizeLabel.split(' · ')[0]}</div>
                <div style={{ fontSize: 12, opacity: 0.6, marginBottom: 18 }}>{rel.arch} · {rel.format}</div>
                <a href={rel.file || undefined} download={rel.file ? rel.name : undefined} aria-disabled={!rel.file} onClick={rel.file ? undefined : e => e.preventDefault()} style={{
                  fontSize: 11.5, fontWeight: 600, textDecoration: 'none',
                  color: active ? '#fff' : t.ink, borderBottom: `1px solid ${active ? 'rgba(255,255,255,0.4)' : t.hair}`,
                }}>{rel.file ? 'Get the beta ↓' : 'Coming soon'}</a>
              </Card>
            );
          })}
        </div>

        <Card padding={0} style={{ overflow: 'hidden', textAlign: 'left' }}>
          <div style={{ padding: '20px 26px', borderBottom: `1px solid ${t.hair}` }}>
            <Eyebrow style={{ marginBottom: 6 }}>Install</Eyebrow>
            <div style={{ fontSize: 14, color: t.dim }}>
              Windows: open the download and confirm the unsigned-app warning. Linux: verify, install, launch. macOS support is coming soon.
            </div>
          </div>
          <div style={{ padding: '22px 26px', display: 'grid', gap: 18 }}>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: t.ink, marginBottom: 8 }}>1. Verify what you downloaded</div>
              <CopyCommand t={t} command="sha256sum Trace_0.1.0_amd64.deb" />
            </div>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: t.ink, marginBottom: 8 }}>2. Install the package (Linux)</div>
              <CopyCommand t={t} command="sudo apt install ./Trace_0.1.0_amd64.deb" />
            </div>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: t.ink, marginBottom: 8 }}>3. Launch Trace</div>
              <CopyCommand t={t} command="trace" />
            </div>
          </div>
          <div style={{ padding: '14px 26px', borderTop: `1px solid ${t.hair}`, fontSize: 11.5, color: t.faint, fontFamily: t.mono }}>
            v0.1.0 · Windows x64 and Linux amd64 beta
          </div>
        </Card>
      </div>
    </section>
  );
};

window.TraceFinalCTA = TraceFinalCTA;
