// Progress Billing & Retention
function ProgressPage({ lang }) {
  const project = PROJECTS[0]; // PJ-2025-014
  const totalValue = project.value;
  const billedValue = PROGRESS_PERIODS.filter(p => ["paid", "billed"].includes(p.status)).reduce((a, p) => a + p.value, 0);
  const totalRetention = INVOICES.reduce((a, i) => a + i.retention, 0);

  return (
    <div className="anim-fadein">
      <PageHeader
        title={lang === "th" ? "งวดงาน & เงินประกันผลงาน" : "Progress Billing & Retention"}
        subtitle={lang === "th" ? "บริหารการเบิกงวดและเงินประกัน 5% ต่อโครงการ" : "Milestone billing & 5% retention per project"}
        actions={<>
          <select className="field" style={{ width: "auto", height: 36 }}>
            {PROJECTS.filter(p => p.status === "active").map((p) => <option key={p.code}>{p.code} · {p.name}</option>)}
          </select>
        </>}
      />

      {/* Project overview bar */}
      <div className="card" style={{ marginBottom: 14, position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", inset: 0, background: "radial-gradient(800px 300px at 100% 0%, rgba(40,72,255,0.18), transparent 60%)", pointerEvents: "none" }} />
        <div style={{ position: "relative", display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr", gap: 16, alignItems: "center" }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 700 }}>{project.name}</div>
            <div style={{ color: "var(--ink-mute)", fontSize: 12, marginTop: 4 }}>{project.code} · 📍 {project.site} · {lang==="th"?"ส่งมอบ":"Due"} {project.due}</div>
          </div>
          <div><div className="micro">{lang==="th"?"มูลค่าสัญญา":"Contract value"}</div><div className="mono" style={{ fontSize: 18, fontWeight: 700, marginTop: 4 }}>{fmtTHB(totalValue)}</div></div>
          <div><div className="micro">{lang==="th"?"วางบิลแล้ว":"Billed"}</div><div className="mono" style={{ fontSize: 18, fontWeight: 700, marginTop: 4, color: "var(--syk-blue-soft)" }}>{fmtTHB(billedValue)}</div></div>
          <div><div className="micro">{lang==="th"?"เงินประกันคงค้าง":"Retention held"}</div><div className="mono" style={{ fontSize: 18, fontWeight: 700, marginTop: 4, color: "var(--gold)" }}>{fmtTHB(totalRetention)}</div></div>
        </div>

        {/* Progress bar with markers */}
        <div style={{ marginTop: 18, position: "relative" }}>
          <div className="prog" style={{ height: 10, position: "relative", overflow: "visible" }}>
            <span style={{ width: `${project.progress * 100}%` }} />
            {PROGRESS_PERIODS.reduce((acc, p, i) => {
              const prev = acc.cumul || 0;
              const cumul = prev + p.pct * 100;
              acc.markers.push({ ...p, at: prev + p.pct * 50 / 100 * 100, leftPct: prev, widthPct: p.pct * 100 });
              acc.cumul = cumul;
              return acc;
            }, { markers: [], cumul: 0 }).markers.map((m, i) => (
              <div key={i} style={{ position: "absolute", left: `${m.leftPct}%`, top: -2, bottom: -2, width: 2, background: i === 0 ? "transparent" : "rgba(255,255,255,0.4)" }} title={m.name} />
            ))}
          </div>
          <div style={{ position: "relative", height: 24, marginTop: 6 }}>
            {PROGRESS_PERIODS.reduce((acc, p, i) => {
              const cumul = (acc.cumul || 0) + p.pct;
              acc.list.push({ ...p, at: cumul * 100 });
              acc.cumul = cumul;
              return acc;
            }, { list: [], cumul: 0 }).list.map((p, i) => (
              <div key={i} style={{ position: "absolute", left: `${p.at - 4}%`, fontSize: 10, color: "var(--ink-mute)" }} className="mono">{(p.at).toFixed(0)}%</div>
            ))}
          </div>
        </div>
      </div>

      {/* Periods timeline */}
      <div className="card" style={{ padding: 0 }}>
        <div style={{ padding: 16, borderBottom: "1px solid var(--line)" }}>
          <h3 className="h2">{lang==="th"?"งวดงาน":"Milestones"}</h3>
        </div>
        <div style={{ padding: 16 }}>
          {PROGRESS_PERIODS.map((p, i) => {
            const colorMap = { paid: "var(--emerald)", billed: "var(--gold)", ongoing: "var(--syk-blue-soft)", planned: "var(--ink-mute)" };
            const c = colorMap[p.status] || "var(--ink-mute)";
            return (
              <div key={i} style={{ display: "flex", gap: 16, paddingBottom: i < PROGRESS_PERIODS.length - 1 ? 18 : 0, position: "relative", animation: `fadeUp .4s ${i*0.06}s both` }}>
                <div style={{ position: "relative", flexShrink: 0, paddingTop: 4 }}>
                  <div style={{ width: 36, height: 36, borderRadius: "50%", background: `${c}22`, border: `2px solid ${c}`, color: c, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontFamily: "var(--font-mono)", fontSize: 13 }}>{p.no}</div>
                  {i < PROGRESS_PERIODS.length - 1 && <div style={{ position: "absolute", left: 17, top: 44, bottom: -14, width: 2, background: p.status === "paid" ? "var(--emerald)" : "var(--line)" }} />}
                </div>
                <div style={{ flex: 1, padding: "10px 16px", borderRadius: 12, background: "var(--glass-2)", border: "1px solid var(--line)" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12, flexWrap: "wrap" }}>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>{p.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-mute)", marginTop: 4 }}>
                        {fmtPct(p.pct)} · {p.date !== "—" ? `${lang==="th"?"วันที่":"date"} ${p.date}` : (lang==="th"?"ยังไม่ระบุวัน":"date TBD")}
                      </div>
                    </div>
                    <div style={{ textAlign: "right" }}>
                      <div className="mono" style={{ fontSize: 16, fontWeight: 700 }}>{fmtTHB(p.value)}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 2 }} className="mono">+ {fmtTHB(p.value * 0.07)} VAT</div>
                    </div>
                    <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                      <StatusBadge status={p.status} />
                      {p.status === "ongoing" && <button className="btn btn-sm btn-primary"><I.send /> {lang==="th"?"ส่งวางบิล":"Bill now"}</button>}
                      {p.status === "billed" && <button className="btn btn-sm"><I.eye /> {lang==="th"?"ดูใบแจ้งหนี้":"View invoice"}</button>}
                    </div>
                  </div>

                  {p.status === "paid" && (
                    <div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px dashed var(--line)", display: "flex", gap: 14, fontSize: 11.5 }}>
                      <span><span className="ink-mute">{lang==="th"?"หัก ณ ที่จ่าย":"WHT"}: </span><span className="mono" style={{ color: "var(--rose)" }}>−{fmtTHB(p.value * 0.03)}</span></span>
                      <span><span className="ink-mute">{lang==="th"?"เงินประกัน":"Retention"}: </span><span className="mono" style={{ color: "var(--gold)" }}>−{fmtTHB(p.value * 0.05)}</span></span>
                      <span><span className="ink-mute">{lang==="th"?"รับจริง":"Net received"}: </span><span className="mono" style={{ color: "var(--emerald)" }}>{fmtTHB(p.value * 1.07 * 0.92)}</span></span>
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Retention ledger */}
      <div className="card" style={{ marginTop: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
          <h3 className="h2">{lang==="th"?"บัญชีเงินประกันผลงาน":"Retention ledger"}</h3>
          <button className="btn btn-sm"><I.cash /> {lang==="th"?"คืนเงินประกัน":"Release"}</button>
        </div>
        <table className="table">
          <thead><tr>
            <th>{lang==="th"?"งวด":"Period"}</th><th>{lang==="th"?"จากใบแจ้งหนี้":"From invoice"}</th><th style={{textAlign:"right"}}>{lang==="th"?"จำนวน":"Amount"}</th><th>{lang==="th"?"กำหนดคืน":"Release date"}</th><th>Status</th>
          </tr></thead>
          <tbody>
            {INVOICES.filter(i => i.status !== "draft").map((inv, i) => (
              <tr key={inv.id} className="row-int">
                <td>{inv.period}</td>
                <td className="mono" style={{ fontSize: 12, color: "var(--syk-blue-soft)" }}>{inv.id}</td>
                <td className="mono" style={{ textAlign: "right", fontWeight: 600, color: "var(--gold)" }}>{fmtTHB(inv.retention)}</td>
                <td className="mono ink-soft" style={{ fontSize: 12 }}>{new Date(new Date(inv.date).getTime() + 365 * 24 * 3600 * 1000).toISOString().slice(0, 10)}</td>
                <td><span className="chip gold"><I.lock size={10} />{lang==="th"?"ถือไว้":"Holding"}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.ProgressPage = ProgressPage;
