'use client';

import {
  STATES,
  deriveValueState,
  valueStateColor,
  modelVsFair,
  fmtOddsAmerican,
  TAKEABLE_ODDS_CEILING,
  TAKEABLE_ODDS_MAX,
} from '@/lib/valueState';

/**
 * PriceTriplet (Session 66) — BOOK · FAIR · MODEL.
 *
 * The first component built natively on the price-layer tokens. Extends the
 * parlay's TRUE FAIR VALUE language from a 2-up grid to a 3-leg per-prop grid.
 *
 * DESIGN: `specs/design-reference/Vyndr Price Triplet.dc.html` (ACT 01) +
 * HANDOFF.md laws. Every colour resolves from a token — no literal hex.
 *
 *   BOOK   the market's offered price. Honest on every row.
 *   FAIR   the de-vigged number. THE HERO (amber). Never hidden — not even
 *          when the model leg is poisoned, and never the paywall.
 *   MODEL  VYNDR's own price. Green ONLY for takeable edge, never a juiced
 *          one. Suppressible on quarantined rows, lockable on free.
 *
 * LIVE DATA ONLY. The design file's numbers (+125 / +110 / +98) are a SPEC,
 * not data — nothing here carries a sample value. A leg with no real number
 * renders absent (a dash), never a zero and never a placeholder.
 *
 * The verdict is NOT computed here: `deriveValueState` owns it so there is one
 * place where "is this value?" is answered. This component only renders it.
 */

export interface PriceTripletData {
  book_odds?: number | string | null;
  fair_odds?: number | string | null;
  model_odds?: number | string | null;
  ev_pct?: number | string | null;
  quarantine_reason?: string | null;
  refused?: boolean;
  /** Free tier: the model leg exists server-side but is not sent. */
  model_price_locked?: boolean;
}

const ABSENT = '—';

/** Verdict copy, verbatim from the design file. */
function verdictFor(state: string, vsFair: number | null, ev: number | null) {
  const pct = (n: number | null) => (n == null ? null : `${n >= 0 ? '+' : ''}${n}%`);
  switch (state) {
    case STATES.VALUE:
      // Show the VS FAIR gap only when it agrees in sign with the verdict.
      // A row can clear the EV bar on the BOOK price while our own price sits
      // level with fair; printing "VALUE · -0.4% VS FAIR" would read as a
      // contradiction, so we lead with the EV that actually drove the call.
      return {
        label: vsFair != null && vsFair > 0 ? `VALUE · ${pct(vsFair)} VS FAIR` : 'VALUE',
        sub: ev != null ? `${pct(ev)} EV` : null,
        body: 'Model prices it shorter than the honest number — the book is paying longer than the leg is worth. Real edge.',
        mark: null,
      };
    case STATES.PRICED_OUT:
      return {
        label: 'EDGE · NOT TAKEABLE',
        sub: ev != null ? `${pct(ev)} EV, priced out` : null,
        body: `The math shows edge — but this price is too juiced to bet. We won't call a juiced price a value, and we won't pretend the edge wasn't there. Takeable band ${TAKEABLE_ODDS_CEILING} to +${TAKEABLE_ODDS_MAX}.`,
        mark: '⊘',
      };
    case STATES.NO_EDGE:
      return {
        // Same sign-coherence rule inverted: a NO-EDGE row whose model happens
        // to sit above fair says so with the EV, not a positive-looking gap.
        label: vsFair != null && vsFair < 0 ? `NO EDGE HERE · ${pct(vsFair)} VS FAIR` : 'NO EDGE HERE',
        sub: ev != null ? `${pct(ev)} EV` : null,
        body: "Model lands short of fair — the honest number is already priced. We're not calling this a play. That “no” is the instrument working.",
        mark: null,
      };
    case STATES.QUARANTINE:
      return {
        label: 'MODEL READ WITHHELD',
        sub: null,
        body: 'We suppressed our own price on this row. Book and fair stand — we never hide the honest fair number because a different leg is poisoned.',
        mark: null,
      };
    case STATES.NO_VERDICT_LOCKED:
      return {
        label: 'MODEL PRICE ON ANALYST',
        sub: null,
        body: 'The honest de-vigged number stays free. Only VYNDR’s own price gates.',
        mark: null,
      };
    default:
      return null;
  }
}

function Leg({
  label,
  value,
  note,
  color,
  hero,
  locked,
  compact,
}: {
  label: string;
  value: string | null;
  note?: string | null;
  color: string;
  hero?: boolean;
  locked?: boolean;
  compact?: boolean;
}) {
  return (
    <div
      style={{
        padding: compact ? '8px 10px' : '10px 12px',
        background: hero ? 'var(--fair-tint)' : 'transparent',
        border: `1px solid ${hero ? 'var(--fair-border)' : 'var(--border)'}`,
        borderRadius: 8,
        minWidth: 0,
      }}
    >
      <div
        className="mono"
        style={{
          fontSize: 7.5,
          letterSpacing: '0.14em',
          color: 'var(--text-2)',
          fontWeight: 700,
          whiteSpace: 'nowrap',
        }}
      >
        {hero ? '◆ ' : ''}
        {label}
      </div>
      {locked ? (
        // The lock is a TEASER, not a number. Nothing here can be mistaken
        // for a price the viewer wasn't given.
        <div
          aria-label="Model price locked"
          style={{
            marginTop: 4,
            height: compact ? 18 : 22,
            borderRadius: 4,
            background:
              'repeating-linear-gradient(90deg, var(--border-hi) 0 10px, transparent 10px 18px)',
            opacity: 0.55,
          }}
        />
      ) : (
        <div
          className="mono"
          style={{
            fontSize: compact ? 17 : 21,
            fontWeight: 800,
            color,
            fontVariantNumeric: 'tabular-nums',
            marginTop: 2,
            lineHeight: 1.1,
          }}
        >
          {value ?? ABSENT}
        </div>
      )}
      {note && (
        <div
          className="mono"
          style={{ fontSize: 7.5, letterSpacing: '0.1em', color: 'var(--text-3)', fontWeight: 700 }}
        >
          {note}
        </div>
      )}
    </div>
  );
}

export default function PriceTriplet({
  data,
  compact = false,
  showBody = true,
  ledgerHref,
}: {
  data: PriceTripletData | null | undefined;
  compact?: boolean;
  showBody?: boolean;
  ledgerHref?: string | null;
}) {
  if (!data) return null;
  const state = deriveValueState(data);

  const book = fmtOddsAmerican(data.book_odds);
  const fair = fmtOddsAmerican(data.fair_odds);
  const model = fmtOddsAmerican(data.model_odds);
  const ev = data.ev_pct == null || data.ev_pct === '' ? null : Number(data.ev_pct);
  const vsFair = modelVsFair(data.model_odds, data.fair_odds);
  const accent = valueStateColor(state);

  // REFUSAL — nothing to price. No legs, no gauge, no fabricated number.
  if (state === STATES.REFUSAL) {
    return (
      <div
        className="price-triplet"
        style={{
          border: '1px dashed var(--border-hi)',
          borderRadius: 10,
          padding: compact ? 12 : 16,
          background: 'var(--bg-deep)',
        }}
      >
        <div
          className="mono"
          style={{ fontSize: 10, fontWeight: 800, letterSpacing: '0.12em', color: 'var(--text-2)' }}
        >
          CAN&rsquo;T PRICE THIS ONE
        </div>
        {showBody && (
          <p style={{ fontSize: 12.5, color: 'var(--text-2)', margin: '6px 0 0', lineHeight: 1.55 }}>
            No fair price we&rsquo;d defend yet — the inputs are too thin. When they clear, the
            triplet returns. We&rsquo;d rather show nothing than a number we can&rsquo;t stand
            behind.
          </p>
        )}
      </div>
    );
  }

  const modelWithheld = state === STATES.QUARANTINE;
  const modelLocked = state === STATES.NO_VERDICT_LOCKED;
  // GREEN = TAKEABLE EDGE ONLY. The model leg is green on exactly one state.
  const modelColor = state === STATES.VALUE ? 'var(--g-a)' : 'var(--text-0)';
  const verdict = verdictFor(state, vsFair, Number.isFinite(ev as number) ? (ev as number) : null);

  return (
    <div className="price-triplet">
      <div
        className="price-triplet-legs"
        style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}
      >
        <Leg label="BOOK" value={book} note="OFFERED" color="var(--text-0)" compact={compact} />
        <Leg
          label="FAIR"
          value={fair}
          note="DE-VIGGED"
          color="var(--amber)"
          hero
          compact={compact}
        />
        <Leg
          label="MODEL"
          value={modelWithheld ? null : model}
          note={modelWithheld ? 'WITHHELD' : modelLocked ? 'ANALYST' : 'OUR PRICE'}
          color={modelColor}
          locked={modelLocked}
          compact={compact}
        />
      </div>

      {verdict && (
        <div
          style={{
            marginTop: 8,
            padding: compact ? '8px 10px' : '10px 12px',
            borderRadius: 8,
            border: `1px solid ${
              state === STATES.PRICED_OUT ? 'var(--priced-out-border)' : 'var(--border)'
            }`,
            background:
              state === STATES.PRICED_OUT
                ? 'var(--priced-out-tint)'
                : state === STATES.VALUE
                  ? 'rgba(0, 212, 160, 0.05)'
                  : 'transparent',
          }}
        >
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
            <span
              className="mono"
              style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.08em', color: accent }}
            >
              {verdict.mark ? `${verdict.mark} ` : ''}
              {verdict.label}
            </span>
            {verdict.sub && (
              <span
                className="mono"
                style={{
                  fontSize: 10.5,
                  color: 'var(--text-2)',
                  fontVariantNumeric: 'tabular-nums',
                }}
              >
                {verdict.sub}
              </span>
            )}
          </div>
          {showBody && verdict.body && (
            <p style={{ fontSize: 12.5, color: 'var(--text-1)', margin: '6px 0 0', lineHeight: 1.55 }}>
              {verdict.body}
            </p>
          )}
          {modelLocked && (
            <a
              href="/pricing"
              className="mono"
              style={{
                display: 'inline-block',
                marginTop: 8,
                fontSize: 10.5,
                fontWeight: 800,
                letterSpacing: '0.08em',
                color: 'var(--g-a)',
                textDecoration: 'none',
              }}
            >
              UNLOCK ▸
            </a>
          )}
        </div>
      )}

      {ledgerHref && (
        <a
          href={ledgerHref}
          className="mono"
          style={{
            display: 'inline-block',
            marginTop: 8,
            minHeight: 44,
            lineHeight: '44px',
            fontSize: 10,
            fontWeight: 700,
            letterSpacing: '0.1em',
            color: 'var(--text-2)',
            textDecoration: 'none',
          }}
        >
          CLOSES TRACKED IN YOUR LEDGER ▸
        </a>
      )}
    </div>
  );
}
