// หน้ารายรับรายวัน (13) + เคลียร์ยอดรายวัน (12)
const DAY1 = 86400000;
function dayStart(ts) { const d = new Date(ts); d.setHours(0, 0, 0, 0); return d.getTime(); }

/* ── เคลียร์ยอดรายวัน — ปุ่มในแถบข้าง (ทุกคนยกเว้นเจ้าของร้าน) ── */
function DailyClearLauncher({ user }) {
  const { st } = useStore();
  const [open, setOpen] = React.useState(false);
  if (user.role === "owner") return null;
  return (
    <React.Fragment>
      <div className="ss-nav" onClick={() => setOpen(true)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", marginTop: 6, borderRadius: 11, cursor: "pointer", background: T.warnBg, color: T.warnFg, fontSize: 13, fontWeight: 700, border: `1px solid ${T.warnFg}44` }}>
        <span style={{ fontSize: 15, width: 19, textAlign: "center" }}>▤</span>เคลียร์ยอดรายวัน
      </div>
      <DailyClearModal open={open} onClose={() => setOpen(false)} user={user} />
    </React.Fragment>
  );
}

function DailyClearModal({ open, onClose, user }) {
  const { st, dispatch } = useStore();
  const toast = useToast();
  const role = st.roles[user.role] || {};
  const [branch, setBranch] = React.useState(role.allBranch ? "B1" : user.branch);
  const [total, setTotal] = React.useState("");
  const [cash, setCash] = React.useState("");
  const [transfer, setTransfer] = React.useState("");
  const [note, setNote] = React.useState("");
  const [photos, setPhotos] = React.useState([]);

  const addPhotos = (files) => {
    [...files].forEach((file) => {
      const r = new FileReader();
      r.onload = (e) => setPhotos((x) => [...x, e.target.result]);
      r.readAsDataURL(file);
    });
  };

  const submit = () => {
    if (!total && !cash && !transfer) { toast("กรอกยอดอย่างน้อยหนึ่งช่อง", "danger"); return; }
    dispatch({ type: "DAILYCLEAR_ADD", clear: {
      branch, date: dayStart(Date.now()),
      total: Number(total) || (Number(cash) || 0) + (Number(transfer) || 0),
      cash: Number(cash) || 0, transfer: Number(transfer) || 0,
      photos, note, by: user.id,
    } });
    toast("ส่งยอดเคลียร์รายวันแล้ว");
    setTotal(""); setCash(""); setTransfer(""); setNote(""); setPhotos([]);
    onClose();
  };

  return (
    <Modal open={open} onClose={onClose} title="เคลียร์ยอดรายวัน" width={500}
      footer={<React.Fragment>
        <Btn kind="ghost" onClick={onClose}>ยกเลิก</Btn>
        <Btn kind="warn" onClick={submit}>ส่งยอดวันนี้</Btn>
      </React.Fragment>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          <Field label="สาขา" style={{ flex: 1 }}>
            <Select value={branch} onChange={setBranch} disabled={!role.allBranch}
              options={st.branches.map((b) => ({ value: b.id, label: b.name }))} />
          </Field>
          <Field label="วันที่"><TextInput value={new Date().toLocaleDateString("th-TH", { day: "2-digit", month: "long", year: "numeric" })} disabled style={{ background: T.chipBg }} /></Field>
        </div>
        <Field label="ยอดรวม (บาท)"><NumInput value={total} onChange={(e) => setTotal(e.target.value)} placeholder="เว้นว่าง = เงินสด + โอน" style={{ fontSize: 18, fontWeight: 800 }} /></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="เงินสด"><NumInput value={cash} onChange={(e) => setCash(e.target.value)} /></Field>
          <Field label="โอน / รูดบัตร"><NumInput value={transfer} onChange={(e) => setTransfer(e.target.value)} /></Field>
        </div>
        <Field label="แนบรูป (สลิป / หลักฐาน — เลือกได้หลายรูป)">
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {photos.map((src, i) => (
              <div key={i} style={{ position: "relative", width: 64, height: 64, borderRadius: 9, overflow: "hidden", border: `1px solid ${T.border}` }}>
                <img src={src} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                <span onClick={() => setPhotos((x) => x.filter((_, j) => j !== i))} style={{ position: "absolute", top: 2, right: 2, width: 18, height: 18, borderRadius: "50%", background: "rgba(0,0,0,.6)", color: "#fff", fontSize: 11, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>✕</span>
              </div>
            ))}
            <label style={{ width: 64, height: 64, borderRadius: 9, border: `1.5px dashed ${T.border}`, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", cursor: "pointer", color: T.sub, fontSize: 11, gap: 3 }}>
              <span style={{ fontSize: 20 }}>＋</span>เพิ่มรูป
              <input type="file" accept="image/*" multiple style={{ display: "none" }} onChange={(e) => addPhotos(e.target.files)} />
            </label>
          </div>
        </Field>
        <Field label="หมายเหตุ"><TextArea value={note} onChange={(e) => setNote(e.target.value)} placeholder="หมายเหตุของวันนี้…" /></Field>
      </div>
    </Modal>
  );
}

/* ── หน้ารายรับรายวัน (13) ── */
function IncomePage({ ui, user }) {
  const { st } = useStore();
  const role = st.roles[user.role] || {};
  const seeAll = role.allBranch;
  const [viewBranch, setViewBranch] = React.useState(seeAll ? (ui.branch !== "ALL" ? ui.branch : "ALL") : user.branch);
  const [openId, setOpenId] = React.useState(null);
  const [lb, setLb] = React.useState({ imgs: [], i: null });

  const scope = st.dailyClears.filter((c) => (seeAll || c.branch === user.branch) && (viewBranch === "ALL" || c.branch === viewBranch));
  // จัดกลุ่มตามวัน
  const byDay = {};
  scope.forEach((c) => { const d = dayStart(c.date); (byDay[d] = byDay[d] || []).push(c); });
  const days = Object.keys(byDay).map(Number).sort((a, b) => b - a);

  const today0 = dayStart(Date.now());
  const sum = (list, k) => list.reduce((a, c) => a + (c[k] || 0), 0);

  // กราฟ 7 วันล่าสุด (รวมยอด) — เมื่อเปิดวันนี้จะเห็นกราฟของเมื่อวานเป็นแท่งล่าสุดที่มีข้อมูล
  const last7 = Array.from({ length: 7 }, (_, i) => today0 - (6 - i) * DAY1);
  const labels = last7.map((d) => new Date(d).toLocaleDateString("th-TH", { day: "2-digit", month: "2-digit" }));
  const cashSeries = last7.map((d) => sum(byDay[d] || [], "cash"));
  const transferSeries = last7.map((d) => sum(byDay[d] || [], "transfer"));

  const yesterday = today0 - DAY1;
  const yList = byDay[yesterday] || [];

  // ── รายรับล่าสุดของทุกสาขา (วันล่าสุดที่แต่ละสาขาส่งยอด) ──
  const branchLatest = st.branches.map((b) => {
    const cs = st.dailyClears.filter((c) => c.branch === b.id);
    const latestDay = cs.length ? Math.max(...cs.map((c) => dayStart(c.date))) : null;
    const dayList = latestDay != null ? cs.filter((c) => dayStart(c.date) === latestDay) : [];
    return {
      short: b.short, name: b.name, day: latestDay,
      cash: sum(dayList, "cash"), transfer: sum(dayList, "transfer"),
      total: sum(dayList, "total") || sum(dayList, "cash") + sum(dayList, "transfer"),
    };
  });

  const open = openId != null ? scope.find((c) => c.id === openId) : null;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <div style={{ fontSize: 13, color: T.sub }}>รายรับจากการเคลียร์ยอดรายวันของพนักงาน · ดูย้อนหลังได้</div>
        {seeAll && (
          <Select value={viewBranch} onChange={setViewBranch} style={{ width: 180, marginLeft: "auto", fontWeight: 700, color: T.primary }}
            options={[{ value: "ALL", label: "ทุกสาขา (รวม)" }, ...st.branches.map((b) => ({ value: b.id, label: b.name }))]} />
        )}
      </div>

      {/* การ์ดสรุปเมื่อวาน */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
        <StatCard hero label="รายรับเมื่อวาน (รวม)" value={sum(yList, "total") || sum(yList, "cash") + sum(yList, "transfer")} money sub={new Date(yesterday).toLocaleDateString("th-TH", { weekday: "long", day: "numeric", month: "long" })} delay={0} />
        <StatCard label="เงินสด เมื่อวาน" value={sum(yList, "cash")} money sub={`${yList.length} รายการเคลียร์`} delay={60} />
        <StatCard label="โอน / รูดบัตร เมื่อวาน" value={sum(yList, "transfer")} money sub="รวมทุกพนักงาน" delay={120} />
      </div>

      <Card style={{ padding: "16px 20px" }}>
        <SectionTitle right={<ChartLegend items={[{ label: "เงินสด", color: T.c1 }, { label: "โอน/บัตร", color: T.c2 }]} />}>
          รายรับ 7 วันล่าสุด {viewBranch !== "ALL" ? `· ${branchOf(st, viewBranch).name}` : "· ทุกสาขา"}
        </SectionTitle>
        <BarChart groups={labels} height={190} series={[
          { label: "เงินสด", color: T.c1, data: cashSeries },
          { label: "โอน/บัตร", color: T.c2, data: transferSeries },
        ]} />
      </Card>

      {/* ── รายรับล่าสุดของทุกสาขาพร้อมกัน (เฉพาะผู้ดูได้หลายสาขา) ── */}
      {seeAll && st.branches.length > 1 && (
        <Card style={{ padding: "16px 20px" }}>
          <SectionTitle right={<ChartLegend items={[{ label: "เงินสด", color: T.c1 }, { label: "โอน/บัตร", color: T.c2 }]} />}>
            รายรับล่าสุดของทุกสาขา (เปรียบเทียบ) <span style={{ color: T.sub, fontWeight: 500, fontSize: 12.5 }}>จากการเคลียร์ยอดล่าสุดของแต่ละสาขา</span>
          </SectionTitle>
          <BarChart groups={branchLatest.map((b) => b.short)} height={200} series={[
            { label: "เงินสด", color: T.c1, data: branchLatest.map((b) => b.cash) },
            { label: "โอน/บัตร", color: T.c2, data: branchLatest.map((b) => b.transfer) },
          ]} />
          <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 12 }}>
            {branchLatest.map((b) => (
              <div key={b.short} style={{ flex: "1 1 130px", background: T.chipBg, borderRadius: 11, padding: "10px 14px" }}>
                <div style={{ fontSize: 12, color: T.sub, display: "flex", alignItems: "center", gap: 6 }}><Badge tone="muted">{b.short}</Badge>{b.day != null ? new Date(b.day).toLocaleDateString("th-TH", { day: "2-digit", month: "short" }) : "—"}</div>
                <div style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 19, color: T.primary, marginTop: 4 }}>{fmtMoney(b.total)}</div>
              </div>
            ))}
          </div>
        </Card>
      )}

      <Card style={{ padding: "6px 18px 10px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.1fr 0.9fr 0.9fr 0.9fr 1fr", gap: 10, fontSize: 11.5, color: T.sub, fontWeight: 700, padding: "12px 4px 8px", borderBottom: `1px solid ${T.border}` }}>
          <div>วันที่</div><div>รวม</div><div>เงินสด</div><div>โอน/บัตร</div><div>สาขา · ผู้ส่ง</div>
        </div>
        {days.map((d) => byDay[d].map((c, i) => (
          <div key={c.id} className="ss-row" onClick={() => setOpenId(c.id)} style={{ display: "grid", gridTemplateColumns: "1.1fr 0.9fr 0.9fr 0.9fr 1fr", gap: 10, alignItems: "center", fontSize: 13, padding: "9px 4px", borderBottom: `1px solid ${T.rowBorder}`, cursor: "pointer" }}>
            <div style={{ fontWeight: 600 }}>{new Date(c.date).toLocaleDateString("th-TH", { day: "2-digit", month: "short", year: "2-digit" })}{dayStart(c.date) === today0 && <Badge tone="ok" sm>วันนี้</Badge>}</div>
            <div style={{ fontFamily: T.headFont, fontWeight: 800, color: T.primary }}>{fmtMoney(c.total || c.cash + c.transfer)}</div>
            <div>{fmtMoney(c.cash)}</div>
            <div>{fmtMoney(c.transfer)}</div>
            <div style={{ fontSize: 12, color: T.sub, display: "flex", alignItems: "center", gap: 6 }}>
              <Badge tone="muted">{branchOf(st, c.branch).short}</Badge>{userOf(st, c.by).name.split(" ")[0]}
              {c.photos && c.photos.length > 0 && <span style={{ color: T.primary, fontSize: 11 }}>📎{c.photos.length}</span>}
            </div>
          </div>
        )))}
        {days.length === 0 && <EmptyState text="ยังไม่มีการเคลียร์ยอด" />}
      </Card>

      {/* รายละเอียดการเคลียร์ */}
      <Modal open={!!open} onClose={() => setOpenId(null)} title={open ? `เคลียร์ยอด ${open.id}` : ""} width={480}
        footer={<Btn kind="ghost" onClick={() => setOpenId(null)}>ปิด</Btn>}>
        {open && (
          <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "9px 18px", fontSize: 13, background: T.chipBg, borderRadius: 12, padding: "13px 16px" }}>
              <div><span style={{ color: T.sub }}>วันที่:</span> <b>{new Date(open.date).toLocaleDateString("th-TH", { dateStyle: "long" })}</b></div>
              <div><span style={{ color: T.sub }}>สาขา:</span> {branchOf(st, open.branch).name}</div>
              <div><span style={{ color: T.sub }}>ผู้ส่ง:</span> {userOf(st, open.by).name}</div>
              <div><span style={{ color: T.sub }}>ยอดรวม:</span> <b style={{ color: T.primary }}>{fmtMoney(open.total || open.cash + open.transfer)}</b></div>
              <div><span style={{ color: T.sub }}>เงินสด:</span> {fmtMoney(open.cash)}</div>
              <div><span style={{ color: T.sub }}>โอน/บัตร:</span> {fmtMoney(open.transfer)}</div>
            </div>
            {open.note && <div style={{ fontSize: 13 }}><span style={{ color: T.sub }}>หมายเหตุ:</span> {open.note}</div>}
            {open.photos && open.photos.length > 0 && (
              <div>
                <div style={{ fontSize: 12, color: T.sub, marginBottom: 7 }}>รูปแนบ {open.photos.length} รูป</div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {open.photos.map((src, i) => <img key={i} src={src} alt="" onClick={() => setLb({ imgs: open.photos, i })} style={{ width: 90, height: 90, objectFit: "cover", borderRadius: 9, border: `1px solid ${T.border}`, cursor: "zoom-in" }} />)}
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>
      <Lightbox images={lb.imgs} index={lb.i} onClose={() => setLb({ imgs: [], i: null })} onIndex={(i) => setLb((x) => ({ ...x, i }))} />
    </div>
  );
}

Object.assign(window, { IncomePage, DailyClearLauncher, DailyClearModal });
