// screen-settlement.jsx — Daily Settlement / 今日結算 / The Due Result
// The most important screen. The day is closed; the proof is recorded.

function ScreenSettlement({ state, onClose }) {
  const accentScale = [W.accentHi, W.accent, W.accentLo, W.accentDk];
  const dist = state.todayDist || [
    { id: 'gmat',     name: 'GMAT EXPERT',       hours: 3.2, color: accentScale[0] },
    { id: 'eng',      name: 'SOFTWARE ENGINEER', hours: 2.4, color: accentScale[1] },
    { id: 'athlete',  name: 'ATHLETE',           hours: 1.0, color: accentScale[2] },
    { id: 'reader',   name: 'READER',            hours: 0.6, color: accentScale[3] },
  ];
  const investedPct = state.todayInvestedPct ?? 72;
  const totalHrs = dist.reduce((a, b) => a + b.hours, 0);
  const wasted = state.todayWasted ?? 1.4;

  // Arc segments (donut)
  const total = totalHrs + wasted + 0.01;
  let cursor = 0;
  const segments = [...dist.map((d) => ({ ...d, frac: d.hours / total })), { id: 'idle', name: 'IDLE / FRICTION', hours: wasted, color: '#1c1d22', frac: wasted / total }];
  const segArcs = segments.map((s) => {
    const start = cursor; const end = cursor + s.frac; cursor = end;
    return { ...s, start, end };
  });

  return (
    <div style={{
      width: '100%', height: '100%',
      background: `radial-gradient(110% 60% at 50% 12%, #18181d 0%, ${W.ink} 55%, ${W.void} 100%)`,
      color: W.textHi, display: 'flex', flexDirection: 'column',
      fontFamily: W.mono, position: 'relative', overflow: 'hidden',
    }}>
      {/* Page-wide hairline grain */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: hairlineMetal({ base: 'transparent', intensity: 0.4, density: 0.6 }),
        opacity: 0.7, mixBlendMode: 'screen',
      }} />

      <WStatusBar time="22:48" />

      {/* Title plate */}
      <div style={{ padding: '14px 24px 0' }}>
        <SerialNum style={{ color: W.goldHi }}>今日結算 · DAILY SETTLEMENT · SEAL № 0241</SerialNum>
        <div style={{
          fontFamily: W.serif, fontSize: 38, marginTop: 6,
          color: W.textHi, lineHeight: 1.0, fontWeight: 400, letterSpacing: '-0.005em',
          ...etched(),
        }}>The Due Result.</div>
        <div style={{
          fontFamily: W.serif, fontStyle: 'italic', fontSize: 22, marginTop: 2,
          color: W.gold, lineHeight: 1.1, fontWeight: 400,
        }}>應得的結果</div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 18px 12px' }}>
        {/* Witness statement */}
        <WPanel base={W.steel} intensity={0.65} density={1} style={{ padding: '18px 20px 20px', marginBottom: 14, position: 'relative', overflow: 'hidden' }}>
          {/* corner serial */}
          <div style={{ position: 'absolute', top: 10, right: 14 }}>
            <SerialNum style={{ color: W.textXLo, fontSize: 8.5 }}>WITNESS · STATEMENT</SerialNum>
          </div>
          <SerialNum>TODAY, YOU ARE SOMEONE WHO</SerialNum>
          <div style={{
            fontFamily: W.display, fontSize: 22, lineHeight: 1.25, marginTop: 8,
            color: W.textHi, fontWeight: 400, letterSpacing: '-0.008em', textWrap: 'pretty',
          }}>
            invested&nbsp;
            <span style={{
              fontFamily: W.mono, fontWeight: 500, color: W.goldHi, letterSpacing: '-0.02em',
              fontVariantNumeric: 'tabular-nums', ...etched(),
            }}>{investedPct}%</span>
            &nbsp;of his time into&nbsp;
            <span style={{ fontFamily: W.serif, fontStyle: 'italic', color: W.goldHi }}>becoming who he wants to be.</span>
          </div>
          {/* Engraved underline */}
          <div style={{
            marginTop: 14, height: 1,
            background: `linear-gradient(90deg, transparent, rgba(${W.midRGB},0.6), transparent)`,
            boxShadow: '0 1px 0 rgba(0,0,0,0.6)',
          }} />
          <div style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between' }}>
            <MonoStat size="md" label="ON IDENTITY" value={totalHrs.toFixed(1)} unit="h" accent />
            <MonoStat size="md" label="OFF / FRICTION" value={wasted.toFixed(1)} unit="h" align="right" />
          </div>
        </WPanel>

        {/* Donut + breakdown */}
        <WPanel base={W.iron} intensity={0.55} density={0.85} style={{ padding: '18px 20px 16px', marginBottom: 14 }}>
          <SerialNum>TIME DISTRIBUTION · 24:00:00 LEDGER</SerialNum>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginTop: 14 }}>
            {/* Donut */}
            <div style={{ width: 140, height: 140, position: 'relative', flexShrink: 0 }}>
              <svg width="140" height="140" viewBox="0 0 140 140">
                <defs>
                  {segArcs.map((s, i) => (
                    <linearGradient key={s.id} id={`segGrad-${s.id}`} x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor={s.id === 'idle' ? '#26272c' : W.gradHi} stopOpacity={s.id === 'idle' ? 1 : 1 - i * 0.18} />
                      <stop offset="100%" stopColor={s.color} />
                    </linearGradient>
                  ))}
                </defs>
                {/* Engraved channel */}
                <circle cx="70" cy="70" r="56" fill="none" stroke="#05060a" strokeWidth="22" />
                {segArcs.map((s) => {
                  if (s.frac <= 0.001) return null;
                  const C = 2 * Math.PI * 56;
                  return (
                    <circle key={s.id} cx="70" cy="70" r="56" fill="none"
                      stroke={`url(#segGrad-${s.id})`}
                      strokeWidth="20"
                      strokeDasharray={`${C * s.frac - 1.5} ${C}`}
                      strokeDashoffset={-C * s.start}
                      transform="rotate(-90 70 70)"
                      style={s.id !== 'idle' ? { filter: `drop-shadow(0 0 3px rgba(${W.midRGB},0.25))` } : {}}
                    />
                  );
                })}
                {/* Inner engraved rim */}
                <circle cx="70" cy="70" r="44" fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="0.5" />
                <circle cx="70" cy="70" r="68" fill="none" stroke="rgba(0,0,0,0.6)" strokeWidth="0.5" />
              </svg>
              <div style={{
                position: 'absolute', inset: 0,
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              }}>
                <SerialNum style={{ fontSize: 8.5, color: W.textXLo }}>INVESTED</SerialNum>
                <div style={{
                  fontFamily: W.mono, fontWeight: 300, fontSize: 28, lineHeight: 1, color: W.goldHi,
                  fontVariantNumeric: 'tabular-nums', ...etched(), marginTop: 4,
                }}>{investedPct}<span style={{ fontSize: 12, color: W.gold }}>%</span></div>
              </div>
            </div>

            {/* Legend */}
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
              {dist.map((d) => {
                const pct = Math.round((d.hours / total) * 100);
                return (
                  <div key={d.id} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 3, height: 16, background: d.color, boxShadow: '0 0 0 0.5px rgba(0,0,0,0.7)' }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontFamily: W.mono, fontSize: 10.5, color: W.textHi, letterSpacing: '0.08em', fontWeight: 500 }}>{d.name}</div>
                      <div style={{ fontFamily: W.mono, fontSize: 9, color: W.textLo, letterSpacing: '0.06em' }}>
                        {d.hours.toFixed(1)}h · {pct}%
                      </div>
                    </div>
                  </div>
                );
              })}
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2, opacity: 0.7 }}>
                <div style={{ width: 3, height: 16, background: '#26272c' }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: W.mono, fontSize: 10.5, color: W.textLo, letterSpacing: '0.08em' }}>IDLE / FRICTION</div>
                  <div style={{ fontFamily: W.mono, fontSize: 9, color: W.textXLo, letterSpacing: '0.06em' }}>
                    {wasted.toFixed(1)}h · {Math.round((wasted / total) * 100)}%
                  </div>
                </div>
              </div>
            </div>
          </div>
        </WPanel>

        {/* Etched-into-axes table */}
        <WPanel base={W.pitch} intensity={0.45} density={0.7} style={{ padding: '14px 16px 14px', marginBottom: 14 }}>
          <SerialNum>ETCHED INTO LIFETIME AXES TODAY</SerialNum>
          <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 11 }}>
            {dist.map((d) => (
              <div key={d.id} style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                <span style={{ fontFamily: W.mono, fontSize: 9.5, letterSpacing: '0.16em', color: W.textLo, width: 130, flexShrink: 0 }}>{d.name}</span>
                <span style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.06)', alignSelf: 'center', boxShadow: 'inset 0 -1px 0 rgba(0,0,0,0.5)' }} />
                <span style={{ fontFamily: W.mono, fontSize: 12, color: W.goldHi, fontVariantNumeric: 'tabular-nums', letterSpacing: '0.04em' }}>
                  +{d.hours.toFixed(1)}h
                </span>
              </div>
            ))}
          </div>
        </WPanel>
      </div>

      {/* Bottom seal button */}
      <div style={{ padding: '4px 18px 28px', borderTop: '1px solid rgba(0,0,0,0.6)', boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.04)' }}>
        <div style={{ padding: '14px 4px 4px', display: 'flex', justifyContent: 'center' }}>
          <WCapsule variant="primary" size="lg" onClick={onClose}
            label="NO REWARD · NO PRAISE · ONLY RECORD"
            hint="PRESSING WILL ETCH THIS DAY INTO YOUR LIFETIME LEDGER">
            Today&rsquo;s Proof Is Recorded
          </WCapsule>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenSettlement });
