// Dashboard — KPIs, cashflow chart, project list, recent activity

function DashboardPage({ lang }) {
  const totalValue   = PROJECTS.reduce((a, p) => a + p.value, 0);
  const activeCount  = PROJECTS.filter(p => p.status === "active").length;
  const billedThis   = INVOICES.filter(i => i.status !== "draft").reduce((a, i) => a + i.net, 0);
  const retentionHeld = INVOICES.reduce((a, i) => a + i.retention, 0);

  return (
    <div className="anim-fadein">
      <PageHeader
        title={lang === "th" ? "แดชบอร์ด" : "Dashboard"}
        subtitle={lang === "th" ? "ภาพรวมโครงการ การเงิน และเอกสารที่รออนุมัติ" : "Project, finance, and approval overview"}
        actions={<>
          <button className="btn btn-sm"><I.calendar /> Q4 2025</button>
          <button className="btn btn-sm btn-primary"><I.plus /> {lang === "th" ? "โครงการใหม่" : "New project"}</button>
        </>}
      />

      {/* KPI cards */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 14 }}>
        <StatCard label={lang === "th" ? "มูลค่าโครงการรวม" : "Total contract value"} value={fmtTHB(totalValue)} delta={12.4} icon="cash" accent="rgba(40,72,255,0.25)" />
        <StatCard label={lang === "th" ? "โครงการที่ดำเนินการ" : "Active projects"}     value={activeCount} hint={lang === "th" ? `จาก ${PROJECTS.length} รายการ` : `of ${PROJECTS.length}`} icon="grid" accent="rgba(140,80,255,0.22)" />
        <StatCard label={lang === "th" ? "วางบิลเดือนนี้" : "Billed this month"}         value={fmtTHB(billedThis)} delta={8.1} icon="receipt" accent="rgba(255,107,138,0.20)" />
        <StatCard label={lang === "th" ? "เงินประกันคงค้าง" : "Retention held"}           value={fmtTHB(retentionHeld)} hint={lang === "th" ? "ปล่อย 30 มี.ค." : "Release: 30 Mar"} icon="lock" accent="rgba(246,201,124,0.22)" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 14, marginTop: 14 }} className="dash-grid">
        <CashflowChart lang={lang} />
        <ApprovalQueue lang={lang} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 14, marginTop: 14 }} className="dash-grid">
        <ProjectsList lang={lang} />
        <RecentActivity lang={lang} />
      </div>

      <style>{`
        @media (max-width: 1100px) {
          .dash-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

// ── Cashflow chart ───────────────────────────────────────────
function CashflowChart({ lang }) {
  const months = ["ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];
  const billed = [1.2, 1.8, 2.4, 1.6, 3.1, 2.2];   // millions
  const cost   = [0.9, 1.3, 1.8, 1.4, 2.4, 1.7];
  const w = 600, h = 240, padL = 40, padR = 16, padT = 16, padB = 28;
  const maxY = 4;
  const xs = (i) => padL + (i * (w - padL - padR)) / (months.length - 1);
  const ys = (v) => padT + (1 - v / maxY) * (h - padT - padB);

  const pathB = "M " + billed.map((v, i) => `${xs(i)} ${ys(v)}`).join(" L ");
  const pathC = "M " + cost.map((v, i) => `${xs(i)} ${ys(v)}`).join(" L ");
  const areaB = pathB + ` L ${xs(billed.length-1)} ${ys(0)} L ${xs(0)} ${ys(0)} Z`;

  return (
    <div className="card">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 6 }}>
        <div>
          <div className="micro">{lang === "th" ? "กระแสเงินสด" : "Cashflow"}</div>
          <h3 className="h2" style={{ marginTop: 4 }}>{lang === "th" ? "วางบิล vs ต้นทุน" : "Billing vs Cost"} <span className="mono ink-mute" style={{ fontSize: 12, fontWeight: 400 }}>(฿ ล้าน)</span></h3>
        </div>
        <div style={{ display: "flex", gap: 14, fontSize: 11.5 }}>
          <span style={{ display:"inline-flex", alignItems:"center", gap:6, color:"var(--ink-soft)"}}><span style={{width:8,height:8,borderRadius:2,background:"var(--syk-blue-soft)"}}/>{lang==="th"?"วางบิล":"Billed"}</span>
          <span style={{ display:"inline-flex", alignItems:"center", gap:6, color:"var(--ink-soft)"}}><span style={{width:8,height:8,borderRadius:2,background:"var(--rose)"}}/>{lang==="th"?"ต้นทุน":"Cost"}</span>
        </div>
      </div>

      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: 240, display: "block" }}>
        <defs>
          <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="rgba(111,134,255,0.4)" />
            <stop offset="100%" stopColor="rgba(111,134,255,0)" />
          </linearGradient>
        </defs>
        {[0, 1, 2, 3, 4].map((v) => (
          <g key={v}>
            <line x1={padL} x2={w - padR} y1={ys(v)} y2={ys(v)} stroke="var(--line)" strokeDasharray="2 4" />
            <text x={padL - 8} y={ys(v) + 4} textAnchor="end" fill="var(--ink-mute)" fontSize="10" fontFamily="JetBrains Mono, monospace">{v.toFixed(1)}M</text>
          </g>
        ))}
        {months.map((m, i) => (
          <text key={m} x={xs(i)} y={h - 8} textAnchor="middle" fill="var(--ink-mute)" fontSize="10.5" fontFamily="Inter, sans-serif">{m}</text>
        ))}
        <path d={areaB} fill="url(#areaGrad)" style={{ animation: "fadeIn .8s .2s both" }} />
        <path d={pathB} stroke="#6f86ff" strokeWidth="2" fill="none" strokeLinejoin="round"
              strokeDasharray="2000" style={{ animation: `drawLine 1.6s cubic-bezier(.2,.7,.2,1) both` }} />
        <path d={pathC} stroke="#ff6b8a" strokeWidth="2" fill="none" strokeLinejoin="round" strokeDasharray="4 3"
              style={{ animation: `drawLine 1.6s .3s cubic-bezier(.2,.7,.2,1) both` }} />
        {billed.map((v, i) => (
          <g key={i}>
            <circle cx={xs(i)} cy={ys(v)} r="4" fill="var(--bg-0)" stroke="#6f86ff" strokeWidth="2" style={{ animation: `fadeIn .4s ${1 + i*0.08}s both` }} />
            <circle cx={xs(i)} cy={ys(cost[i])} r="3" fill="var(--bg-0)" stroke="#ff6b8a" strokeWidth="1.7" style={{ animation: `fadeIn .4s ${1.2 + i*0.08}s both` }} />
          </g>
        ))}
      </svg>
    </div>
  );
}

// ── Approval queue ───────────────────────────────────────────
function ApprovalQueue({ lang }) {
  const items = [
    { kind: "PR", code: "PR-2025-081", who: "ช.วินัย", amount: 186_500, prj: "PJ-2025-013", age: "2 ชม." },
    { kind: "BOQ", code: "QT-2025-038", who: "QS สมพร", amount: 4_850_000, prj: "PJ-2025-014", age: "5 ชม." },
    { kind: "INV", code: "INV-2025-044", who: "บัญชี", amount: 311_850, prj: "PJ-2025-010", age: "1 วัน" },
  ];
  const toast = useToast();
  return (
    <div className="card">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
        <h3 className="h2">{lang === "th" ? "รออนุมัติ" : "Awaiting approval"}</h3>
        <span className="chip warn"><span className="chip-dot" />{items.length} {lang === "th" ? "รายการ" : "items"}</span>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {items.map((it, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: 10, borderRadius: 10, background: "var(--glass-2)", border: "1px solid var(--line)" }}>
            <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--glass-3)", border: "1px solid var(--line)", display:"flex", alignItems:"center", justifyContent:"center", fontSize: 10.5, fontWeight: 700, color: "var(--syk-blue-soft)", fontFamily: "var(--font-mono)" }}>{it.kind}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{it.code}</div>
              <div style={{ fontSize: 11.5, color: "var(--ink-mute)" }}>{it.prj} · {it.who} · {it.age}{lang === "en" ? " ago" : ""}</div>
            </div>
            <div className="mono" style={{ fontSize: 13, fontWeight: 600, textAlign: "right" }}>{fmtTHB(it.amount)}</div>
            <div style={{ display: "flex", gap: 4 }}>
              <button className="btn btn-sm" style={{ padding: 0, width: 28, justifyContent:"center", color:"var(--rose)" }} onClick={() => toast("ปฏิเสธ " + it.code, "danger")}><I.x /></button>
              <button className="btn btn-sm btn-primary" style={{ padding: 0, width: 28, justifyContent:"center" }} onClick={() => toast("อนุมัติ " + it.code + " แล้ว", "success")}><I.check /></button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Projects list ────────────────────────────────────────────
function ProjectsList({ lang }) {
  return (
    <div className="card">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
        <h3 className="h2">{lang === "th" ? "โครงการ" : "Projects"}</h3>
        <button className="btn btn-sm btn-ghost">{lang === "th" ? "ดูทั้งหมด" : "View all"} <I.chev /></button>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {PROJECTS.filter(p => p.status === "active").map((p, i) => (
          <div key={p.code} style={{ padding: 12, borderRadius: 12, background: "var(--glass-2)", border: "1px solid var(--line)", animation: `fadeUp .4s ${i*0.06}s both` }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12, marginBottom: 8 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span className="mono" style={{ fontSize: 11, color: "var(--syk-blue-soft)", padding: "2px 6px", background: "rgba(40,72,255,0.12)", borderRadius: 4 }}>{p.code}</span>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>{p.name}</span>
                </div>
                <div style={{ fontSize: 11.5, color: "var(--ink-mute)", marginTop: 4 }}>📍 {p.site} · {lang === "th" ? "ส่งมอบ" : "Due"} {p.due}</div>
              </div>
              <div className="mono" style={{ fontSize: 14, fontWeight: 700, textAlign: "right" }}>{fmtTHB(p.value)}</div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div className="prog" style={{ flex: 1 }}><span style={{ width: `${p.progress*100}%` }} /></div>
              <span className="mono ink-soft" style={{ fontSize: 11 }}>{fmtPct(p.progress)}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Recent activity ──────────────────────────────────────────
function RecentActivity({ lang }) {
  const events = [
    { who: "นภา", what: lang === "th" ? "ออก PO-2025-064" : "Issued PO-2025-064", when: "10 นาทีที่แล้ว", color: "#4ade80" },
    { who: "วินัย", what: lang === "th" ? "บันทึกรับของหน้างาน PJ-2025-014" : "Goods received PJ-2025-014", when: "1 ชม.", color: "#6f86ff" },
    { who: "สมพร", what: lang === "th" ? "ส่ง BOQ QT-2025-038 รออนุมัติ" : "Submitted BOQ QT-2025-038", when: "5 ชม.", color: "#f6c97c" },
    { who: "การเงิน", what: lang === "th" ? "INV-2025-041 ได้รับชำระแล้ว" : "INV-2025-041 paid", when: "1 วัน", color: "#ff6b8a" },
    { who: "PM", what: lang === "th" ? "ปิดงวดที่ 3 PJ-2025-014" : "Closed milestone 3 PJ-2025-014", when: "1 วัน", color: "#ffb84d" },
  ];
  return (
    <div className="card">
      <h3 className="h2" style={{ marginBottom: 12 }}>{lang === "th" ? "กิจกรรมล่าสุด" : "Recent activity"}</h3>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {events.map((e, i) => (
          <div key={i} style={{ display: "flex", gap: 12, animation: `fadeUp .4s ${i*0.08}s both` }}>
            <div style={{ position: "relative" }}>
              <div style={{ width: 30, height: 30, borderRadius: "50%", background: `${e.color}22`, border: `1px solid ${e.color}66`, display: "flex", alignItems: "center", justifyContent: "center", color: e.color, fontSize: 11, fontWeight: 600 }}>{e.who[0]}</div>
              {i < events.length - 1 && <div style={{ position: "absolute", left: 14, top: 32, width: 1.5, height: "100%", background: "var(--line)" }} />}
            </div>
            <div style={{ flex: 1, paddingBottom: 4 }}>
              <div style={{ fontSize: 12.5 }}><b>{e.who}</b> <span className="ink-soft">{e.what}</span></div>
              <div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 2 }}>{e.when}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.DashboardPage = DashboardPage;
