import { ImageResponse } from 'next/og';
import type { NextRequest } from 'next/server';

/**
 * /u/[handle]/portrait (Wave 5A, D2) — the PORTRAIT share crop (1080×1350,
 * the 4:5 story/feed format from the design mockup). The square-crop OG
 * (opengraph-image.tsx, 1200×630) unfurls a link; this is the standalone
 * image you drop into a story or a partner deck.
 *
 * It reads the SAME /api/profiles/:handle payload — so the house handle
 * (`vyndr`) renders the real public model record, a published user handle
 * renders theirs, and anything else falls back to the tagline. NEVER a
 * fabricated number: no record past the n-gate → the tagline, not a zero.
 *
 * Self-hosted standalone build → Node runtime (NOT edge; Session-53 rule).
 */
export const dynamic = 'force-dynamic';

const SIZE = { width: 1080, height: 1350 };
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 async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ handle: string }> },
) {
  const { handle } = await params;
  const h = decodeURIComponent(handle || '').slice(0, 20).toLowerCase() || 'handle';
  const rec = await fetchRecord(h);
  const heading = rec?.house ? 'VYNDR MODEL' : `@${h}`;
  const eyebrow = rec ? (rec.house ? 'VYNDR MODEL · PUBLIC RECORD' : 'SETTLED RECORD · 30D') : 'PUBLIC LEDGER';

  return new ImageResponse(
    (
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
          width: '100%',
          height: '100%',
          background: '#06060B',
          color: '#F0F0F0',
          padding: 90,
          fontFamily: 'monospace',
        }}
      >
        <div style={{ display: 'flex', position: 'absolute', top: 0, left: 0, right: 0, height: 8, background: '#00D4A0' }} />
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <div style={{ display: 'flex', fontSize: 30, letterSpacing: '0.22em', color: '#00D4A0', fontWeight: 700 }}>
            {eyebrow}
          </div>
          <div style={{ display: 'flex', fontSize: 84, fontWeight: 900, letterSpacing: '-0.02em', marginTop: 18, color: '#FFFFFF' }}>
            {heading}
          </div>
        </div>

        {rec ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 44 }}>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <div style={{ display: 'flex', fontSize: 240, fontWeight: 900, lineHeight: 1, color: '#00D4A0' }}>{rec.hit_pct}%</div>
              <div style={{ display: 'flex', fontSize: 30, letterSpacing: '0.14em', color: '#7A7A8E', marginTop: 12 }}>HIT RATE · {rec.hits}-{rec.misses}</div>
            </div>
            {/* Session 65 — the close-beat figure was removed from the public
                portrait card (legacy C4 closing_line derivation). Display
                removal only; the data path is untouched. */}
          </div>
        ) : (
          <div style={{ display: 'flex', fontSize: 40, color: '#7A7A8E', lineHeight: 1.4 }}>
            Every settled read · wins and misses · nothing curated
          </div>
        )}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div style={{ display: 'flex', fontSize: 60, fontWeight: 900, letterSpacing: '0.08em' }}>
            <span style={{ color: '#FFFFFF' }}>VYND</span>
            <span style={{ color: '#00D4A0' }}>R</span>
          </div>
          <div style={{ display: 'flex', fontSize: 26, color: '#4A4A5E', letterSpacing: '0.12em' }}>
            NOTHING CURATED · NOTHING DELETED
          </div>
        </div>
      </div>
    ),
    { ...SIZE },
  );
}
