// หน้าแดชบอร์ด
function GlobalSearch({ ui, go }) {
  const { st } = useStore();
  const [q, setQ] = React.useState("");
  const ql = q.trim().toLowerCase();
  const hits = ql.length < 2 ? [] : [
    ...st.products.filter((p) => (p.name + p.sku + p.barcode + (p.brand || "")).toLowerCase().includes(ql)).slice(0, 4)
      .map((p) => ({ icon: "▣", title: p.name, sub: `สินค้า · ${p.sku} · คงเหลือ ${stockTotal(p)}`, page: "stock" })),
    ...st.repairs.filter((r) => (r.id + r.customer + r.phone + r.device + (r.imei || "")).toLowerCase().includes(ql)).slice(0, 4)
      .map((r) => ({ icon: "⚙", title: `${r.id} · ${r.device}`, sub: `งานซ่อม · ${r.customer} · ${r.status}`, page: "repairs", param: r.id })),
    ...st.sales.filter((s) => (s.id + s.customer).toLowerCase().includes(ql)).slice(0, 3)
      .map((s) => ({ icon: "⧉", title: s.id, sub: `บิลขาย · ${s.customer} · ${fmtMoney(saleTotal(s))}`, page: "reports" })),
  ];
  return (
    <Card style={{ padding: "6px 8px", position: "relative", zIndex: 30 }}>
      <SearchBox value={q} onChange={setQ} placeholder="ค้นหาทุกอย่าง — สินค้า / SKU / IMEI / ใบซ่อม / ลูกค้า / บิล…" />
      {hits.length > 0 && (
        <div style={{ position: "absolute", top: "100%", left: 8, right: 8, marginTop: 4, background: "#fff", borderRadius: 14, boxShadow: "0 18px 48px rgba(10,18,42,.22)", border: `1px solid ${T.border}`, overflow: "hidden", animation: "ss-rise .18s ease" }}>
          {hits.map((h, i) => (
            <div key={i} className="ss-row" onClick={() => { go(h.page, h.param); setQ(""); }} style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 16px", cursor: "pointer", borderBottom: i < hits.length - 1 ? `1px solid ${T.rowBorder}` : "none", fontSize: 13 }}>
              <span style={{ width: 30, height: 30, borderRadius: 8, background: T.infoBg, color: T.primary, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, flex: "none" }}>{h.icon}</span>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{h.title}</div>
                <div style={{ fontSize: 11.5, color: T.sub }}>{h.sub}</div>
              </div>
              <span style={{ marginLeft: "auto", color: T.sub, fontSize: 11 }}>ไปที่หน้า →</span>
            </div>
          ))}
        </div>
      )}
    </Card>
  );
}

function DashboardPage({ ui, go }) {
  const { st } = useStore();
  const DAY = 86400000;
  const today0 = new Date(); today0.setHours(0, 0, 0, 0);
  // พนักงานขาย/ช่าง/สต็อก เห็นเฉพาะข้อมูลสาขาที่สังกัด (ยกเว้นความเคลื่อนไหวล่าสุดที่เห็นรวมทุกสาขา)
  const dashUser = st.users.find((u) => u.id === ui.userId) || st.users[0];
  const dashRole = st.roles[dashUser.role] || {};
  const scopeBranch = dashRole.allBranch ? ui.branch : (dashUser.branch || ui.branch);
  const inBranch = (b) => scopeBranch === "ALL" || b === scopeBranch;

  const salesToday = st.sales.filter((s) => inBranch(s.branch) && s.ts >= today0.getTime());
  const sumToday = salesToday.reduce((a, s) => a + saleTotal(s), 0);
  const openRepairs = st.repairs.filter((r) => inBranch(r.branch) && !["ส่งมอบแล้ว", "ยกเลิก"].includes(r.status));
  const overdue = openRepairs.filter((r) => r.due && r.due < Date.now());
  const buyToday = st.buyins.filter((b) => inBranch(b.branch) && b.ts >= today0.getTime());
  const partCatNames = st.cats.filter((c) => c.parts).map((c) => c.name);
  const lowAll = st.products.filter((p) => {
    const q = scopeBranch === "ALL" ? stockTotal(p) : stockInBranch(st, p, scopeBranch);
    return p.reorder > 0 && q > 0 && q <= p.reorder;
  });
  const low = lowAll.filter((p) => !partCatNames.includes(p.cat));
  const lowParts = lowAll.filter((p) => partCatNames.includes(p.cat));

  // 7-day series
  const COLORS = T.chartPalette;
  const dayStarts = [...Array(7)].map((_, i) => today0.getTime() - (6 - i) * DAY);
  const labels = dayStarts.map((d0) => new Date(d0).toLocaleDateString("th-TH", { day: "2-digit", month: "2-digit" }));
  // ยอดสุทธิ (หักส่วนลดบิลตามสัดส่วนของแต่ละรายการ) เพื่อให้ตรงกับยอดขายจริง
  const salesIn = (d0, pred) => st.sales.filter((s) => inBranch(s.branch) && s.ts >= d0 && s.ts < d0 + DAY)
    .reduce((a, s) => {
      const gross = s.items.reduce((x, i) => x + i.qty * i.price, 0);
      const matched = s.items.filter(pred).reduce((x, i) => x + i.qty * i.price, 0);
      const net = gross > 0 ? matched - (s.discount || 0) * (matched / gross) : 0;
      return a + net;
    }, 0);
  const isDevice = (i) => { const c = ((prodOf(st, i.productId) || {}).cat || ""); return c.startsWith("เครื่อง") || c === "Notebook/MacBook"; };
  const deviceSeries = dayStarts.map((d0) => salesIn(d0, isDevice));
  const accSeries = dayStarts.map((d0) => salesIn(d0, (i) => !isDevice(i)));
  // รายได้งานช่าง = ค่าซ่อมของงานที่ "ส่งมอบแล้ว" คิดในวันที่ส่งมอบลูกค้าจริงเท่านั้น
  const repairSeries = dayStarts.map((d0) => st.repairs.filter((r) => inBranch(r.branch) && r.status === "ส่งมอบแล้ว")
    .reduce((a, r) => { const t = r.deliveredAt || r.due || r.ts; return a + (t >= d0 && t < d0 + DAY ? (r.est || 0) : 0); }, 0));
  const sum7 = deviceSeries.concat(accSeries).reduce((a, b) => a + b, 0);
  const sumRepair7 = repairSeries.reduce((a, b) => a + b, 0);
  // ①② ยอดขาย 7 วัน — แท่งแนวตั้งแยก เครื่อง/อุปกรณ์/ช่าง
  const salesBars = [
    { label: "เครื่อง", color: T.c1, data: deviceSeries },
    { label: "อุปกรณ์", color: T.c2, data: accSeries },
    { label: "ช่าง/ซ่อม", color: T.c3, data: repairSeries },
  ];
  // ③ ยอดรวมรายสาขา — 3 วันล่าสุด แท่งแนวตั้งแยกต่อสาขา
  const days3 = dayStarts.slice(-3);
  const labels3 = days3.map((d0) => new Date(d0).toLocaleDateString("th-TH", { day: "2-digit", month: "2-digit" }));
  const branchBars = st.branches.filter((b) => scopeBranch === "ALL" || b.id === scopeBranch).map((b, bi) => ({
    label: b.short, color: COLORS[bi % COLORS.length],
    data: days3.map((d0) => st.sales.filter((s) => s.branch === b.id && s.ts >= d0 && s.ts < d0 + DAY).reduce((a, s) => a + saleTotal(s), 0)),
  }));

  const recentRepairs = st.repairs.filter((r) => inBranch(r.branch)).slice(0, 5);
  const recentMoves = st.moves.slice(0, 6);

  // ④ รายรับรายเดือน (เงินสด + โอน/บัตร) ย้อนหลัง 6 เดือน รวมเดือนล่าสุด — จากการเคลียร์ยอดรายวัน
  const monthLabels = [];
  const monthIncome = [];
  const baseD = new Date(today0);
  for (let i = 5; i >= 0; i--) {
    const d = new Date(baseD.getFullYear(), baseD.getMonth() - i, 1);
    const mStart = d.getTime();
    const mEnd = new Date(d.getFullYear(), d.getMonth() + 1, 1).getTime();
    monthLabels.push(d.toLocaleDateString("th-TH", { month: "short", year: "2-digit" }));
    monthIncome.push(st.dailyClears.filter((c) => inBranch(c.branch) && c.date >= mStart && c.date < mEnd).reduce((a, c) => a + (c.cash || 0) + (c.transfer || 0), 0));
  }
  const monthIncomeTotal = monthIncome.reduce((a, b) => a + b, 0);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <GlobalSearch ui={ui} go={go} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
        <StatCard hero label="ยอดขายวันนี้" value={sumToday} money sub={`${salesToday.length} บิล`} delay={0} />
        <StatCard label="งานซ่อมค้างอยู่" value={openRepairs.length} sub={overdue.length ? `${overdue.length} งานเกินกำหนด` : "ไม่มีงานเกินกำหนด"} accent={overdue.length > 0} delay={60} />
        <StatCard label="รับซื้อ/เทิร์นวันนี้" value={buyToday.length} sub={fmtMoney(buyToday.reduce((a, b) => a + b.price, 0))} delay={120} />
        <StatCard label="สต็อกใกล้หมด" value={low.length + lowParts.length} sub="ต่ำกว่าจุดสั่งซื้อ" accent={(low.length + lowParts.length) > 0} delay={180} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.7fr 1fr", gap: 14 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {/* ①② ยอดขาย 7 วัน — แท่งแนวตั้งแยก เครื่อง/อุปกรณ์/ช่าง */}
          <Card style={{ padding: "16px 20px", animation: "ss-rise .5s 120ms cubic-bezier(.2,.9,.3,1.1) backwards" }}>
            <SectionTitle right={<ChartLegend items={salesBars.map((s) => ({ label: s.label, color: s.color }))} />}>
              ยอดขาย 7 วันล่าสุด <span style={{ color: T.sub, fontWeight: 500, fontSize: 12.5 }}>รวมขาย {fmtMoney(sum7)} · ซ่อม {fmtMoney(sumRepair7)}</span>
            </SectionTitle>
            <BarChart groups={labels} series={salesBars} height={190} />
          </Card>

          {/* ③ ยอดรวมรายสาขา 3 วัน — แท่งแนวตั้งแยกแต่ละสาขา */}
          <Card style={{ padding: "16px 20px", animation: "ss-rise .5s 200ms cubic-bezier(.2,.9,.3,1.1) backwards" }}>
            <SectionTitle right={<ChartLegend items={branchBars.map((b) => ({ label: b.label, color: b.color }))} />}>
              ยอดขายรวมแยกรายสาขา (3 วันล่าสุด)
            </SectionTitle>
            <BarChart groups={labels3} series={branchBars} height={205} />
          </Card>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14, alignSelf: "start" }}>
        <Card style={{ padding: "16px 20px", display: "flex", flexDirection: "column", gap: 11, animation: "ss-rise .5s 180ms cubic-bezier(.2,.9,.3,1.1) backwards" }}>
          <SectionTitle right={<a className="ss-link" onClick={() => go("stock")}>ดูทั้งหมด →</a>}>สต็อกใกล้หมด</SectionTitle>
          {low.length === 0 && <EmptyState icon="✓" text="สต็อกเพียงพอทุกรายการ" />}
          {low.slice(0, 5).map((p) => {
            const q = scopeBranch === "ALL" ? stockTotal(p) : stockInBranch(st, p, scopeBranch);
            return (
              <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <ProductImg p={p} size={36} />
                <div style={{ minWidth: 0, lineHeight: 1.3, flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
                  <div style={{ fontSize: 11, color: T.sub }}>จุดสั่งซื้อ {p.reorder} ชิ้น</div>
                </div>
                <Badge tone="danger">เหลือ {q}</Badge>
              </div>
            );
          })}
        </Card>

        {/* ③b สต็อกอะไหล่ใกล้หมด — แยกออกมาอีกการ์ด */}
        <Card style={{ padding: "16px 20px", display: "flex", flexDirection: "column", gap: 11, animation: "ss-rise .5s 220ms cubic-bezier(.2,.9,.3,1.1) backwards" }}>
          <SectionTitle right={<a className="ss-link" onClick={() => go("parts")}>ดูทั้งหมด →</a>}>สต็อกอะไหล่ใกล้หมด</SectionTitle>
          {lowParts.length === 0 && <EmptyState icon="✓" text="อะไหล่เพียงพอทุกรายการ" />}
          {lowParts.slice(0, 5).map((p) => {
            const q = scopeBranch === "ALL" ? stockTotal(p) : stockInBranch(st, p, scopeBranch);
            return (
              <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <ProductImg p={p} size={36} />
                <div style={{ minWidth: 0, lineHeight: 1.3, flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
                  <div style={{ fontSize: 11, color: T.sub }}>จุดสั่งซื้อ {p.reorder} ชิ้น</div>
                </div>
                <Badge tone="danger">เหลือ {q}</Badge>
              </div>
            );
          })}
        </Card>

        {/* ④ รายรับรายเดือน (เงินสด + โอน/บัตร) ย้อนหลัง 4 เดือน */}
        <Card style={{ padding: "16px 20px", animation: "ss-rise .5s 260ms cubic-bezier(.2,.9,.3,1.1) backwards" }}>
          <SectionTitle right={<ChartLegend items={[{ label: "เงินสด + โอน/บัตร", color: T.c4 }]} />}>
            รายรับรายเดือน <span style={{ color: T.sub, fontWeight: 500, fontSize: 12.5 }}>6 เดือนล่าสุด · รวม {fmtMoney(monthIncomeTotal)}</span>
          </SectionTitle>
          <BarChart groups={monthLabels} height={205} series={[{ label: "รายรับ", color: T.c4, data: monthIncome }]} />
        </Card>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.7fr 1fr", gap: 14 }}>
        <Card style={{ padding: "15px 20px 10px", animation: "ss-rise .5s 240ms cubic-bezier(.2,.9,.3,1.1) backwards" }}>
          <SectionTitle right={<a className="ss-link" onClick={() => go("repairs")}>ไปหน้างานซ่อม →</a>}>คิวงานซ่อมล่าสุด</SectionTitle>
          <div style={{ display: "grid", gridTemplateColumns: "84px 1.3fr 1.1fr 0.9fr auto", gap: 8, fontSize: 11.5, color: T.sub, fontWeight: 700, padding: "2px 6px 7px", borderBottom: `1px solid ${T.border}` }}>
            <div>เลขที่</div><div>เครื่อง</div><div>งาน</div><div>ช่าง</div><div>สถานะ</div>
          </div>
          {recentRepairs.map((r, i) => (
            <div key={r.id} className="ss-row" onClick={() => go("repairs", r.id)} style={{ display: "grid", gridTemplateColumns: "84px 1.3fr 1.1fr 0.9fr auto", gap: 8, alignItems: "center", fontSize: 13, padding: "9px 6px", borderBottom: i < recentRepairs.length - 1 ? `1px solid ${T.rowBorder}` : "none", cursor: "pointer" }}>
              <div style={{ fontWeight: 700, color: T.primary, fontSize: 12.5 }}>{r.id}</div>
              <div style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.device}</div>
              <div style={{ color: T.sub, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.issue}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5 }}><Avatar name={userOf(st, r.tech).name} img={userOf(st, r.tech).img} size={22} />{userOf(st, r.tech).name.split(" ")[0]}</div>
              <Badge tone={REPAIR_TONES[r.status]}>{r.status}</Badge>
            </div>
          ))}
        </Card>

        <Card style={{ padding: "15px 20px", animation: "ss-rise .5s 300ms cubic-bezier(.2,.9,.3,1.1) backwards" }}>
          <SectionTitle right={<a className="ss-link" onClick={() => go("reports")}>รายงาน →</a>}>ความเคลื่อนไหวล่าสุด</SectionTitle>
          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            {recentMoves.map((m) => {
              const p = prodOf(st, m.productId) || { name: "—" };
              const tone = m.type === "ขายออก" ? T.accent : m.type === "รับเข้า" ? "#11A05F" : m.type === "โอนย้าย" ? T.primary : T.sub;
              return (
                <div key={m.id} style={{ display: "flex", gap: 9, alignItems: "flex-start", fontSize: 12 }}>
                  <span style={{ width: 8, height: 8, borderRadius: "50%", background: tone, marginTop: 5, flex: "none" }}></span>
                  <div style={{ lineHeight: 1.4, minWidth: 0 }}>
                    <span style={{ fontWeight: 700, color: tone }}>{m.type}</span> {p.name}
                    <span style={{ fontWeight: 700 }}> {m.qty > 0 ? "+" : ""}{m.qty}</span>
                    <div style={{ color: T.sub, fontSize: 11 }}>{m.loc.includes("→") ? m.loc : locName(st, m.loc)} · {fmtTime(m.ts)} · {m.ref}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </div>
  );
}
window.DashboardPage = DashboardPage;
