// SCREEN 04 — Value & Market History
// Collector intelligence — value, appreciation, comps, restoration investment.

function ScreenValue() {
  const v = VEHICLE;

  // Build chart data — reverse appraisals so oldest is first
  const points = [...v.value.appraisals].reverse();
  const minV = Math.min(...points.map(p => p.value));
  const maxV = Math.max(...points.map(p => p.value));
  const range = maxV - minV;
  const padding = range * 0.18;
  const yMin = minV - padding;
  const yMax = maxV + padding;
  const yRange = yMax - yMin;

  const W = 346;
  const H = 168;
  const PADX = 6;
  const PADY = 14;

  const xFor = (i) => PADX + (W - PADX * 2) * (i / (points.length - 1));
  const yFor = (val) => PADY + (H - PADY * 2) * (1 - (val - yMin) / yRange);

  const pathD = points.map((p, i) =>
    (i === 0 ? 'M' : 'L') + xFor(i).toFixed(1) + ' ' + yFor(p.value).toFixed(1)
  ).join(' ');

  // Fill area underneath
  const areaD =
    pathD +
    ` L ${xFor(points.length - 1).toFixed(1)} ${(H - PADY).toFixed(1)}` +
    ` L ${xFor(0).toFixed(1)} ${(H - PADY).toFixed(1)} Z`;

  const totalRestoration = v.value.investments.reduce((s, x) => s + x.cost, 0);

  return (
    <div className="proto-screen" style={{ background: P.ink, color: P.paper }}>

      <ScreenIntro
        eyebrow="VALUE · COLLECTOR INTELLIGENCE"
        title="UP ↑ AND TO THE RIGHT"
        sub="Acquisition price, appraisal trail, and live market comps. Investment in restoration is tracked separately."
      />

      {/* Headline value */}
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
          <div>
            <Eyebrow color={P.mute}>CURRENT VALUATION</Eyebrow>
            <div style={{
              fontFamily: T.display, fontSize: 44, fontWeight: 700,
              color: P.paper, letterSpacing: '-0.025em', lineHeight: 1,
              marginTop: 6,
            }}>{fmtMoney(v.value.current)}</div>
            <div style={{
              fontFamily: T.mono, fontSize: 10, color: P.gold,
              letterSpacing: '0.16em', textTransform: 'uppercase', marginTop: 8,
            }}>
              + {fmtMoney(v.value.deltaTotal)} · {v.value.deltaPct}% SINCE PURCHASE
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <Eyebrow color={P.mute}>RANGE 12MO</Eyebrow>
            <div style={{
              fontFamily: T.mono, fontSize: 10, color: P.bone, marginTop: 4,
              letterSpacing: '0.1em',
            }}>{fmtMoney(minV, { compact: true })}<br/>—<br/>{fmtMoney(maxV, { compact: true })}</div>
          </div>
        </div>
      </div>

      {/* Chart */}
      <div style={{ padding: '0 22px 14px' }}>
        <div style={{ background: P.graphite, padding: '16px 12px' }}>
          <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
            <defs>
              <linearGradient id="valFill" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={P.gold} stopOpacity="0.32" />
                <stop offset="100%" stopColor={P.gold} stopOpacity="0" />
              </linearGradient>
            </defs>
            {/* gridlines */}
            {[0.25, 0.5, 0.75].map(t => (
              <line key={t} x1="0" y1={PADY + (H - PADY * 2) * t} x2={W}
                y2={PADY + (H - PADY * 2) * t}
                stroke={P.slate} strokeWidth="1" strokeDasharray="2 4" opacity="0.4" />
            ))}
            {/* area */}
            <path d={areaD} fill="url(#valFill)" />
            {/* line */}
            <path d={pathD} fill="none" stroke={P.gold} strokeWidth="2" />
            {/* points */}
            {points.map((p, i) => (
              <g key={i}>
                <circle cx={xFor(i)} cy={yFor(p.value)} r="3" fill={P.ink} stroke={P.gold} strokeWidth="1.5" />
              </g>
            ))}
            {/* current point — emphasized */}
            <circle cx={xFor(points.length - 1)} cy={yFor(points[points.length - 1].value)}
              r="6" fill={P.gold} />
            <circle cx={xFor(points.length - 1)} cy={yFor(points[points.length - 1].value)}
              r="6" fill="none" stroke={P.gold} strokeWidth="1" opacity="0.5">
              <animate attributeName="r" values="6;14;6" dur="2s" repeatCount="indefinite" />
              <animate attributeName="opacity" values="0.5;0;0.5" dur="2s" repeatCount="indefinite" />
            </circle>
          </svg>

          {/* X axis labels */}
          <div style={{
            display: 'flex', justifyContent: 'space-between', marginTop: 8,
            fontFamily: T.mono, fontSize: 8, letterSpacing: '0.14em',
            color: P.mute, textTransform: 'uppercase',
          }}>
            {points.map((p, i) => (
              <span key={i}>{p.date}</span>
            ))}
          </div>
        </div>
      </div>

      <RowRule>APPRAISAL TRAIL · {v.value.appraisals.length} POINTS</RowRule>
      <div style={{ padding: '14px 22px 8px' }}>
        {v.value.appraisals.map((a, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '60px 1fr auto',
            gap: 14, padding: '12px 0',
            borderBottom: i < v.value.appraisals.length - 1 ? `1px solid ${P.graphite}` : 'none',
            alignItems: 'center',
          }}>
            <div style={{
              fontFamily: T.mono, fontSize: 10, color: P.mute,
              letterSpacing: '0.12em', textTransform: 'uppercase',
            }}>{a.date}</div>
            <div>
              <div style={{
                fontFamily: T.body, fontSize: 13, color: P.paper,
              }}>{a.source}</div>
              <div style={{
                fontFamily: T.mono, fontSize: 9, color: P.gold,
                letterSpacing: '0.14em', textTransform: 'uppercase', marginTop: 3,
              }}>{i === 0 ? 'LATEST' : i === v.value.appraisals.length - 1 ? 'BASIS' : 'APPRAISAL'}</div>
            </div>
            <div style={{
              fontFamily: T.display, fontSize: 16, fontWeight: 600,
              color: P.paper, textAlign: 'right', letterSpacing: '-0.01em',
            }}>{fmtMoney(a.value, { compact: true })}</div>
          </div>
        ))}
      </div>

      {/* Auction comps */}
      <div style={{ padding: '14px 0 4px' }}>
        <RowRule>RECENT MARKET COMPS</RowRule>
      </div>
      <div style={{ padding: '14px 22px 8px' }}>
        {[
          { lot: 'GOODING · MONTEREY 2024',  desc: "'73 911 Carrera RS · Touring", value: 1_320_000, delta: 'PREMIUM TO YOURS' },
          { lot: 'RM SOTHEBY\'S · LONDON',   desc: "'73 Carrera RS · M471 LWB",    value: 1_180_000, delta: 'DISCOUNT TO YOURS' },
          { lot: 'BONHAMS · QUAIL 2024',     desc: "'73 Carrera RS · M472",        value: 985_000,   delta: 'TOURING SPEC' },
        ].map((c, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '1fr auto',
            gap: 14, padding: '12px 0',
            borderBottom: `1px solid ${P.graphite}`,
          }}>
            <div>
              <Eyebrow color={P.gold}>{c.lot}</Eyebrow>
              <div style={{
                fontFamily: T.body, fontSize: 12, color: P.paper, marginTop: 4,
              }}>{c.desc}</div>
              <div style={{
                fontFamily: T.mono, fontSize: 8, color: P.mute,
                letterSpacing: '0.18em', textTransform: 'uppercase', marginTop: 3,
              }}>{c.delta}</div>
            </div>
            <div style={{
              fontFamily: T.display, fontSize: 16, fontWeight: 600,
              color: P.paper, textAlign: 'right', letterSpacing: '-0.01em',
              alignSelf: 'center',
            }}>{fmtMoney(c.value, { compact: true })}</div>
          </div>
        ))}
      </div>

      {/* Restoration investment */}
      <div style={{ padding: '14px 0 4px' }}>
        <RowRule>RESTORATION INVESTMENT · CUMULATIVE</RowRule>
      </div>
      <div style={{ padding: '14px 22px 8px' }}>
        <div style={{
          background: P.graphite, padding: 18,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <Eyebrow color={P.mute}>TOTAL SUNK</Eyebrow>
            <div style={{
              fontFamily: T.display, fontSize: 26, fontWeight: 700,
              color: P.paper, letterSpacing: '-0.02em',
            }}>{fmtMoney(totalRestoration, { compact: true })}</div>
          </div>
          <div style={{ height: 1, background: P.slate, margin: '14px 0' }} />

          {/* Stacked bar */}
          <div style={{
            display: 'flex', height: 12, marginBottom: 14,
            background: P.ink,
          }}>
            {v.value.investments.map((inv, i) => {
              const pct = (inv.cost / totalRestoration) * 100;
              const tones = [P.gold, P.goldHi, P.bone, P.line];
              return (
                <div key={i} style={{
                  width: `${pct}%`, background: tones[i % tones.length],
                }} />
              );
            })}
          </div>

          {/* Legend */}
          {v.value.investments.map((inv, i) => {
            const tones = [P.gold, P.goldHi, P.bone, P.line];
            return (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '8px 1fr auto',
                gap: 10, padding: '6px 0', alignItems: 'center',
              }}>
                <div style={{ width: 8, height: 8, background: tones[i % tones.length] }} />
                <div style={{ fontFamily: T.body, fontSize: 11, color: P.paper }}>{inv.label}</div>
                <div style={{
                  fontFamily: T.mono, fontSize: 11, fontWeight: 500, color: P.paper,
                  letterSpacing: '0.04em',
                }}>{fmtMoney(inv.cost)}</div>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ height: 24 }} />
    </div>
  );
}

Object.assign(window, { ScreenValue });
