// Step 7 — Review & Launch: full summary, checklist, big launch CTA

const Step7Review = ({ draft, setDraft, onLaunch }) => {
  const { SectionTitle, BRANDS, COUNTRY_FLAGS, COUNTRY_NAMES, LOCALES, CopyableUrl, StatusPill } = window;

  // Build live URL
  const liveBase = draft.domain
    ? (draft.domain.startsWith('http') ? draft.domain : 'https://' + draft.domain)
    : '';
  const adUrl = liveBase ? `${liveBase}/?utm_source=facebook&utm_medium=paid&utm_campaign=${draft.id}_v1&fbclid={{ad.id}}` : '';

  // Checklist
  const checks = [
    { label: 'App named',              done: !!draft.name },
    { label: 'Type set',               done: !!draft.type },
    { label: 'Brand picked',           done: !!draft.brand },
    { label: 'At least one GEO',       done: draft.geos.length > 0 },
    { label: 'Default URL set',        done: !!draft.defaultUrl },
    { label: 'Domain assigned',        done: !!draft.domain, optional: true },
    { label: 'Meta Pixel ID',          done: !!draft.metaPixelId, optional: true },
    { label: 'At least one locale',    done: draft.locales.length > 0 },
  ];
  const required = checks.filter(c => !c.optional);
  const ready = required.every(c => c.done);

  return (
    <div className="step-anim">
      <SectionTitle
        kicker="Step 07 / 07"
        title="Review & launch"
        desc="Cross-check everything below. Hitting Launch writes the config to KV, deploys the Pages project, and goes live within ~60 seconds."
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20 }}>
        {/* Summary card */}
        <div>
          <div className="panel" style={{ padding: 24, marginBottom: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 22, paddingBottom: 20, borderBottom: '1px solid var(--line-soft)' }}>
              <div style={{
                width: 64, height: 64, borderRadius: 14,
                background: 'linear-gradient(135deg, #ff00ff 0%, #00ffff 100%)',
                display: 'grid', placeItems: 'center',
                fontSize: 32,
                boxShadow: '0 8px 22px -8px rgba(255,0,255,0.5)',
              }}>{draft.icon}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.01em' }}>{draft.name || 'Unnamed app'}</div>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>{draft.id}</div>
                <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
                  <span className="pill">{draft.type?.toUpperCase()}</span>
                  {draft.brand && (
                    <span className="pill" style={{ color: BRANDS[draft.brand]?.color, borderColor: `${BRANDS[draft.brand]?.color}40` }}>
                      {BRANDS[draft.brand]?.name}
                    </span>
                  )}
                  <StatusPill status={draft.status} enabled={draft.enabled} />
                </div>
              </div>
            </div>

            {/* Detail rows */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <DetailRow label="Domain">
                {draft.domain ? <code style={{ color: 'var(--accent)' }}>{draft.domain}</code> : <span style={{ color: 'var(--muted)' }}>Auto-assign on launch</span>}
              </DetailRow>

              <DetailRow label="GEO targeting">
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {draft.geos.length === 0 && <span style={{ color: 'var(--muted)' }}>None</span>}
                  {draft.geos.map(g => (
                    <span key={g} style={{
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                      padding: '3px 8px', background: 'var(--bg-3)', borderRadius: 6,
                      border: '1px solid var(--line)', fontSize: 11.5,
                    }}>
                      <span>{COUNTRY_FLAGS[g]}</span>
                      <span className="mono">{g}</span>
                    </span>
                  ))}
                </div>
              </DetailRow>

              <DetailRow label="Default URL">
                {draft.defaultUrl ? (
                  <CopyableUrl value={draft.defaultUrl} accent />
                ) : <span style={{ color: 'var(--danger)' }}>Not set</span>}
              </DetailRow>

              {draft.forceUrl && (
                <DetailRow label="Force URL">
                  <CopyableUrl value={draft.forceUrl} />
                </DetailRow>
              )}

              {draft.blockCountries?.length > 0 && (
                <DetailRow label="Blocked">
                  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                    {draft.blockCountries.map(c => (
                      <span key={c} className="pill paused" style={{ fontSize: 10 }}>{c}</span>
                    ))}
                  </div>
                </DetailRow>
              )}

              <DetailRow label="Languages">
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {draft.locales.map(l => (
                    <span key={l} className="pill" style={{ fontSize: 10, ...(l === draft.defaultLocale ? { color: 'var(--accent)', borderColor: 'var(--accent-line)' } : {}) }}>
                      {l === draft.defaultLocale ? '★ ' : ''}{l}
                    </span>
                  ))}
                </div>
              </DetailRow>

              <DetailRow label="Tracking">
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12 }}>
                  <TrackingRow label="Meta Pixel"  value={draft.metaPixelId} />
                  <TrackingRow label="OneSignal"   value={draft.oneSignalId} />
                  <TrackingRow label="GA4"         value={draft.gaId} />
                </div>
              </DetailRow>
            </div>
          </div>

          {/* Generated URLs */}
          {liveBase && (
            <div className="panel" style={{ padding: 22 }}>
              <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Generated URLs</div>

              <div style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 10.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600, marginBottom: 6 }}>Live URL</div>
                <CopyableUrl value={liveBase} accent />
              </div>

              <div>
                <div style={{ fontSize: 10.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600, marginBottom: 6 }}>FB Ads URL · with UTMs & click ID</div>
                <CopyableUrl value={adUrl} />
              </div>
            </div>
          )}
        </div>

        {/* Right rail — launch checklist */}
        <div>
          <div className="panel" style={{
            padding: 22,
            background: ready ? 'linear-gradient(180deg, rgba(0,208,132,0.05), transparent 70%) var(--bg-1)' : 'var(--bg-1)',
            borderColor: ready ? 'var(--accent-line)' : 'var(--line)',
            position: 'sticky', top: 88,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
              <window.IconRocket size={18} style={{ color: ready ? 'var(--accent)' : 'var(--muted)' }} />
              <div>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Launch checklist</div>
                <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{required.filter(c => c.done).length} / {required.length} required complete</div>
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 18 }}>
              {checks.map(c => (
                <div key={c.label} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5 }}>
                  <div style={{
                    width: 18, height: 18, borderRadius: '50%',
                    border: `1.5px solid ${c.done ? 'var(--accent)' : 'var(--line)'}`,
                    background: c.done ? 'var(--accent)' : 'transparent',
                    color: '#001a0c',
                    display: 'grid', placeItems: 'center',
                    flexShrink: 0,
                  }}>
                    {c.done && <window.IconCheck size={11} sw={3} />}
                  </div>
                  <span style={{
                    flex: 1,
                    color: c.done ? 'var(--text)' : 'var(--muted)',
                    textDecoration: c.done ? 'none' : 'none',
                  }}>{c.label}</span>
                  {c.optional && <span style={{ fontSize: 10, color: 'var(--muted-2)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>opt</span>}
                </div>
              ))}
            </div>

            <div style={{ paddingTop: 16, borderTop: '1px solid var(--line-soft)' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>Go live now</div>
                  <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>Worker starts routing in ~60s</div>
                </div>
                <window.Toggle on={draft.enabled} lg onChange={(v) => setDraft({ ...draft, enabled: v, status: v ? 'live' : 'deployed' })} />
              </div>

              <button
                className="btn primary lg"
                onClick={onLaunch}
                disabled={!ready}
                style={{
                  width: '100%', justifyContent: 'center',
                  opacity: ready ? 1 : 0.4,
                  cursor: ready ? 'pointer' : 'not-allowed',
                }}
              >
                <window.IconRocket size={15} />
                {draft._editing ? 'Save changes' : 'Launch app'}
              </button>
              <div style={{ fontSize: 11, color: 'var(--muted-2)', textAlign: 'center', marginTop: 8 }}>
                {ready ? 'All required checks pass' : 'Complete required steps to launch'}
              </div>
            </div>
          </div>

          {!draft._editing && (
            <div className="panel" style={{ padding: 18, marginTop: 14 }}>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 10, lineHeight: 1.6 }}>
                <strong style={{ color: 'var(--text)' }}>What happens on launch:</strong>
              </div>
              <ol style={{ fontSize: 12, color: 'var(--text-dim)', paddingLeft: 18, lineHeight: 1.75, listStyle: 'decimal' }}>
                <li>Config writes to Cloudflare KV</li>
                <li>Pages project provisions (~30s)</li>
                <li>Pixel + push IDs injected into HTML</li>
                <li>Locale JSONs uploaded to R2</li>
                <li>Worker cache flips, traffic flows</li>
              </ol>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const DetailRow = ({ label, children }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: 14, alignItems: 'flex-start' }}>
    <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, paddingTop: 4 }}>{label}</div>
    <div style={{ fontSize: 13 }}>{children}</div>
  </div>
);

const TrackingRow = ({ label, value }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
    <span style={{
      width: 6, height: 6, borderRadius: '50%',
      background: value ? 'var(--accent)' : 'var(--muted-2)',
    }}></span>
    <span style={{ color: 'var(--muted)', minWidth: 80 }}>{label}</span>
    {value ? (
      <code style={{ fontSize: 11, color: 'var(--text-dim)' }}>{value.length > 18 ? value.slice(0, 8) + '…' + value.slice(-8) : value}</code>
    ) : (
      <span style={{ color: 'var(--muted-2)', fontSize: 11.5 }}>not set</span>
    )}
  </div>
);

window.Step7Review = Step7Review;
