// ResultScreen — full analysis dashboard matching source structure.
const { Timeline, StatCard, Card, ProgressBar, Badge, Button } =
  window.HappyRetirementDesignSystem_d542ec;

// ── Canvas animation helpers ────────────────────────────────────────────
function runFireworks(canvas) {
  const ctx = canvas.getContext('2d');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const colors = ['#f4a261','#2a9d8f','#e9c46a','#2ebfaf','#e76f51','#a8dadc','#fff'];
  const particles = [];

  function burst(x, y) {
    const count = 60 + Math.random() * 40;
    for (let i = 0; i < count; i++) {
      const angle = (Math.PI * 2 * i) / count + Math.random() * 0.3;
      const speed = 2 + Math.random() * 6;
      particles.push({
        x, y, vx: Math.cos(angle) * speed, vy: Math.sin(angle) * speed,
        color: colors[Math.floor(Math.random() * colors.length)],
        alpha: 1, r: 2 + Math.random() * 3, gravity: 0.08,
      });
    }
  }

  let t = 0;
  const burstTimes = [0, 18, 36, 54, 72, 90];

  function tick() {
    if (t > 200) { canvas.style.display = 'none'; return; }
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    if (burstTimes.includes(t)) {
      burst(
        canvas.width * (0.2 + Math.random() * 0.6),
        canvas.height * (0.1 + Math.random() * 0.5)
      );
    }
    for (let i = particles.length - 1; i >= 0; i--) {
      const p = particles[i];
      p.x += p.vx; p.y += p.vy; p.vy += p.gravity;
      p.vx *= 0.98; p.alpha -= 0.012;
      if (p.alpha <= 0) { particles.splice(i, 1); continue; }
      ctx.save();
      ctx.globalAlpha = p.alpha;
      ctx.fillStyle = p.color;
      ctx.beginPath();
      ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
      ctx.fill();
      ctx.restore();
    }
    t++;
    requestAnimationFrame(tick);
  }
  tick();
}

function runRain(canvas) {
  const ctx = canvas.getContext('2d');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const drops = [];
  for (let i = 0; i < 180; i++) {
    drops.push({
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height,
      len: 12 + Math.random() * 20,
      speed: 6 + Math.random() * 8,
      alpha: 0.15 + Math.random() * 0.35,
    });
  }
  let t = 0;
  function tick() {
    if (t > 220) { canvas.style.display = 'none'; return; }
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    const fade = t < 20 ? t / 20 : t > 180 ? 1 - (t - 180) / 40 : 1;
    drops.forEach(d => {
      ctx.save();
      ctx.globalAlpha = d.alpha * fade;
      ctx.strokeStyle = '#8abccc';
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(d.x, d.y);
      ctx.lineTo(d.x - 3, d.y + d.len);
      ctx.stroke();
      ctx.restore();
      d.y += d.speed;
      d.x -= 1.5;
      if (d.y > canvas.height) { d.y = -d.len; d.x = Math.random() * canvas.width; }
    });
    t++;
    requestAnimationFrame(tick);
  }
  tick();
}
// ────────────────────────────────────────────────────────────

function ResultScreen({ form, result, onBack }) {
  const fmt = window.fmtTH;
  const ok = result.surplus >= 0;
  const statusColor = ok ? "var(--color-success)" : "var(--color-danger)";
  const canvasRef = React.useRef(null);
  const bannerRef = React.useRef(null);
  const firedRef  = React.useRef(false);

  React.useEffect(() => {
    firedRef.current = false;
    if (!bannerRef.current || !canvasRef.current) return;
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !firedRef.current) {
          firedRef.current = true;
          const canvas = canvasRef.current;
          canvas.style.display = 'block';
          ok ? runFireworks(canvas) : runRain(canvas);
        }
      },
      { threshold: 0.4 }
    );
    observer.observe(bannerRef.current);
    return () => observer.disconnect();
  }, [result, ok]);


  return (
    <div>
      {/* Fixed canvas for animation */}
      <canvas ref={canvasRef} style={{ display: "none", position: "fixed", inset: 0, width: "100%", height: "100%", pointerEvents: "none", zIndex: 100 }} />
      {/* Phase timeline */}
      <Timeline segments={[
        { weight: result.yearsToRetire, label: `สะสมทรัพย์ ${result.yearsToRetire} ปี`,
          background: "linear-gradient(135deg,#2a9d8f,#264653)" },
        { weight: result.yearsInRetirement, label: `เกษียณ ${result.yearsInRetirement} ปี`,
          background: "linear-gradient(135deg,#f4a261,#e76f51)" },
      ]} />

      {/* Inflation strip */}
      <Card flat style={{ background: "rgba(233,196,106,0.06)", borderColor: "rgba(233,196,106,0.3)", margin: "16px 0" }}>
        <div className="infl-row">
          <div>
            <div className="infl-cap">รายจ่ายวันนี้</div>
            <div className="infl-val">฿{fmt(form.retireMonthlyExpense)}</div>
            <div className="infl-sub">ต่อเดือน</div>
          </div>
          <div className="infl-mid">
            <div>เงินเฟ้อ {form.inflationRate}%/ปี<br />× {result.yearsToRetire} ปี</div>
            <div style={{ fontSize: 18 }}>→</div>
          </div>
          <div>
            <div className="infl-cap" style={{ color: "var(--gold-600)" }}>รายจ่ายตอนเกษียณ</div>
            <div className="infl-val" style={{ color: "var(--gold-600)" }}>฿{fmt(result.retireMonthlyExpenseAdj)}</div>
            <div className="infl-sub">ต่อเดือน</div>
          </div>
        </div>
      </Card>

      {/* Post-retirement income strip — only if there's passive income */}
      {result.totalMonthlyIncome > 0 && (
        <Card flat style={{ background: "rgba(58,140,110,0.05)", borderColor: "rgba(58,140,110,0.22)", marginBottom: 16 }}>
          <div style={{ fontSize: 12, color: "var(--text-muted)", fontWeight: 400, marginBottom: 10 }}>📥 รายรับประจำหลังเกษียณ</div>
          <div className="grid-2">
            <Card accent="var(--color-passive)" flat>
              <div className="hr-stat__label">รวมรายรับ/เดือน</div>
              <div className="hr-stat__value" style={{ color: "var(--color-passive)" }}>฿{fmt(result.totalMonthlyIncome)}</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 3, marginTop: 8 }}>
                {form.monthlyPension > 0 && <div style={{ fontSize: 11, color: "var(--text-muted)", display: "flex", justifyContent: "space-between" }}><span>· บำนาญ</span><span>฿{fmt(form.monthlyPension)}</span></div>}
                {form.monthlySSOPension > 0 && <div style={{ fontSize: 11, color: "var(--text-muted)", display: "flex", justifyContent: "space-between" }}><span>· ประกันสังคม</span><span>฿{fmt(form.monthlySSOPension)}</span></div>}
                {form.monthlyInsurancePension > 0 && <div style={{ fontSize: 11, color: "var(--text-muted)", display: "flex", justifyContent: "space-between" }}><span>· ประกันบำนาญ</span><span>฿{fmt(form.monthlyInsurancePension)}</span></div>}
              </div>
            </Card>
            <Card accent="var(--clay-600)" flat>
              <div className="hr-stat__label">ต้องดึงจากเงินออม/เดือน</div>
              <div className="hr-stat__value" style={{ color: "var(--clay-600)" }}>฿{fmt(result.netMonthlyNeed)}</div>
            </Card>
          </div>
        </Card>
      )}

      {/* 3 summary stat cards */}
      <div className="grid-3">
        <StatCard accent="var(--clay-600)" label="เงินออม ณ เกษียณ"
          value={`฿${fmt(result.totalAtRetirement)}`} sub={`อายุ ${form.retireAge} ปี`} />
        <StatCard accent="var(--teal-500)" label="เงินที่ต้องเตรียม"
          value={`฿${fmt(result.requiredNestEgg)}`} sub={`สำหรับ ${result.yearsInRetirement} ปี`} />
        <StatCard accent={statusColor} valueColor={statusColor}
          label={ok ? "✅ ส่วนเกิน" : "⚠️ ขาดเงิน"}
          value={`${ok ? "+" : ""}฿${fmt(result.surplus)}`}
          sub={ok ? "อยู่ในเส้นทางที่ดี!" : "ต้องปรับแผน"} />
      </div>

      {/* Legacy card */}
      <Card flat style={{
        background: result.legacyAmount > 0 ? "linear-gradient(135deg,#f0fff8,#d4f5e2)" : "linear-gradient(135deg,#fff8f0,#fce8cc)",
        borderColor: result.legacyAmount > 0 ? "var(--color-success)" : "var(--clay-600)",
        borderWidth: 2,
        marginTop: 14,
      }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
          <div>
            <div className="hr-stat__label" style={{ marginBottom: 4 }}>
              🏦 เงินมรดก ณ สิ้นอายุขัย (อายุ {form.lifeExpectancy} ปี)
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: "clamp(20px,4vw,28px)", color: result.legacyAmount > 0 ? "var(--color-success)" : "var(--color-danger)" }}>
              {result.legacyAmount > 0 ? `฿${fmt(result.legacyAmount)}` : "เงินหมดก่อนสิ้นอายุขัย"}
            </div>
            <div className="hr-stat__sub" style={{ marginTop: 4 }}>
              {result.legacyAmount > 0
                ? `หลังใช้จ่าย ${result.yearsInRetirement} ปี · ผลตอบแทน ${form.retireReturn}% · เงินเฟ้อ ${form.inflationRate}%`
                : `เงินออมไม่พอตลอด ${result.yearsInRetirement} ปี`}
            </div>
          </div>
          <div style={{ fontSize: 40 }}>{result.legacyAmount > 0 ? "🎁" : "⚠️"}</div>
        </div>
      </Card>

      {/* Readiness */}
      <Card emphasis style={{ marginTop: 14 }}>
        <div className="hr-stat__label" style={{ marginBottom: 6 }}>ความพร้อมสู่การเกษียณ</div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 30, color: statusColor, marginBottom: 10 }}>
          {result.readyPercent.toFixed(1)}%
        </div>
        <ProgressBar value={Math.min(result.readyPercent, 100)} color={statusColor} />
      </Card>

      {/* Saving plan */}
      <div className="grid-2" style={{ marginTop: 14 }}>
        <StatCard accent="var(--clay-600)" label="💳 ออมอยู่ตอนนี้"
          value={`฿${fmt(result.monthlyContribution)}`} sub={`${form.monthlySavingRate}%/เดือน`} />
        <StatCard accent={statusColor} valueColor={statusColor} label="🎯 ต้องออม"
          value={`฿${fmt(result.requiredMonthlySaving)}`} sub={`${result.requiredSavingRate.toFixed(1)}%/เดือน`} />
      </div>

      {/* Milestones */}
      {result.milestones && result.milestones.length > 0 && (
        <Card flat style={{ borderColor: ok ? "var(--color-success)" : "var(--color-danger)", borderWidth: 1.5, marginTop: 14 }}>
          <div className="hr-stat__label" style={{ marginBottom: 12 }}>🎯 เป้าหมายเงินออมรายทาง (ทุก 5 ปี)</div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            {result.milestones.map((m, i) => (
              <div key={i} style={{ background: "var(--surface-card)", border: `1.5px solid ${m.ok ? "var(--color-success)" : "var(--border-default)"}`, borderRadius: "var(--radius-md)", padding: "10px 14px", minWidth: 130, flex: "1 1 130px" }}>
                <div style={{ fontSize: 12, color: "var(--clay-600)", fontWeight: 400, marginBottom: 6 }}>{m.age}</div>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3 }}>
                  <span style={{ fontSize: 10, color: "var(--text-muted)" }}>เป้าหมาย</span>
                  <span style={{ fontSize: 12 }}>฿{fmt(m.target)}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                  <span style={{ fontSize: 10, color: "var(--text-muted)" }}>ที่ทำได้</span>
                  <span style={{ fontSize: 12, color: m.ok ? "var(--color-success)" : "var(--color-danger)" }}>฿{fmt(m.actual)}</span>
                </div>
                <div style={{ height: 4, background: "var(--surface-sunken)", borderRadius: 2, overflow: "hidden" }}>
                  <div style={{ height: "100%", width: `${Math.min((m.actual / (m.target || 1)) * 100, 100)}%`, background: m.ok ? "var(--color-success)" : "var(--clay-600)", borderRadius: 2 }} />
                </div>
                <div style={{ fontSize: 10, color: m.ok ? "var(--color-success)" : "var(--color-danger)", marginTop: 4, textAlign: "right" }}>
                  {m.ok ? `+฿${fmt(m.actual - m.target)}` : `-฿${fmt(m.target - m.actual)}`}
                </div>
              </div>
            ))}
            {/* Final milestone */}
            <div style={{ background: ok ? "linear-gradient(135deg,#f0fff8,#d4f5e2)" : "rgba(244,162,97,0.10)", border: `2px solid ${ok ? "var(--color-success)" : "var(--clay-600)"}`, borderRadius: "var(--radius-md)", padding: "10px 14px", minWidth: 130, flex: "1 1 130px" }}>
              <div style={{ fontSize: 12, color: "var(--clay-600)", fontWeight: 400, marginBottom: 6 }}>อายุ {form.retireAge} ปี 🏁</div>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3 }}>
                <span style={{ fontSize: 10, color: "var(--text-muted)" }}>เป้าหมาย</span>
                <span style={{ fontSize: 12, color: "var(--clay-600)" }}>฿{fmt(result.requiredNestEgg)}</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                <span style={{ fontSize: 10, color: "var(--text-muted)" }}>ที่ทำได้</span>
                <span style={{ fontSize: 12, color: statusColor }}>฿{fmt(result.totalAtRetirement)}</span>
              </div>
              <div style={{ height: 4, background: "var(--surface-sunken)", borderRadius: 2, overflow: "hidden" }}>
                <div style={{ height: "100%", width: `${Math.min(result.readyPercent, 100)}%`, background: ok ? "var(--color-success)" : "var(--clay-600)", borderRadius: 2 }} />
              </div>
              <div style={{ fontSize: 10, color: statusColor, marginTop: 4, textAlign: "right" }}>
                {ok ? `+฿${fmt(result.surplus)}` : `-฿${fmt(Math.abs(result.surplus))}`}
              </div>
            </div>
          </div>
        </Card>
      )}

      {/* Charts */}
      <div className="chart-grid" style={{ marginTop: 14 }}>
        <Card style={{ background: "var(--surface-inset)" }}>
          <div className="chart-title">📈 รายรับ · ค่าใช้จ่าย · เงินออม</div>
          <AreaLineChart
            data={result.projection}
            width={500}
            height={260}
            series={[
              { key: "savings",  label: "เงินออม",    color: "#c0722a", width: 2.5 },
              { key: "income",   label: "รายรับ",     color: "#2a9d8f", width: 2 },
              { key: "expense",  label: "ค่าใช้จ่าย", color: "#e76f51", width: 2, dash: "5 3" },
            ]}
          />
        </Card>
        <Card style={{ background: "var(--surface-inset)" }}>
          <div className="chart-title">🥧 สัดส่วนแหล่งที่มา</div>
          <SimplePieChart data={result.pie} size={160} />
        </Card>
      </div>

      {/* Banner */}
      <div ref={bannerRef}>
        {ok ? (
        /* ═══ SUCCESS BANNER ═══ */
        <div style={{
          marginTop: 20, borderRadius: "var(--radius-3xl)",
          background: "linear-gradient(135deg,#0a2e28,#0e3d34,#0a2e28)",
          border: "2px solid #2a9d8f88", padding: "36px 28px 28px", textAlign: "center",
        }}>
          {/* Trophy + glow */}
          <div style={{ fontSize: 56, lineHeight: 1, filter: "drop-shadow(0 0 20px #2a9d8f88)", marginBottom: 18 }}>🏆</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: "clamp(22px,4vw,30px)", fontWeight: 400, color: "#2ebfaf", marginBottom: 8 }}>ขอแสดงความยินดี! 🎉</div>
          <div style={{ fontSize: 14, color: "rgba(255,255,255,0.65)", marginBottom: 28 }}>คุณบรรลุเป้าหมายการเกษียณแล้ว!</div>
          {/* 3 stat boxes */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginBottom: 22 }}>
            <div style={{ background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.10)", borderRadius: "var(--radius-lg)", padding: "16px 12px" }}>
              <div style={{ fontSize: 20, marginBottom: 8 }}>💰</div>
              <div style={{ fontSize: 12, color: "rgba(255,255,255,0.55)", marginBottom: 8 }}>มีเงินออม</div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "#2ebfaf" }}>฿{fmt(result.totalAtRetirement)}</div>
            </div>
            <div style={{ background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.10)", borderRadius: "var(--radius-lg)", padding: "16px 12px" }}>
              <div style={{ fontSize: 20, marginBottom: 8 }}>✅</div>
              <div style={{ fontSize: 12, color: "rgba(255,255,255,0.55)", marginBottom: 8 }}>ส่วนเกิน</div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "#2ebfaf" }}>+฿{fmt(result.surplus)}</div>
            </div>
            <div style={{ background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.10)", borderRadius: "var(--radius-lg)", padding: "16px 12px" }}>
              <div style={{ fontSize: 20, marginBottom: 8 }}>📅</div>
              <div style={{ fontSize: 12, color: "rgba(255,255,255,0.55)", marginBottom: 8 }}>เกษียณอายุ</div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "rgba(255,255,255,0.9)" }}>{form.retireAge} ปี</div>
            </div>
          </div>
          <div style={{ fontSize: 13, color: "rgba(255,255,255,0.5)" }}>
            มีเงินเหลือเป็นมรดก <strong style={{ color: "#2ebfaf" }}>฿{fmt(result.legacyAmount)}</strong>
          </div>
        </div>
      ) : (
        /* ═══ SHORTFALL BANNER ═══ */
        <div style={{
          marginTop: 20, borderRadius: "var(--radius-3xl)",
          background: "linear-gradient(135deg,#2a1a08,#321e0a,#2a1a08)",
          border: "2px solid #c0722a88", padding: "36px 28px 28px", textAlign: "center",
        }}>
          {/* Muscle + glow */}
          <div style={{ fontSize: 56, lineHeight: 1, filter: "drop-shadow(0 0 20px #c0722a88)", marginBottom: 18 }}>💪</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: "clamp(22px,4vw,30px)", fontWeight: 400, color: "#f4a261", marginBottom: 8 }}>อย่าหยุดพยายาม!</div>
          <div style={{ fontSize: 14, color: "rgba(255,255,255,0.65)", marginBottom: 28 }}>ทุกบาทที่ออมวันนี้มีค่า</div>
          {/* 3 stat boxes */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginBottom: 22 }}>
            <div style={{ background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.10)", borderRadius: "var(--radius-lg)", padding: "16px 12px" }}>
              <div style={{ fontSize: 20, marginBottom: 8 }}>⚠️</div>
              <div style={{ fontSize: 12, color: "rgba(255,255,255,0.55)", marginBottom: 8 }}>ขาดเงิน</div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "#e76f51" }}>−฿{fmt(Math.abs(result.surplus))}</div>
            </div>
            <div style={{ background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.10)", borderRadius: "var(--radius-lg)", padding: "16px 12px" }}>
              <div style={{ fontSize: 20, marginBottom: 8 }}>📈</div>
              <div style={{ fontSize: 12, color: "rgba(255,255,255,0.55)", marginBottom: 8 }}>ต้องออมเพิ่ม</div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "#f4a261" }}>฿{fmt(Math.abs(result.savingGap))}/เดือน</div>
            </div>
            <div style={{ background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.10)", borderRadius: "var(--radius-lg)", padding: "16px 12px" }}>
              <div style={{ fontSize: 20, marginBottom: 8 }}>⏳</div>
              <div style={{ fontSize: 12, color: "rgba(255,255,255,0.55)", marginBottom: 8 }}>เวลาที่เหลือ</div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "rgba(255,255,255,0.9)" }}>{result.yearsToRetire} ปี</div>
            </div>
          </div>
          <div style={{ fontSize: 13, color: "rgba(255,255,255,0.5)" }}>
            เพิ่มการออมอีกเพียง <strong style={{ color: "#f4a261" }}>฿{fmt(Math.abs(result.savingGap))}/เดือน</strong><br />
            ภายใน {result.yearsToRetire} ปี คุณทำได้แน่นอน! ✨
          </div>
        </div>
      )}

      </div>{/* /banner wrapper */}

      <Button variant="secondary" icon="←" onClick={onBack} style={{ marginTop: 20 }}>
        กลับไปแก้ไขข้อมูล
      </Button>
    </div>
  );
}

window.ResultScreen = ResultScreen;
