import { ImageResponse } from 'next/og';

// A1 Session 10 · elevated DS4 — every shared /u/:handle link unfurls as a
// record card at social crop (1200×630). The billboard now carries the REAL
// record (hit%) when the handle is published + past the n-gate (Session 65
// removed beat-close% — see the un-claim note below),
// so the timeline (customer #1) sees the proof, not just a tagline. Self-hosted
// standalone build → Node runtime (NOT edge; Session-53 rule).
export const alt = 'VYNDR Public Ledger';
export const size = { width: 1200, height: 630 };
export const contentType = 'image/png';

const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000';

async function fetchRecord(handle: string): Promise<{ hit_pct: number | null; beat_close_pct: number | null; hits: number; misses: number; house: boolean } | null> {
  try {
    const r = await fetch(`${BACKEND_URL}/api/profiles/${encodeURIComponent(handle)}`, {
      headers: { Accept: 'application/json' },
      cache: 'no-store',
    });
    if (!r.ok) return null;
    const d = await r.json();
    const agg = d && d.aggregate;
    if (!agg || agg.hit_pct == null) return null;
    return { hit_pct: agg.hit_pct, beat_close_pct: agg.beat_close_pct ?? null, hits: agg.hits, misses: agg.misses, house: Boolean(d.house) };
  } catch {
    return null;
  }
}

export default async function Image({ params }: { params: Promise<{ handle: string }> }) {
  const { handle } = await params;
  const h = decodeURIComponent(handle || '').slice(0, 20).toLowerCase() || 'handle';
  const rec = await fetchRecord(h);
  return new ImageResponse(
    (
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
          width: '100%',
          height: '100%',
          background: '#06060B',
          color: '#F0F0F0',
          padding: 72,
          fontFamily: 'monospace',
        }}
      >
        <div style={{ display: 'flex', position: 'absolute', top: 0, left: 0, right: 0, height: 6, background: '#00D4A0' }} />
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <div style={{ display: 'flex', fontSize: 26, letterSpacing: '0.22em', color: '#00D4A0', fontWeight: 700 }}>
            {rec ? (rec.house ? 'VYNDR MODEL · PUBLIC RECORD' : 'SETTLED RECORD · 30D') : 'PUBLIC LEDGER'}
          </div>
          <div style={{ display: 'flex', fontSize: 72, fontWeight: 900, letterSpacing: '-0.02em', marginTop: 14, color: '#FFFFFF' }}>
            {rec?.house ? 'VYNDR MODEL' : `@${h}`}
          </div>
          {rec ? (
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 56, marginTop: 26 }}>
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                <div style={{ display: 'flex', fontSize: 128, fontWeight: 900, lineHeight: 1, color: '#00D4A0' }}>{rec.hit_pct}%</div>
                <div style={{ display: 'flex', fontSize: 22, letterSpacing: '0.14em', color: '#7A7A8E', marginTop: 8 }}>HIT RATE · {rec.hits}-{rec.misses}</div>
              </div>
              {/* Session 65 — the secondary close-beat figure was REMOVED from
                  this public share card. It rendered beat_close_pct, derived from
                  the legacy overwritable closing_line (C4 open: closing == locked
                  on ~95% of rows). Display removal only — the aggregate + its gate
                  in ledgerService are untouched. */}
            </div>
          ) : (
            <div style={{ display: 'flex', fontSize: 28, color: '#7A7A8E', marginTop: 20 }}>
              Every settled read · wins and misses · nothing curated
            </div>
          )}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', fontSize: 44, fontWeight: 900, letterSpacing: '0.08em' }}>
            <span style={{ color: '#FFFFFF' }}>VYND</span>
            <span style={{ color: '#00D4A0' }}>R</span>
          </div>
          <div style={{ display: 'flex', fontSize: 22, color: '#4A4A5E', letterSpacing: '0.12em' }}>
            NOTHING CURATED · NOTHING DELETED
          </div>
        </div>
      </div>
    ),
    { ...size },
  );
}
