// FiveYearPlan.jsx — "แผนทุก 5 ปี" tab
// Shows summary chips, a dot timeline, and a detailed card per 5-year checkpoint.

const { ProgressBar } = window.HappyRetirementDesignSystem_d542ec;
const fmt = window.fmtTH;
const fmtShort = (n) => n >= 1e6 ? `฿${(n/1e6).toFixed(1)}M` : n >= 1000 ? `฿${(n/1000).toFixed(0)}K` : `฿${fmt(n)}`;

function SummaryChip({ label, value }) {
  return (
    <div style={{
      flex: "1 1 0", minWidth: 130, padding: "14px 16px",
      background: "var(--surface-card)", border: "1.5px solid var(--border-default)",
      borderRadius: "var(--radius-lg)", textAlign: "center",
    }}>
      <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 8 }}>{label}</div>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "var(--text-brand)" }}>{value}</div>
    </div>
  );
}

function DotTimeline({ points }) {
  return (
    <div style={{
      background: "var(--surface-card)", border: "1.5px solid var(--border-default)",
      borderRadius: "var(--radius-lg)", padding: "20px 24px", marginBottom: 20,
    }}>
      <div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: 14, fontWeight: 400, letterSpacing: "0.08em", textTransform: "uppercase" }}>เส้นทางเงินออม</div>
      <div style={{ position: "relative" }}>
        {/* Track line */}
        <div style={{ position: "absolute", top: 10, left: "calc(50px / 2)", right: "calc(50px / 2)", height: 3, background: "var(--border-default)", borderRadius: 2 }}></div>
        <div style={{ display: "flex", justifyContent: "space-between", position: "relative" }}>
          {points.map((p, i) => {
            const isLast = i === points.length - 1;
            const dotColor = p.ok ? "#2a9d8f" : p.isStart ? "#8a7060" : "var(--color-primary)";
            return (
              <div key={i} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 5, flex: isLast ? "0 0 50px" : 1, maxWidth: 90 }}>
                {/* dot */}
                <div style={{
                  width: 22, height: 22, borderRadius: "50%",
                  background: dotColor, border: "3px solid var(--surface-card)",
                  boxShadow: `0 0 0 2px ${dotColor}`,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  position: "relative", zIndex: 1,
                }}>
                  {p.ok && <span style={{ fontSize: 9, color: "#fff" }}>✓</span>}
                </div>
                {/* age label */}
                <div style={{ fontSize: 11, fontWeight: 400, color: "var(--text-body)", textAlign: "center" }}>
                  {p.ageLabel}
                </div>
                {/* sub-label */}
                <div style={{ fontSize: 10, color: "var(--text-muted)", textAlign: "center" }}>{p.subLabel}</div>
                {/* amount */}
                <div style={{ fontSize: 11, fontFamily: "var(--font-display)", color: p.ok ? "#2a9d8f" : "var(--text-brand)", textAlign: "center" }}>
                  {p.amountLabel}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function MilestoneCard({ m }) {
  const ok = m.ok;
  const accentColor = ok ? "#2a9d8f" : "var(--color-danger)";
  const pct = m.target > 0 ? Math.min((m.actual / m.target) * 100, 100) : 100;

  return (
    <div style={{
      border: `1.5px solid ${ok ? "#2a9d8f55" : "var(--border-default)"}`,
      borderLeft: `3px solid ${accentColor}`,
      borderRadius: "var(--radius-lg)", marginBottom: 14, overflow: "hidden",
    }}>
      {/* Header */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "12px 16px", background: ok ? "rgba(42,157,143,0.07)" : "var(--surface-inset)",
        flexWrap: "wrap", gap: 8,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 10, height: 10, borderRadius: "50%", background: accentColor, boxShadow: `0 0 8px ${accentColor}` }}></div>
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 400, fontSize: 15, color: accentColor }}>
            อายุ {m.age} ปี
          </span>
          <span style={{ fontSize: 12, color: "var(--text-muted)" }}>
            · อีก {m.yearsFromNow} ปี · เหลือ {m.yearsToRetire} ปีก่อนเกษียณ
          </span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 15, color: accentColor, fontWeight: 400 }}>
            {ok ? "+" : ""}฿{fmt(m.actual)}
          </span>
          <span style={{
            fontSize: 11, fontWeight: 400, padding: "3px 10px", borderRadius: "var(--radius-pill)",
            border: `1.5px solid ${accentColor}`, color: ok ? "#fff" : "var(--text-body)",
            background: ok ? accentColor : "transparent",
          }}>
            {ok ? "✅ ตามเป้า" : "⚠️ ต่ำกว่าเป้า"}
          </span>
        </div>
      </div>

      {/* Body */}
      <div style={{ padding: "16px", background: "var(--surface-card)" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 24px" }}>
          {/* TL: principal */}
          <div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>
              💰 เงินต้นที่ออมสะสม
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 26, color: "var(--text-heading)" }}>
              ฿{fmt(m.principal)}
            </div>
            <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 2 }}>รวมเงินออมเดิม + ออมใหม่</div>
          </div>

          {/* TR: returns */}
          <div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>
              📈 กำไรจากผลตอบแทน
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 26, color: "#2a9d8f" }}>
              +฿{fmt(m.returns)}
            </div>
            <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 2 }}>ดอกเบี้ยทบต้น {m.returnRate}% / ปี</div>
          </div>

          {/* BL: total */}
          <div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>
              🏦 มูลค่ารวม ณ อายุนี้
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 26, color: accentColor }}>
              ฿{fmt(m.actual)}
            </div>
            <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 2 }}>เงินต้น + กำไรจากการลงทุน</div>
          </div>

          {/* BR: target */}
          <div>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>
              🎯 เป้าหมาย ณ จุดนี้
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 26, color: "var(--text-heading)" }}>
              ฿{fmt(m.target)}
            </div>
            <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 2 }}>ต้องมีเพื่อเกษียณตามแผน</div>
          </div>
        </div>

        {/* Progress */}
        <div style={{ marginTop: 16 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
            <span style={{ fontSize: 12, color: "var(--text-muted)" }}>ความคืบหน้าสู่เป้าหมาย</span>
            <span style={{ fontSize: 13, fontFamily: "var(--font-display)", color: accentColor }}>{pct.toFixed(1)}%</span>
          </div>
          <ProgressBar value={pct} color={accentColor} />
        </div>

        {/* Motivational message */}
        <div style={{
          marginTop: 12, padding: "10px 14px",
          background: ok ? "rgba(42,157,143,0.08)" : "rgba(192,114,42,0.08)",
          borderRadius: "var(--radius-md)",
          fontSize: 12, color: ok ? "#2a9d8f" : "var(--text-brand)",
        }}>
          {ok
            ? `✨ เกินเป้า ฿${fmt(m.actual - m.target)} · ยังคงออมต่อเนื่องเพื่อสร้างส่วนเกินเมื่อเกษียณ`
            : `💪 ขาดอีก ฿${fmt(m.target - m.actual)} · เพิ่มออมได้เพื่อให้ถึงเป้าหมายในจุดนี้`}
        </div>
      </div>
    </div>
  );
}

function FiveYearPlan({ form, result }) {
  const rPre = form.expectedReturn / 100;
  const annualContrib = result.monthlyContribution * 12;
  const yearsToRetire = result.yearsToRetire;

  // Build 5-year checkpoints from currentAge+5 up to retireAge (inclusive)
  const checkpoints = [];
  for (let age = form.currentAge + 5; age <= form.retireAge; age += 5) {
    const yrs = age - form.currentAge;
    // principal = initial savings + contributions (simple sum, before compounding)
    const principal = Math.round(form.currentSavings + annualContrib * yrs);
    // actual total from projection
    const proj = result.projection.find(p => p.age === age);
    const actual = proj ? proj.savings : 0;
    const returns = Math.max(0, actual - principal);
    // proportional target
    const targetFrac = yrs / yearsToRetire;
    const target = Math.round(result.requiredNestEgg * targetFrac);
    checkpoints.push({
      age,
      yearsFromNow: yrs,
      yearsToRetire: Math.max(0, form.retireAge - age),
      principal,
      returns,
      actual,
      target,
      ok: actual >= target,
      returnRate: form.expectedReturn,
    });
  }

  // Timeline points: start + every 5 years
  const timelinePoints = [
    {
      ageLabel: `อายุ ${form.currentAge} ปี`,
      subLabel: "เริ่มต้น",
      amountLabel: "฿0",
      ok: false, isStart: true,
    },
    ...checkpoints.map(m => ({
      ageLabel: `${m.age} ปี`,
      subLabel: m.ok ? "✅" : "⚠",
      amountLabel: fmtShort(m.actual),
      ok: m.ok, isStart: false,
    })),
  ];
  // Last point: retirement
  const lastPoint = timelinePoints[timelinePoints.length - 1];
  if (lastPoint.ageLabel !== `${form.retireAge} ปี`) {
    timelinePoints[timelinePoints.length - 1] = {
      ...lastPoint,
      ageLabel: `อายุ ${form.retireAge} ปี ⚙️`,
      subLabel: "เกษียณ",
    };
  } else {
    timelinePoints[timelinePoints.length - 1] = {
      ...lastPoint,
      ageLabel: `อายุ ${form.retireAge} ปี ⚙️`,
      subLabel: "เกษียณ",
      amountLabel: fmtShort(result.totalAtRetirement),
    };
  }

  return (
    <div>
      {/* Summary chips */}
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 20 }}>
        <SummaryChip label="ออมต่อเดือน" value={`฿${fmt(Math.round(result.monthlyContribution))}`} />
        <SummaryChip label="ผลตอบแทน" value={`${form.expectedReturn}% / ปี`} />
        <SummaryChip label="เวลาสะสม" value={`${yearsToRetire} ปี`} />
        <SummaryChip label="เป้าเกษียณ" value={`${form.retireAge} ปี`} />
      </div>

      {/* Timeline */}
      <DotTimeline points={timelinePoints} />

      {/* Milestone cards */}
      {checkpoints.map((m, i) => (
        <MilestoneCard key={i} m={m} />
      ))}
    </div>
  );
}

window.FiveYearPlan = FiveYearPlan;
