// ==========================================
// Stock page — per-project Store-friendly view
// ==========================================

function StockPage({ state, setState, user }) {
  const toast = useToast();
  const stock = useMemo(() => computeStock(state), [state]);
  const [catFilter, setCatFilter] = useState("all");
  const [projFilter, setProjFilter] = useState("all");
  const [search, setSearch] = useState("");
  const [showLow, setShowLow] = useState(false);
  const [adjust, setAdjust] = useState(null);     // {m, kind}
  const [showAddProj, setShowAddProj] = useState(false);
  const isPM = user && user.role === "pm";

  const catMap = Object.fromEntries(state.categories.map((c) => [c.id, c]));

  function addProject(form) {
    const id = genId("P");
    setState({ ...state, projects: [...state.projects, { ...form, id }] });
    setProjFilter(id);
    setShowAddProj(false);
    toast("เพิ่มโครงการเรียบร้อย");
  }

  function commitAdjust(form) {
    const qty = window.DB.safeQty(form.qty);
    if (qty === null) {
      toast("จำนวนต้องมากกว่า 0", "warn");
      return;
    }
    // Block stock adjustment that would push balance negative.
    if (form.kind === "out") {
      const avail = (stock[adjust.m.id] || {})[form.projectId] || 0;
      if (qty > avail) {
        toast(`สต๊อกไม่พอ · คงเหลือ ${avail}`, "warn");
        return;
      }
    }
    const txn = window.DB.stampTransaction({
      id: genId(form.kind === "in" ? "RC" : "IS"),
      type: form.kind === "in" ? "receive" : "issue",
      date: todayISO(),
      materialId: adjust.m.id,
      qty,
      projectId: form.projectId,
      note: form.note || (form.kind === "in" ? "ปรับเพิ่มสต๊อก (โดย Store)" : "ปรับลดสต๊อก (โดย Store)"),
      [form.kind === "in" ? "supplier" : "requester"]: form.party || "—",
      by: "store",
    });
    setState({ ...state, transactions: [...state.transactions, txn] });
    toast(form.kind === "in" ? "รับเข้าเรียบร้อย" : "เบิกออกเรียบร้อย");
    setAdjust(null);
  }

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>คลังวัสดุ {projFilter !== "all" && <span style={{ color: "var(--accent)" }}>· {state.projects.find((p) => p.id === projFilter)?.code}</span>}</h1>
          <p className="muted">
            {projFilter === "all"
              ? "ภาพรวมคลังทุกหน่วยงาน · เลือกหน่วยงานเพื่อจัดการสต๊อกเฉพาะโครงการ"
              : <>สต๊อกของ <b>{state.projects.find((p) => p.id === projFilter)?.name}</b> · Store สามารถปรับสต๊อกได้ทันที</>
            }
          </p>
        </div>
      </div>

      <ProjectSelector
        projects={state.projects}
        stock={stock}
        materials={state.materials}
        value={projFilter}
        onChange={setProjFilter}
        onAdd={isPM ? (() => setShowAddProj(true)) : null}
      />

      <div className="filter-bar">
        <div className="chip-group">
          <button className={`chip ${catFilter === "all" ? "active" : ""}`} onClick={() => setCatFilter("all")}>ทั้งหมด</button>
          {state.categories.map((c) => (
            <button key={c.id} className={`chip ${catFilter === c.id ? "active" : ""}`} onClick={() => setCatFilter(c.id)} style={catFilter === c.id ? { background: c.color, borderColor: c.color, color: "#fff" } : { borderColor: c.color + "55", color: c.color }}>
              <span>{c.icon}</span> {c.name}
            </button>
          ))}
        </div>
        <div className="filter-right">
          <input placeholder="ค้นหาวัสดุ / รหัส..." value={search} onChange={(e) => setSearch(e.target.value)} />
          <label className="toggle">
            <input type="checkbox" checked={showLow} onChange={(e) => setShowLow(e.target.checked)} />
            <span>เฉพาะที่ต่ำกว่ากำหนด</span>
          </label>
        </div>
      </div>

      {projFilter === "all" ? (
        <AllProjectsMatrix
          state={state}
          stock={stock}
          catFilter={catFilter}
          search={search}
          showLow={showLow}
          catMap={catMap}
        />
      ) : (
        <SingleProjectView
          state={state}
          stock={stock}
          projectId={projFilter}
          catFilter={catFilter}
          search={search}
          showLow={showLow}
          catMap={catMap}
          onAdjust={(m, kind) => setAdjust({ m, kind })}
        />
      )}

      <Modal open={!!adjust} onClose={() => setAdjust(null)} title={`ปรับสต๊อก: ${adjust?.m.name || ""}`} width={520}>
        {adjust && (
          <StockAdjustForm
            material={adjust.m}
            initialKind={adjust.kind}
            defaultProjectId={projFilter !== "all" ? projFilter : state.projects[0]?.id}
            stock={stock}
            projects={state.projects}
            onCancel={() => setAdjust(null)}
            onSubmit={commitAdjust}
          />
        )}
      </Modal>

      <Modal open={showAddProj} onClose={() => setShowAddProj(false)} title="เพิ่มโครงการใหม่" width={520}>
        <ProjectForm initial={null} onCancel={() => setShowAddProj(false)} onSubmit={addProject} />
      </Modal>
    </div>
  );
}

// ============ All Projects: matrix table ============
function AllProjectsMatrix({ state, stock, catFilter, search, showLow, catMap }) {
  const rows = state.materials
    .filter((m) => catFilter === "all" || m.category === catFilter)
    .filter((m) => !search || m.name.toLowerCase().includes(search.toLowerCase()) || m.id.toLowerCase().includes(search.toLowerCase()))
    .map((m) => {
      const perProj = state.projects.map((p) => ({ p, qty: stock[m.id]?.[p.id] || 0 }));
      const total = perProj.reduce((a, b) => a + b.qty, 0);
      return { m, perProj, total };
    })
    .filter((r) => !showLow || r.total < r.m.min);

  return (
    <div className="card no-pad">
      <div className="table-wrap">
        <table className="data-table">
          <thead>
            <tr>
              <th style={{ width: 80 }}>รหัส</th>
              <th>วัสดุ</th>
              <th>หมวด</th>
              <th style={{ width: 70 }}>หน่วย</th>
              {state.projects.map((p) => <th key={p.id} className="num-col" title={p.name}>{p.code}</th>)}
              <th className="num-col">รวม</th>
              <th className="num-col">ขั้นต่ำ</th>
              <th>สถานะ</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && (
              <tr><td colSpan={6 + state.projects.length}><Empty /></td></tr>
            )}
            {rows.map(({ m, perProj, total }) => {
              const cat = catMap[m.category];
              const isLow = total < m.min;
              const isZero = total <= 0;
              return (
                <tr key={m.id}>
                  <td className="mono">{m.id}</td>
                  <td><b>{m.name}</b></td>
                  <td><CatBadge cat={cat} /></td>
                  <td>{m.unit}</td>
                  {perProj.map(({ p, qty }) => (
                    <td key={p.id} className="num-col" style={{ color: qty <= 0 ? "#bbb" : "var(--text)" }}>{fmtNum(qty)}</td>
                  ))}
                  <td className="num-col"><b style={{ color: isLow ? "#ef4444" : "var(--text)" }}>{fmtNum(total)}</b></td>
                  <td className="num-col muted">{fmtNum(m.min)}</td>
                  <td>
                    {isZero ? <span className="status-pill" style={{ background: "#fee2e2", color: "#991b1b" }}>หมด</span>
                      : isLow ? <span className="status-pill" style={{ background: "#fef3c7", color: "#92400e" }}>ต่ำ</span>
                      : <span className="status-pill" style={{ background: "#d1fae5", color: "#065f46" }}>ปกติ</span>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ============ Single Project: grouped-by-category view ============
function SingleProjectView({ state, stock, projectId, catFilter, search, showLow, catMap, onAdjust }) {
  const project = state.projects.find((p) => p.id === projectId);

  // Build per-category sections
  const sections = state.categories
    .filter((c) => catFilter === "all" || c.id === catFilter)
    .map((c) => {
      const items = state.materials
        .filter((m) => m.category === c.id)
        .filter((m) => !search || m.name.toLowerCase().includes(search.toLowerCase()) || m.id.toLowerCase().includes(search.toLowerCase()))
        .map((m) => ({ m, qty: stock[m.id]?.[projectId] || 0 }))
        .filter((x) => !showLow || x.qty < x.m.min);
      return { c, items };
    })
    .filter((s) => s.items.length > 0);

  // Summary stats for this project
  const allItems = state.materials.map((m) => ({ m, qty: stock[m.id]?.[projectId] || 0 }));
  const totalQty = allItems.reduce((a, x) => a + x.qty, 0);
  const inStock = allItems.filter((x) => x.qty > 0).length;
  const lowCount = allItems.filter((x) => x.qty < x.m.min).length;
  const zeroCount = allItems.filter((x) => x.qty <= 0).length;

  return (
    <>
      {/* Project summary header */}
      <div className="stock-summary">
        <div className="stock-summary-item">
          <div className="stock-summary-label">หน่วยงาน</div>
          <div className="stock-summary-name">{project.name}</div>
          <div className="stock-summary-meta">{project.code} · {project.manager || "—"}</div>
        </div>
        <div className="stock-summary-stat">
          <div className="ss-label">รายการมีสต๊อก</div>
          <div className="ss-num" style={{ color: "#10b981" }}>{fmtNum(inStock)}</div>
          <div className="ss-sub">จาก {state.materials.length} รายการ</div>
        </div>
        <div className="stock-summary-stat">
          <div className="ss-label">ปริมาณรวม</div>
          <div className="ss-num">{fmtNum(totalQty)}</div>
          <div className="ss-sub">หน่วยในคลัง</div>
        </div>
        <div className="stock-summary-stat">
          <div className="ss-label">ต่ำกว่ากำหนด</div>
          <div className="ss-num" style={{ color: lowCount > 0 ? "#ef4444" : "#10b981" }}>{fmtNum(lowCount)}</div>
          <div className="ss-sub">{zeroCount > 0 ? `หมด ${zeroCount} รายการ` : "ทุกรายการมีของ"}</div>
        </div>
      </div>

      {sections.length === 0 && (
        <div className="card"><Empty text="ยังไม่มีวัสดุในหน่วยงานนี้" /></div>
      )}

      {sections.map(({ c, items }) => {
        const catTotal = items.reduce((a, x) => a + x.qty, 0);
        const catLow = items.filter((x) => x.qty < x.m.min).length;
        return (
          <div key={c.id} className="card no-pad stock-section">
            <div className="stock-section-head" style={{ background: c.color + "10", borderLeft: `4px solid ${c.color}` }}>
              <div className="stock-section-title">
                <div className="stock-section-icon" style={{ background: c.color + "22", color: c.color }}>{c.icon}</div>
                <div>
                  <div className="stock-section-name">{c.name}</div>
                  <div className="muted small">{items.length} รายการ · ปริมาณรวม {fmtNum(catTotal)}</div>
                </div>
              </div>
              {catLow > 0 && (
                <div className="warn-pill">⚠ ต่ำกว่ากำหนด {catLow} รายการ</div>
              )}
            </div>
            <table className="data-table">
              <thead>
                <tr>
                  <th style={{ width: 80 }}>รหัส</th>
                  <th>วัสดุ</th>
                  <th style={{ width: 80 }}>หน่วย</th>
                  <th className="num-col" style={{ width: 110 }}>คงเหลือ</th>
                  <th className="num-col" style={{ width: 90 }}>ขั้นต่ำ</th>
                  <th style={{ width: 100 }}>สถานะ</th>
                  <th style={{ width: 180 }}>การจัดการ</th>
                </tr>
              </thead>
              <tbody>
                {items.map(({ m, qty }) => {
                  const isLow = qty < m.min;
                  const isZero = qty <= 0;
                  return (
                    <tr key={m.id}>
                      <td className="mono">{m.id}</td>
                      <td><b>{m.name}</b></td>
                      <td>{m.unit}</td>
                      <td className="num-col">
                        <b style={{ color: isZero ? "#9ca3af" : isLow ? "#ef4444" : "var(--text)", fontSize: 15 }}>
                          {fmtNum(qty)}
                        </b>
                      </td>
                      <td className="num-col muted">{fmtNum(m.min)}</td>
                      <td>
                        {isZero ? <span className="status-pill" style={{ background: "#fee2e2", color: "#991b1b" }}>หมด</span>
                          : isLow ? <span className="status-pill" style={{ background: "#fef3c7", color: "#92400e" }}>ต่ำ</span>
                          : <span className="status-pill" style={{ background: "#d1fae5", color: "#065f46" }}>ปกติ</span>}
                      </td>
                      <td>
                        <div className="stock-actions">
                          <button className="qa-btn qa-in" onClick={() => onAdjust(m, "in")} title="รับเข้า">📥 รับเข้า</button>
                          <button className="qa-btn qa-out" onClick={() => onAdjust(m, "out")} title="เบิกออก" disabled={isZero}>📤 เบิกออก</button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        );
      })}
    </>
  );
}

// ============ Quick adjust form (lives in stock page) ============
function StockAdjustForm({ material, initialKind, defaultProjectId, stock, projects, onSubmit, onCancel }) {
  const [f, setF] = useState({
    kind: initialKind || "in",
    qty: "",
    projectId: defaultProjectId || projects[0]?.id || "",
    party: "",
    note: "",
  });
  const currentQty = stock[material.id]?.[f.projectId] || 0;

  return (
    <form onSubmit={(e) => { e.preventDefault(); onSubmit(f); }} className="form-grid">
      <div className="adjust-toggle">
        <button type="button" className={`adjust-tog ${f.kind === "in" ? "active in" : ""}`} onClick={() => setF({ ...f, kind: "in" })}>
          📥 รับเข้า (+)
        </button>
        <button type="button" className={`adjust-tog ${f.kind === "out" ? "active out" : ""}`} onClick={() => setF({ ...f, kind: "out" })}>
          📤 เบิกออก (−)
        </button>
      </div>

      <Field label="หน่วยงาน">
        <select value={f.projectId} onChange={(e) => setF({ ...f, projectId: e.target.value })} required>
          {projects.map((p) => <option key={p.id} value={p.id}>{p.code} · {p.name}</option>)}
        </select>
      </Field>

      <div style={{ background: "var(--surface-2)", padding: 12, borderRadius: 10, fontSize: 13, display: "flex", justifyContent: "space-between" }}>
        <span className="muted">สต๊อกปัจจุบันในหน่วยงานนี้:</span>
        <b style={{ color: currentQty < material.min ? "#ef4444" : "var(--text)" }}>{fmtNum(currentQty)} {material.unit}</b>
      </div>

      <Field label={`จำนวนที่จะ${f.kind === "in" ? "รับเข้า" : "เบิกออก"} (${material.unit})`}>
        <input type="number" min="0" step="any" value={f.qty} onChange={(e) => setF({ ...f, qty: e.target.value })} required autoFocus />
      </Field>

      <Field label={f.kind === "in" ? "ผู้จำหน่าย / ที่มา" : "ผู้ขอเบิก / งาน"}>
        <input value={f.party} onChange={(e) => setF({ ...f, party: e.target.value })} placeholder={f.kind === "in" ? "เช่น บริษัท ABC" : "เช่น ทีมงาน 1"} />
      </Field>

      <Field label="หมายเหตุ">
        <input value={f.note} onChange={(e) => setF({ ...f, note: e.target.value })} />
      </Field>

      <div className="form-actions">
        <button type="button" className="btn-ghost" onClick={onCancel}>ยกเลิก</button>
        <button type="submit" className="btn-primary" style={{ background: f.kind === "in" ? "#10b981" : "#ef4444", borderColor: f.kind === "in" ? "#10b981" : "#ef4444" }}>
          ✓ บันทึก{f.kind === "in" ? "รับเข้า" : "เบิกออก"}
        </button>
      </div>
    </form>
  );
}

window.StockPage = StockPage;
