// Screen 4: Processing & Screen 5: Report

function ProcessingScreen({ T, t, accent, theme, onDone }) {
  const steps = [t.proc1, t.proc2, t.proc3, t.proc4];
  const [active, setActive] = React.useState(0);
  const [done, setDone] = React.useState([]);

  React.useEffect(() => {
    if (active >= steps.length) {
      const id = setTimeout(() => onDone(), 600);
      return () => clearTimeout(id);
    }
    const id = setTimeout(() => {
      setDone(d => [...d, active]);
      setActive(a => a + 1);
    }, 1400);
    return () => clearTimeout(id);
  }, [active]);

  return (
    <div style={{ position: "relative", minHeight: "100%", padding: "20px 22px 100px" }}>
      <AmbientBg T={T} accent={accent} theme={theme} />
      <div style={{ position: "relative", zIndex: 1, display: "flex", flexDirection: "column", alignItems: "center", paddingTop: 24 }}>
        <Kicker T={T} accent={accent}>{t.procKicker}</Kicker>
        <div style={{ height: 16 }} />
        <LucyOrb size={150} accent={accent} theme={theme} processing />
        <div style={{ height: 24 }} />
        <SerifTitle T={T} size={38}>{t.procTitle}</SerifTitle>
        <div style={{ height: 10 }} />
        <Body T={T} size={13} style={{ textAlign: "center" }}>{t.procSub}</Body>

        <div style={{ height: 36 }} />

        {/* Step checklist */}
        <div style={{ width: "100%", display: "flex", flexDirection: "column", gap: 0 }}>
          {steps.map((s, i) => {
            const isDone = done.includes(i);
            const isActive = active === i;
            return (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 14,
                padding: "16px 14px",
                borderTop: `1px solid ${T.border}`,
                opacity: isDone || isActive ? 1 : 0.45,
                transition: "opacity 300ms",
                ...(i === steps.length - 1 ? { borderBottom: `1px solid ${T.border}` } : {}),
              }}>
                <div style={{
                  width: 24, height: 24, borderRadius: "50%",
                  border: `1.5px solid ${isDone ? accent.primary : isActive ? accent.primary : T.borderStrong}`,
                  background: isDone ? accent.primary : "transparent",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  flexShrink: 0, transition: "all 200ms",
                }}>
                  {isDone ? (
                    <svg width="11" height="11" viewBox="0 0 11 11"><path d="M2 5.5L4.5 8L9 3" stroke="#0B0F19" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  ) : isActive ? (
                    <div style={{ width: 8, height: 8, borderRadius: "50%", background: accent.primary, animation: "lucyPulse 1s ease-in-out infinite" }} />
                  ) : null}
                </div>
                <span style={{ flex: 1, fontFamily: FONTS.ui, fontSize: 13.5, color: T.text, fontWeight: isActive ? 600 : 400 }}>
                  {s}
                </span>
                {isActive && (
                  <span style={{ fontFamily: FONTS.ui, fontSize: 10, color: accent.primary, letterSpacing: 1, textTransform: "uppercase" }}>
                    <ScanDots />
                  </span>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function ScanDots() {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setN(x => (x + 1) % 4), 350);
    return () => clearInterval(id);
  }, []);
  return <span style={{ fontVariantNumeric: "tabular-nums", display: "inline-block", width: 18, textAlign: "left" }}>{".".repeat(n)}</span>;
}

// ─── REPORT ─────────────────────────────────────────────────────

function RadialDial({ score, accent, T, size = 180, variant = "single" }) {
  const r = size / 2 - 14;
  const c = 2 * Math.PI * r;
  const dash = (score / 100) * c;
  const cx = size / 2, cy = size / 2;
  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={cx} cy={cy} r={r} stroke={T.surfaceStrong} strokeWidth="6" fill="none" />
        <circle cx={cx} cy={cy} r={r} stroke={accent.primary} strokeWidth="6" fill="none"
          strokeDasharray={`${dash} ${c}`} strokeLinecap="round"
          style={{ transition: "stroke-dasharray 1.2s cubic-bezier(0.2, 0.8, 0.2, 1)", filter: `drop-shadow(0 0 8px ${accent.primaryGlow})` }} />
        {variant === "rings" && [0.85, 0.72, 0.78, 0.65].map((p, i) => (
          <circle key={i} cx={cx} cy={cy} r={r - 12 - i*7} stroke={accent.chart[i+1]} strokeOpacity="0.55" strokeWidth="2.5" fill="none"
            strokeDasharray={`${p * 2*Math.PI*(r - 12 - i*7)} ${2*Math.PI*(r - 12 - i*7)}`} strokeLinecap="round" />
        ))}
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <div style={{ fontFamily: FONTS.fraunces, fontSize: size * 0.34, fontWeight: 400, color: T.text, letterSpacing: -2, lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{score}</div>
        <div style={{ fontFamily: FONTS.ui, fontSize: 9.5, fontWeight: 600, letterSpacing: 1.2, textTransform: "uppercase", color: T.textMute, marginTop: 2 }}>/ 100</div>
      </div>
    </div>
  );
}

function ScoreCard({ label, score, max = 100, accent, T, color }) {
  const pct = score / max;
  const grade = score >= 80 ? "A" : score >= 65 ? "B" : score >= 50 ? "C" : "D";
  return (
    <div style={{
      padding: "14px 14px",
      borderRadius: 12,
      background: T.surface,
      border: `1px solid ${T.border}`,
      display: "flex", flexDirection: "column", gap: 10,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div style={{ fontFamily: FONTS.ui, fontSize: 11, color: T.textDim, fontWeight: 500, lineHeight: 1.3, maxWidth: 90 }}>{label}</div>
        <span style={{ fontFamily: FONTS.fraunces, fontSize: 14, color: color || accent.primary, fontWeight: 500 }}>{grade}</span>
      </div>
      <div style={{ fontFamily: FONTS.fraunces, fontSize: 30, color: T.text, letterSpacing: -1, lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{score}</div>
      <div style={{ height: 3, borderRadius: 999, background: T.surfaceStrong, overflow: "hidden" }}>
        <div style={{ width: `${pct * 100}%`, height: "100%", background: color || accent.primary, transition: "width 1s" }} />
      </div>
    </div>
  );
}

function ReportScreen({ T, t, accent, theme, name, alloc, onRestart, onOptimize, vizVariant }) {
  // derive synthetic scores from alloc
  const overall = 72;
  const items = [
    { label: t.inflation, score: 68, color: accent.chart[2] },
    { label: t.diversification, score: 81, color: accent.chart[1] },
    { label: t.liquidity, score: 76, color: accent.chart[3] },
    { label: t.goalAlign, score: 64, color: accent.chart[4] },
  ];
  const allocItems = [
    { key: "bank", label: t.bank, c: accent.chart[0], you: alloc.bank, sug: 25 },
    { key: "realEstate", label: t.realEstate, c: accent.chart[1], you: alloc.realEstate, sug: 25 },
    { key: "stocks", label: t.stocks, c: accent.chart[2], you: alloc.stocks, sug: 25 },
    { key: "bonds", label: t.bonds, c: accent.chart[3], you: alloc.bonds, sug: 10 },
    { key: "gold", label: t.gold, c: accent.chart[4], you: alloc.gold, sug: 10 },
    { key: "crypto", label: t.crypto, c: accent.chart[5], you: alloc.crypto, sug: 5 },
  ];

  return (
    <div style={{ position: "relative", minHeight: "100%", padding: "20px 22px 120px" }}>
      <AmbientBg T={T} accent={accent} theme={theme} variant="report" />
      <div style={{ position: "relative", zIndex: 1 }}>
        <Kicker T={T} accent={accent}>{t.reportKicker}</Kicker>
        <div style={{ height: 14 }} />
        <SerifTitle T={T} size={42}>{t.reportTitle}</SerifTitle>
        <div style={{ height: 8 }} />
        <Body T={T} size={12} style={{ color: T.textMute }}>
          {t.reportFor} <span style={{ color: T.text, fontWeight: 500 }}>{name || "Investor"}</span> · {new Date().toLocaleDateString(undefined, { day: '2-digit', month: 'short', year: 'numeric' })}
        </Body>

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

        {/* Hero score */}
        <div style={{
          padding: "28px 20px",
          borderRadius: 18,
          background: `linear-gradient(165deg, ${T.bgElev}, ${T.bgElev2})`,
          border: `1px solid ${T.borderStrong}`,
          position: "relative", overflow: "hidden",
        }}>
          <div style={{
            position: "absolute", top: -40, right: -40, width: 200, height: 200, borderRadius: "50%",
            background: `radial-gradient(circle, ${accent.primaryGlow}, transparent 70%)`,
          }} />
          {vizVariant === "editorial" ? (
            <div style={{ position: "relative" }}>
              <div style={{ fontFamily: FONTS.ui, fontSize: 10.5, letterSpacing: 1.4, color: T.textMute, textTransform: "uppercase", marginBottom: 6 }}>{t.overallLabel}</div>
              <div style={{ fontFamily: FONTS.fraunces, fontSize: 132, fontWeight: 300, color: T.text, lineHeight: 0.95, letterSpacing: -5, fontVariantNumeric: "tabular-nums" }}>{overall}</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 4 }}>
                <span style={{ fontFamily: FONTS.fraunces, fontSize: 20, color: accent.primary, fontStyle: "italic" }}>B+</span>
                <span style={{ fontFamily: FONTS.ui, fontSize: 12, color: T.textMute }}>· {t.of100}</span>
              </div>
            </div>
          ) : (
            <div style={{ display: "flex", alignItems: "center", gap: 22, position: "relative" }}>
              <RadialDial score={overall} accent={accent} T={T} size={140} variant={vizVariant === "rings" ? "rings" : "single"} />
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: FONTS.ui, fontSize: 10.5, letterSpacing: 1.4, color: T.textMute, textTransform: "uppercase", marginBottom: 6 }}>{t.overallLabel}</div>
                <div style={{ fontFamily: FONTS.fraunces, fontSize: 22, color: T.text, lineHeight: 1.15, letterSpacing: -0.4, marginBottom: 4 }}>
                  {t.grade}: <span style={{ color: accent.primary, fontStyle: "italic" }}>B+</span>
                </div>
                <Body T={T} size={11.5} style={{ color: T.textMute }}>{t.of100}</Body>
              </div>
            </div>
          )}
        </div>

        <div style={{ height: 16 }} />

        {/* Scorecards grid */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          {items.map(i => <ScoreCard key={i.label} label={i.label} score={i.score} color={i.color} accent={accent} T={T} />)}
        </div>

        <div style={{ height: 22 }} />

        {/* Pull quote — Lucy commentary */}
        <div style={{
          position: "relative",
          padding: "24px 22px",
          borderRadius: 16,
          background: `linear-gradient(155deg, ${accent.primarySoft}, ${T.surface} 60%)`,
          border: `1px solid ${accent.primary}30`,
          overflow: "hidden",
        }}>
          <div style={{
            fontFamily: FONTS.fraunces, fontSize: 56, color: accent.primary,
            position: "absolute", top: -4, left: 14, lineHeight: 1, opacity: 0.7,
          }}>“</div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10, paddingLeft: 24 }}>
            <LucyMark size={20} accent={accent.primary} />
            <span style={{ fontFamily: FONTS.ui, fontSize: 10.5, fontWeight: 600, color: accent.primary, letterSpacing: 1.2, textTransform: "uppercase" }}>{t.aiCommentary}</span>
          </div>
          <p style={{
            fontFamily: FONTS.fraunces, fontSize: 17, fontWeight: 400,
            color: T.text, lineHeight: 1.45, letterSpacing: -0.2,
            margin: 0, fontStyle: "italic",
            paddingLeft: 24,
          }}>{t.quote}</p>
        </div>

        <div style={{ height: 22 }} />

        {/* Allocation comparison: bullet bars */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
          <span style={{ fontFamily: FONTS.fraunces, fontSize: 18, color: T.text, letterSpacing: -0.3 }}>{t.benchmark}</span>
          <div style={{ display: "flex", gap: 12 }}>
            <Legend color={T.textDim} label={t.yourAlloc} T={T} />
            <Legend color={accent.primary} label={t.suggested} T={T} />
          </div>
        </div>
        <div style={{
          padding: "14px 14px", borderRadius: 12,
          background: T.surface, border: `1px solid ${T.border}`,
          display: "flex", flexDirection: "column", gap: 12,
        }}>
          {allocItems.map(a => (
            <div key={a.key}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 5 }}>
                <span style={{ fontFamily: FONTS.ui, fontSize: 12, color: T.text }}>{a.label}</span>
                <span style={{ fontFamily: FONTS.ui, fontSize: 11, color: T.textMute, fontVariantNumeric: "tabular-nums" }}>
                  <span style={{ color: T.textDim }}>{a.you}%</span> → <span style={{ color: accent.primary, fontWeight: 600 }}>{a.sug}%</span>
                </span>
              </div>
              <div style={{ position: "relative", height: 10, background: T.surfaceStrong, borderRadius: 999, overflow: "hidden" }}>
                {/* user — gray ghost */}
                <div style={{ position: "absolute", left: 0, top: 0, height: "100%", width: `${a.you}%`, background: T.borderStrong, borderRadius: 999 }} />
                {/* suggested — accent line */}
                <div style={{ position: "absolute", left: `${a.sug}%`, top: -3, width: 2, height: 16, background: accent.primary, borderRadius: 1 }} />
              </div>
            </div>
          ))}
        </div>

        <div style={{ height: 22 }} />

        {/* Actions */}
        <div style={{ fontFamily: FONTS.fraunces, fontSize: 18, color: T.text, letterSpacing: -0.3, marginBottom: 10 }}>{t.actions}</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {[t.action1, t.action2, t.action3].map((a, i) => (
            <div key={i} style={{
              display: "flex", alignItems: "center", gap: 12,
              padding: "12px 14px", borderRadius: 10,
              background: T.surface, border: `1px solid ${T.border}`,
            }}>
              <span style={{ fontFamily: FONTS.fraunces, fontSize: 13, color: accent.primary, width: 22, fontVariantNumeric: "tabular-nums" }}>{`0${i+1}`}</span>
              <span style={{ flex: 1, fontFamily: FONTS.ui, fontSize: 12.5, color: T.text }}>{a}</span>
            </div>
          ))}
        </div>

        <div style={{ height: 28 }} />

        {/* Asset simulation block */}
        <AssetSimulation T={T} t={t} accent={accent} alloc={alloc} />

        <div style={{ height: 26 }} />

        {/* Primary CTA — Optimize with Lucy */}
        <button onClick={onOptimize} style={{
          width: "100%",
          padding: "16px 20px",
          borderRadius: 14,
          border: `1px solid ${accent.primary}50`,
          cursor: "pointer",
          background: `linear-gradient(135deg, ${T.surfaceStrong}, ${T.surface})`,
          color: accent.primary,
          fontFamily: FONTS.ui,
          fontSize: 15,
          fontWeight: 600,
          letterSpacing: 0.3,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 10,
          boxShadow: `0 8px 32px ${accent.primaryGlow}, inset 0 1px 0 rgba(255,255,255,0.05)`,
          position: "relative",
          overflow: "hidden",
          transition: "all 200ms ease",
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/>
          </svg>
          <span>{t.optimizeWithLucy}</span>
        </button>
      </div>
    </div>
  );
}

function Legend({ color, label, T }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
      <div style={{ width: 10, height: 2, background: color, borderRadius: 1 }} />
      <span style={{ fontFamily: FONTS.ui, fontSize: 10, color: T.textMute, letterSpacing: 0.4 }}>{label}</span>
    </div>
  );
}

Object.assign(window, { ProcessingScreen, ReportScreen });
