/* X-REAL Stock System — Forecast (with smart suggestions) + Consignment */

// ─── FORECAST PAGE ────────────────────────────────────────────────────
// Lead time assumption — used to compute order-now thresholds.
const LEAD_TIME_MONTHS_MIN = 1;
const LEAD_TIME_MONTHS_MAX = 1.5;
const SAFETY_BUFFER_MONTHS = 0.5; // extra month of stock to have when new order arrives
const CRITICAL_THRESHOLD = LEAD_TIME_MONTHS_MAX + SAFETY_BUFFER_MONTHS; // 2.0 mo
const WARN_THRESHOLD = LEAD_TIME_MONTHS_MAX + SAFETY_BUFFER_MONTHS + 1; // 3.0 mo

function ForecastPage({ products, cats, catMap, stocks, locations, history, getTot, getQty, consLedger, stores, reservations }) {
  const [catFilter, setCatFilter] = useState("all");
  const [selSku, setSelSku] = useState(null);
  const [monthsBack, setMonthsBack] = useState(3);

  const baan = locations.find(l => l.name === "บ้าน") || locations.find(l => l.isStorage);
  const fulfillmentLoc = locations.find(l => l.name === "Mycloud Fulfillment") || locations.find(l => l.locType === "storage" && l.id !== baan?.id);

  const getPendingReserved = useCallback((skuId) =>
    reservations.filter(r => r.status === "pending").flatMap(r => r.items)
      .filter(i => i.skuId === skuId).reduce((a, i) => a + i.qty, 0)
  , [reservations]);

  // Parse history to compute outflow from บ้าน + Mycloud per SKU per month.
  // Counted actions:
  //   - "นำออก" where detail starts with "จากบ้าน" or "จากMycloud …"
  //   - "ฝาก Consignment"        (always deducts บ้าน when shipping to a branch)
  //   - "Reservation Fulfilled"  (always deducts บ้าน)
  // Detail strings include SKU×qty patterns (e.g. "Ori-s×100, Cocoa-s×60").
  const outflowBySku = useMemo(() => {
    const result = {};
    const skuMap = Object.fromEntries(products.map(p => [p.sku.toLowerCase(), p.id]));
    const baanName = baan?.name || "บ้าน";
    const fulName = fulfillmentLoc?.name || "Mycloud Fulfillment";
    const fromBaan = "จาก" + baanName;
    const fromFul = "จาก" + fulName;

    for (const h of history || []) {
      if (!h.ts || !h.detail) continue;
      let counts = false;
      if (h.action === "นำออก") {
        counts = h.detail.startsWith(fromBaan) || h.detail.startsWith(fromFul);
      } else if (h.action === "ฝาก Consignment" || h.action === "Reservation Fulfilled") {
        counts = true;
      }
      if (!counts) continue;

      const d = new Date(h.ts);
      if (isNaN(d.getTime())) continue;
      const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;

      // Match patterns like "Ori-s×100" — SKU codes can contain letters, digits, hyphens.
      const re = /([A-Za-z0-9_-]+)×(\d+)/g;
      let m;
      while ((m = re.exec(h.detail)) !== null) {
        const skuId = skuMap[m[1].toLowerCase()];
        if (!skuId) continue;
        if (!result[skuId]) result[skuId] = {};
        result[skuId][key] = (result[skuId][key] || 0) + (parseInt(m[2]) || 0);
      }
    }
    return result;
  }, [history, products, baan, fulfillmentLoc]);

  const getSkuVelocity = (skuId) => {
    const monthly = outflowBySku[skuId] || {};
    const months = [];
    for (let i = monthsBack - 1; i >= 0; i--) {
      const d = new Date(); d.setMonth(d.getMonth() - i);
      months.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`);
    }
    const perMonth = months.map(m => ({ label: m, qty: monthly[m] || 0 }));
    const totalOut = perMonth.reduce((a, m) => a + m.qty, 0);
    const avgOut = monthsBack > 0 ? Math.round(totalOut / monthsBack) : 0;
    return { perMonth, avgOut, months };
  };

  const filteredProds = (catFilter === "all" ? products : products.filter(p => p.catId === catFilter)).filter(p => p.active !== false);

  const rows = filteredProds.map(p => {
    const stock = getTot(p.id);
    const baanQty = baan ? getQty(p.id, baan.id) : 0;
    const fulfillQty = fulfillmentLoc ? getQty(p.id, fulfillmentLoc.id) : 0;
    // Storage = our own warehouses (บ้าน + Mycloud). Forecast considers what we still control to refill from.
    const storageQty = baanQty + fulfillQty;
    const { perMonth, avgOut } = getSkuVelocity(p.id);
    const consBal = consLedger.filter(e => e.skuId === p.id).reduce((a, e) => a + (e.sentQty || 0) - (e.soldQty || 0) - (e.returnQty || 0) + (e.adjQty || 0), 0);
    const reserved = getPendingReserved(p.id);
    const available = storageQty - reserved;
    const runsOut = avgOut > 0 ? (available / avgOut) : null;
    return { p, stock, baanQty, fulfillQty, storageQty, consBal, reserved, available, avgOut, perMonth, runsOut };
  }).sort((a, b) => {
    if (!a.avgOut && !b.avgOut) return 0;
    if (!a.avgOut) return 1; if (!b.avgOut) return -1;
    return (a.runsOut ?? 999) - (b.runsOut ?? 999);
  });

  // Smart suggestions — thresholds aligned with lead time
  // Lead time = 1-1.5 months. Critical when ≤ CRITICAL_THRESHOLD (2 mo), Warn when ≤ WARN_THRESHOLD (3 mo)
  const suggestions = rows.flatMap(r => {
    const out = [];
    if (r.runsOut !== null && r.runsOut <= CRITICAL_THRESHOLD) {
      out.push({ kind: "restock", urgency: "critical", row: r,
        text: `${r.p.sku} เหลือ ${r.runsOut.toFixed(1)} เดือน — สั่งทันที (lead time 1-1.5 เดือน)`,
        suggested: Math.max(Math.round(r.avgOut * 3), r.avgOut), });
    } else if (r.runsOut !== null && r.runsOut <= WARN_THRESHOLD) {
      out.push({ kind: "restock", urgency: "warn", row: r,
        text: `${r.p.sku} เหลือ ${r.runsOut.toFixed(1)} เดือน — เตรียมสั่ง`,
        suggested: Math.round(r.avgOut * 3), });
    }
    if (r.baanQty > 30 && r.fulfillQty < 20 && r.avgOut > 0) {
      out.push({ kind: "transfer", urgency: "info", row: r,
        text: `${r.p.sku} ใน Fulfillment เหลือ ${r.fulfillQty} — ย้ายจากบ้านดีกว่า`,
        suggested: Math.min(50, Math.round(r.baanQty / 2)), });
    }
    return out;
  }).sort((a, b) => {
    const order = { critical: 0, warn: 1, info: 2 };
    return order[a.urgency] - order[b.urgency];
  });

  const months3 = rows[0]?.perMonth?.map(m => m.label.slice(5)) || [];

  return (
    <div >
      {/* Smart suggestions */}
      {suggestions.length > 0 && (
        <Card style={{ marginBottom: 14, background: "var(--accent-subtle-2)", borderColor: "var(--accent-border)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
            <Icon name="sparkles" size={18} style={{ color: "var(--accent-hover)" }}/>
            <div style={{ fontWeight: 700, color: "var(--accent-hover)" }}>Smart Suggestions</div>
            <Pill variant="accent">{suggestions.length}</Pill>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {suggestions.slice(0, 5).map((s, i) => {
              const meta = { critical: { color: "danger", icon: "alert" }, warn: { color: "warn", icon: "trend-down" }, info: { color: "info", icon: "trend-up" } }[s.urgency];
              return (
                <div key={i} style={{
                  background: "var(--surface)", borderRadius: "var(--r-md)", padding: "10px 14px",
                  display: "flex", alignItems: "center", gap: 12, border: "1px solid var(--border)",
                }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: "var(--r-sm)",
                    background: `var(--${meta.color}-bg)`, color: `var(--${meta.color})`,
                    display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                  }}><Icon name={meta.icon} size={15}/></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 2 }}>{s.text}</div>
                    <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>
                      แนะนำ: {s.kind === "restock" ? "สั่งเติม" : "ย้าย"} <strong>{s.suggested} {s.row.p.unit}</strong>
                      {s.kind === "restock" && s.row.avgOut > 0 && ` (≈${(s.suggested / s.row.avgOut).toFixed(1)} เดือน)`}
                    </div>
                  </div>
                  <Btn variant="ghost" size="sm" onClick={() => setSelSku(s.row.p.id)}>ดู</Btn>
                </div>
              );
            })}
          </div>
        </Card>
      )}

      {/* Filter bar */}
      <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap", alignItems: "center" }}>
        <span className="xr-label">หมวด:</span>
        <button onClick={() => setCatFilter("all")} className="xr-btn xr-btn--sm" style={{
          background: catFilter === "all" ? "var(--text-1)" : undefined,
          color: catFilter === "all" ? "var(--surface)" : undefined,
          borderColor: catFilter === "all" ? "transparent" : undefined,
        }}>ทั้งหมด</button>
        {cats.map(c => (
          <button key={c.id} onClick={() => setCatFilter(c.id)} className="xr-btn xr-btn--sm" style={{
            background: catFilter === c.id ? c.color : undefined,
            color: catFilter === c.id ? "#fff" : c.color,
            borderColor: catFilter === c.id ? c.color : undefined,
          }}>{c.name}</button>
        ))}
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 6 }}>
          <span className="xr-label">Window:</span>
          <Segmented options={[
            { value: 1, label: "1M" }, { value: 3, label: "3M" }, { value: 6, label: "6M" }, { value: 12, label: "12M" },
          ]} value={monthsBack} onChange={setMonthsBack}/>
        </div>
      </div>

      <InfoBanner icon="info">
        Velocity = ของออกจาก<strong>บ้าน + Mycloud</strong> เฉลี่ย/เดือน ({monthsBack} เดือนล่าสุด) · Available = stock ในคลังเรา − reserved
        · Lead time สั่งของ <strong>1-1.5 เดือน</strong> · <span style={{ color:"var(--danger)" }}>เร่งด่วน ≤2 เดือน</span> · <span style={{ color:"var(--warn)" }}>ติดตาม 2-3 เดือน</span> · <span style={{ color:"var(--success)" }}>ปกติ &gt;3 เดือน</span>
      </InfoBanner>

      <Card padded={false} style={{ marginBottom: 14 }}>
        <div className="xr-table-scroll">
          <table className="xr-table" style={{ minWidth: 800 }}>
            <thead><tr>
              <th>SKU</th><th>หมวด</th>
              <th style={{ textAlign: "right" }}>สต็อครวม</th>
              <th style={{ textAlign: "right" }}>คลังเรา<br/><span style={{ fontSize: 9, fontWeight: 400 }}>บ้าน+Mycloud</span></th>
              <th style={{ textAlign: "right" }}>Reserved</th>
              <th style={{ textAlign: "right" }}>Available</th>
              <th style={{ textAlign: "right" }}>ฝากขาย</th>
              <th style={{ textAlign: "right" }}>Velocity<br/><span style={{ fontSize: 9, fontWeight: 400 }}>out / mo</span></th>
              {months3.map(m => <th key={m} style={{ textAlign: "center" }}>{m}</th>)}
              <th style={{ textAlign: "right" }}>หมดใน</th>
              <th>สถานะ</th>
            </tr></thead>
            <tbody>
              {rows.map(({ p, stock, storageQty, consBal, reserved, available, avgOut, perMonth, runsOut }) => {
                const status = !avgOut ? "no-data" :
                  (available <= 0 || (runsOut !== null && runsOut <= CRITICAL_THRESHOLD)) ? "critical" :
                  (runsOut !== null && runsOut <= WARN_THRESHOLD) ? "warn" : "ok";
                const variantMap = { critical: "danger", warn: "warn", ok: "success", "no-data": "default" };
                const labelMap = { critical: "สั่งทันที", warn: "เตรียมสั่ง", ok: "ปกติ", "no-data": "ไม่มีข้อมูล" };
                return (
                  <tr key={p.id} onClick={() => setSelSku(selSku === p.id ? null : p.id)} style={{
                    cursor: "pointer",
                    background: selSku === p.id ? "var(--accent-subtle)" : undefined,
                  }}>
                    <td><SkuBadge sku={p.sku}/></td>
                    <td><CatBadge cat={catMap[p.catId]}/></td>
                    <td style={{ textAlign: "right", color: "var(--text-2)", fontVariantNumeric: "tabular-nums" }}>{stock}</td>
                    <td style={{ textAlign: "right", fontWeight: 700, color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>{storageQty}</td>
                    <td style={{ textAlign: "right", color: reserved > 0 ? "var(--danger)" : "var(--text-3)", fontVariantNumeric: "tabular-nums" }}>{reserved > 0 ? `-${reserved}` : "—"}</td>
                    <td style={{ textAlign: "right", fontWeight: 700, color: available > 0 ? "var(--success)" : "var(--danger)", fontVariantNumeric: "tabular-nums" }}>{available}</td>
                    <td style={{ textAlign: "right", color: consBal > 0 ? "var(--purple)" : "var(--text-3)", fontVariantNumeric: "tabular-nums" }}>{consBal > 0 ? consBal : "—"}</td>
                    <td style={{ textAlign: "right", fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{avgOut || "—"}</td>
                    {perMonth.map(m => (
                      <td key={m.label} style={{ textAlign: "center", color: m.qty > 0 ? "var(--accent-hover)" : "var(--text-3)", fontVariantNumeric: "tabular-nums" }}>
                        {m.qty > 0 ? m.qty : "—"}
                      </td>
                    ))}
                    <td style={{ textAlign: "right", fontWeight: 700, fontVariantNumeric: "tabular-nums", color: runsOut !== null && runsOut <= CRITICAL_THRESHOLD ? "var(--danger)" : runsOut !== null && runsOut <= WARN_THRESHOLD ? "var(--warn)" : undefined }}>
                      {runsOut !== null ? `${runsOut.toFixed(1)}M` : "∞"}
                    </td>
                    <td><Pill variant={variantMap[status]}>{labelMap[status]}</Pill></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>

      {selSku && <ForecastDetail selSku={selSku} rows={rows} products={products} stores={stores} consLedger={consLedger}/>}
    </div>
  );
}

function ForecastDetail({ selSku, rows, products, stores, consLedger }) {
  const row = rows.find(r => r.p.id === selSku);
  if (!row) return null;
  const { p, stock, storageQty, consBal, avgOut, perMonth, runsOut } = row;
  const suggestedOrder = avgOut > 0 ? Math.round(avgOut * 3) : 0;
  return (
    <Card className="xr-fade-in" style={{ borderColor: "var(--accent)" }}>
      <div style={{ fontWeight: 700, fontSize: 15, color: "var(--accent-hover)", marginBottom: 12 }}>
        <SkuBadge sku={p.sku}/> {p.name}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 10, marginBottom: 16 }}>
        {[
          { label: "คลังเรา (บ้าน+Mycloud)", val: storageQty, unit: p.unit, color: "var(--accent)" },
          { label: "สต็อครวมทุกที่", val: stock, unit: p.unit, color: "var(--text-2)" },
          { label: "ฝากขายรวม", val: consBal, unit: p.unit, color: "var(--purple)" },
          { label: "Velocity (out)", val: avgOut || "—", unit: avgOut ? "ชิ้น/เดือน" : "", color: "var(--text-1)" },
          { label: "คาดหมดใน", val: runsOut !== null ? `${runsOut.toFixed(1)} เดือน` : "—", unit: "lead time 1-1.5 เดือน", color: runsOut !== null && runsOut <= CRITICAL_THRESHOLD ? "var(--danger)" : runsOut !== null && runsOut <= WARN_THRESHOLD ? "var(--warn)" : "var(--success)" },
          { label: "แนะนำสั่งเติม", val: suggestedOrder || "—", unit: suggestedOrder ? `${p.unit} (~3 เดือน)` : "", color: "var(--info)" },
        ].map((c, i) => (
          <div key={i} style={{ background: "var(--surface-2)", borderRadius: "var(--r-md)", padding: "12px 14px" }}>
            <div className="xr-label">{c.label}</div>
            <div style={{ fontSize: 20, fontWeight: 800, color: c.color, fontVariantNumeric: "tabular-nums", marginTop: 4 }}>{c.val}</div>
            {c.unit && <div style={{ fontSize: 10, color: "var(--text-3)" }}>{c.unit}</div>}
          </div>
        ))}
      </div>
      {avgOut > 0 && (
        <>
          <div className="xr-label" style={{ marginBottom: 8 }}>สต็อคออกจากคลังเรารายเดือน</div>
          <div style={{ display: "flex", gap: 4, alignItems: "flex-end", height: 100 }}>
            {perMonth.map(m => {
              const maxVal = Math.max(...perMonth.map(x => x.qty), 1);
              const pct = Math.round((m.qty / maxVal) * 100);
              return (
                <div key={m.label} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 3 }}>
                  <div style={{ fontSize: 10, color: "var(--accent-hover)", fontWeight: 700 }}>{m.qty || ""}</div>
                  <div style={{
                    width: "100%",
                    background: m.qty > 0 ? "linear-gradient(180deg, var(--accent), color-mix(in oklab, var(--accent) 60%, transparent))" : "var(--surface-3)",
                    height: Math.max(pct * 0.7, 4), borderRadius: "4px 4px 0 0",
                    transition: "height var(--dur) var(--ease)",
                  }}/>
                  <div style={{ fontSize: 10, color: "var(--text-3)" }}>{m.label.slice(5)}</div>
                </div>
              );
            })}
          </div>
        </>
      )}
    </Card>
  );
}

// ─── CONSIGNMENT MODULE ────────────────────────────────────────────────
const ADJ_REASONS = ["เสียหาย", "หมดอายุ", "คืนของจากร้าน", "สูญหาย", "ปรับยอด (อื่นๆ)"];

function ConsignmentModule({ products, cats, stores, consLedger, onSaveStores, onSaveLedger, onSetInitial, showToast, askConfirm }) {
  const [view, setView] = useState("summary");
  const [selStore, setSelStore] = useState(stores[0]?.id || "");
  const [selBranch, setSelBranch] = useState(stores[0]?.branches[0]?.id || "");
  const [selYear, setSelYear] = useState(THIS_YEAR);
  const [newStoreName, setNewStoreName] = useState("");
  const [adjModal, setAdjModal] = useState(null);
  const [adjQty, setAdjQty] = useState("");
  const [adjReason, setAdjReason] = useState(ADJ_REASONS[0]);
  const [adjNote, setAdjNote] = useState("");
  const [initModal, setInitModal] = useState(null); // { storeId, branchId, branchName }
  const [initRows, setInitRows] = useState([]); // [{ skuId, qty }]

  const store = stores.find(s => s.id === selStore);
  const branch = store?.branches.find(b => b.id === selBranch);

  const getBalance = (branchId, skuId) => {
    const entries = consLedger.filter(e => e.branchId === branchId && e.skuId === skuId);
    return entries.reduce((a, e) => a + (e.sentQty || 0) - (e.soldQty || 0) - (e.returnQty || 0) + (e.adjQty || 0), 0);
  };
  const getEntry = (branchId, skuId, month, year) =>
    consLedger.find(e => e.branchId === branchId && e.skuId === skuId && e.month === month && e.year === year)
    || { sentQty: 0, soldQty: 0, returnQty: 0, adjQty: 0 };

  const updateEntry = (branchId, skuId, month, year, field, val) => {
    const v = parseInt(val) || 0;
    const exists = consLedger.find(e => e.branchId === branchId && e.skuId === skuId && e.month === month && e.year === year);
    const updated = exists
      ? consLedger.map(e => e.branchId === branchId && e.skuId === skuId && e.month === month && e.year === year ? { ...e, [field]: v } : e)
      : [...consLedger, { id: uid(), branchId, skuId, month, year, sentQty: 0, soldQty: 0, returnQty: 0, adjQty: 0, [field]: v }];
    onSaveLedger(updated);
  };

  const applyAdj = () => {
    const qty = parseInt(adjQty);
    if (!qty || isNaN(qty)) return showToast("กรอกจำนวน (ลบได้)", "err");
    const { branchId, skuId } = adjModal;
    const mo = THIS_MONTH, yr = THIS_YEAR;
    const exists = consLedger.find(e => e.branchId === branchId && e.skuId === skuId && e.month === mo && e.year === yr);
    const updated = exists
      ? consLedger.map(e => e.branchId === branchId && e.skuId === skuId && e.month === mo && e.year === yr
          ? { ...e, adjQty: (e.adjQty || 0) + qty } : e)
      : [...consLedger, { id: uid(), branchId, skuId, month: mo, year: yr, sentQty: 0, soldQty: 0, returnQty: 0, adjQty: qty }];
    onSaveLedger(updated);
    showToast(`✓ ปรับยอด ${qty > 0 ? "+" : ""}${qty} (${adjReason})`);
    setAdjModal(null); setAdjQty(""); setAdjNote("");
  };

  const addStore = () => {
    if (!newStoreName.trim()) return showToast("กรอกชื่อร้าน", "err");
    onSaveStores([...stores, { id: uid(), name: newStoreName.trim(), branches: [] }]);
    setNewStoreName(""); showToast("เพิ่มร้านแล้ว");
  };
  const addBranch = (storeId, name) => {
    if (!name.trim()) return;
    onSaveStores(stores.map(s => s.id === storeId ? { ...s, branches: [...s.branches, { id: uid(), name: name.trim() }] } : s));
    showToast("เพิ่มสาขาแล้ว");
  };
  const delBranch = (storeId, branchId, branchName) => {
    askConfirm(`ลบสาขา "${branchName}"?`, "ประวัติยอดขายของสาขานี้จะยังอยู่ใน Ledger", () => {
      onSaveStores(stores.map(s => s.id === storeId ? { ...s, branches: s.branches.filter(b => b.id !== branchId) } : s));
      showToast("ลบสาขาแล้ว");
    });
  };
  const delStore = (id, name) => {
    askConfirm(`ลบร้านค้า "${name}"?`, "สาขาทั้งหมดในร้านนี้จะถูกลบด้วย", () => {
      onSaveStores(stores.filter(s => s.id !== id));
      showToast("ลบร้านแล้ว");
    });
  };

  const activeProd = products.filter(p => p.active !== false);

  const VIEWS = [
    { id: "summary",   icon: "list",      label: "สรุปทั้งหมด" },
    { id: "dashboard", icon: "dashboard", label: "Dashboard" },
    { id: "report",    icon: "list",      label: "บันทึกยอดรายเดือน" },
    { id: "stores",    icon: "store",     label: "จัดการร้าน/สาขา" },
  ];

  const submitInitial = () => {
    if (!initModal) return;
    const items = initRows.filter(r => r.skuId && parseInt(r.qty) > 0).map(r => ({ skuId: r.skuId, qty: parseInt(r.qty) }));
    if (!items.length) return showToast("กรุณาเพิ่มสินค้าและจำนวน", "err");
    const ok = onSetInitial(initModal.storeId, initModal.branchId, items, "ยอดตั้งต้น");
    if (ok) { setInitModal(null); setInitRows([]); }
  };

  return (
    <div >
      {adjModal && (
        <div className="xr-modal-overlay" onClick={e => e.target === e.currentTarget && setAdjModal(null)}>
          <div className="xr-modal" style={{ padding: 22 }}>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 12, color: "var(--purple)" }}>ปรับยอดคงเหลือ</div>
            <div style={{ padding: "10px 14px", background: "var(--purple-bg)", borderRadius: "var(--r-md)", marginBottom: 12, fontSize: 13 }}>
              <SkuBadge sku={adjModal.skuSku}/>
              <span style={{ marginLeft: 8 }}>{adjModal.skuName}</span>
              <span style={{ marginLeft: 8, color: "var(--purple)", fontWeight: 700 }}>คงเหลือ {getBalance(adjModal.branchId, adjModal.skuId)}</span>
            </div>
            <FG label="เหตุผล" style={{ marginBottom: 10 }}>
              <select className="xr-select" value={adjReason} onChange={e => setAdjReason(e.target.value)}>
                {ADJ_REASONS.map(r => <option key={r}>{r}</option>)}
              </select>
            </FG>
            <FG label="จำนวนที่ปรับ (ลบ = ตัดออก, บวก = เพิ่ม)" style={{ marginBottom: 10 }}>
              <input className="xr-input" type="number" value={adjQty} onChange={e => setAdjQty(e.target.value)}
                placeholder="เช่น -3 (เสียหาย 3 ชิ้น)" autoFocus style={{ fontSize: 16, fontWeight: 700, textAlign: "center" }}/>
            </FG>
            <FG label="หมายเหตุ (ถ้ามี)" style={{ marginBottom: 16 }}>
              <input className="xr-input" value={adjNote} onChange={e => setAdjNote(e.target.value)} placeholder="รายละเอียดเพิ่มเติม"/>
            </FG>
            <div style={{ display: "flex", gap: 8 }}>
              <Btn variant="accent" icon="check" onClick={applyAdj} full>ปรับยอด</Btn>
              <Btn variant="ghost" onClick={() => { setAdjModal(null); setAdjQty(""); setAdjNote(""); }}>ยกเลิก</Btn>
            </div>
          </div>
        </div>
      )}

      {initModal && (
        <div className="xr-modal-overlay" onClick={e => e.target === e.currentTarget && setInitModal(null)}>
          <div className="xr-modal" style={{ padding: 22, maxWidth: 540, width: "94vw" }}>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 6, color: "var(--purple)" }}>ยอดตั้งต้น Consignment</div>
            <div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 12 }}>
              กรอกจำนวนคงเหลือปัจจุบันที่สาขา <strong>{initModal.branchName}</strong> ก่อนเริ่มใช้ระบบ
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 12, maxHeight: "50vh", overflowY: "auto" }}>
              {initRows.map((row, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "minmax(0,2fr) 90px 36px", gap: 8, alignItems: "center" }}>
                  <select className="xr-select" value={row.skuId} onChange={e => setInitRows(rs => rs.map((r, j) => j === i ? { ...r, skuId: e.target.value } : r))}>
                    <option value="">— เลือกสินค้า —</option>
                    {activeProd.map(p => <option key={p.id} value={p.id}>{p.sku} — {p.name}</option>)}
                  </select>
                  <input type="number" min="0" value={row.qty} placeholder="จำนวน"
                    onChange={e => setInitRows(rs => rs.map((r, j) => j === i ? { ...r, qty: e.target.value } : r))}
                    className="xr-input" style={{ textAlign: "center", fontWeight: 700 }}/>
                  <button onClick={() => setInitRows(rs => rs.filter((_, j) => j !== i))} className="xr-btn xr-btn--icon xr-btn--danger-soft" style={{ width: 36, height: 36 }}>
                    <Icon name="x" size={14}/>
                  </button>
                </div>
              ))}
            </div>
            <button onClick={() => setInitRows(rs => [...rs, { skuId: "", qty: "" }])} className="xr-btn xr-btn--soft" style={{ width: "100%", marginBottom: 12 }}>
              <Icon name="plus" size={14}/> เพิ่ม SKU
            </button>
            <div style={{ display: "flex", gap: 8 }}>
              <Btn variant="accent" icon="check" onClick={submitInitial} full>บันทึกยอดตั้งต้น</Btn>
              <Btn variant="ghost" onClick={() => { setInitModal(null); setInitRows([]); }}>ยกเลิก</Btn>
            </div>
          </div>
        </div>
      )}

      <div style={{ display: "flex", gap: 6, marginBottom: 16, flexWrap: "wrap" }}>
        {VIEWS.map(v => (
          <button key={v.id} onClick={() => setView(v.id)} className="xr-btn" style={{
            background: view === v.id ? "var(--purple-bg)" : undefined,
            color: view === v.id ? "var(--purple)" : undefined,
            borderColor: view === v.id ? "var(--purple-border)" : undefined,
          }}><Icon name={v.icon} size={14}/>{v.label}</button>
        ))}
      </div>

      {view === "summary" && (
        <div>
          <InfoBanner icon="info">
            ภาพรวมต่อ <strong>SKU</strong> รวมทุกสาขา · คอลัมน์ <strong>สาขา</strong> = จำนวนสาขาที่มี SKU นี้อยู่
          </InfoBanner>
          {stores.length === 0 && <EmptyState icon="store" title="ยังไม่มีร้านค้า" hint="ไปที่ “จัดการร้าน/สาขา” เพื่อเพิ่มร้านและสาขา"/>}
          {stores.map(st => {
            const branchIds = st.branches.map(b => b.id);
            const skusInStore = activeProd.filter(p =>
              branchIds.some(bid => consLedger.some(e => e.branchId === bid && e.skuId === p.id))
            );
            if (skusInStore.length === 0) return null;
            return (
              <Card key={st.id} style={{ marginBottom: 14 }} padded={false}>
                <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <Icon name="store" size={16} style={{ color: "var(--purple)" }}/>
                    <div style={{ fontWeight: 700 }}>{st.name}</div>
                    <Pill variant="info">{st.branches.length} สาขา</Pill>
                  </div>
                </div>
                <div className="xr-table-scroll">
                  <table className="xr-table">
                    <thead><tr>
                      <th>SKU</th><th>ชื่อ</th>
                      <th style={{ textAlign: "right" }}>ส่งสะสม</th>
                      <th style={{ textAlign: "right" }}>ขายสะสม</th>
                      <th style={{ textAlign: "right" }}>คืน</th>
                      <th style={{ textAlign: "right" }}>ปรับ</th>
                      <th style={{ textAlign: "right", color: "var(--purple)" }}>คงเหลือรวม</th>
                      <th style={{ textAlign: "center" }}>สาขาที่มี</th>
                    </tr></thead>
                    <tbody>
                      {skusInStore.map(p => {
                        const ents = consLedger.filter(e => branchIds.includes(e.branchId) && e.skuId === p.id);
                        const sent = ents.reduce((a, e) => a + (e.sentQty || 0), 0);
                        const sold = ents.reduce((a, e) => a + (e.soldQty || 0), 0);
                        const ret  = ents.reduce((a, e) => a + (e.returnQty || 0), 0);
                        const adj  = ents.reduce((a, e) => a + (e.adjQty || 0), 0);
                        const bal  = sent - sold - ret + adj;
                        const branchesWithStock = st.branches.filter(b =>
                          consLedger.filter(e => e.branchId === b.id && e.skuId === p.id)
                            .reduce((a, e) => a + (e.sentQty || 0) - (e.soldQty || 0) - (e.returnQty || 0) + (e.adjQty || 0), 0) > 0
                        );
                        return (
                          <tr key={p.id}>
                            <td><SkuBadge sku={p.sku}/></td>
                            <td style={{ fontSize: 12.5, color: "var(--text-2)" }}>{p.name}</td>
                            <td style={{ textAlign: "right", color: "var(--info)", fontVariantNumeric: "tabular-nums" }}>{sent || "—"}</td>
                            <td style={{ textAlign: "right", color: "var(--warn)", fontVariantNumeric: "tabular-nums" }}>{sold || "—"}</td>
                            <td style={{ textAlign: "right", color: "var(--success)", fontVariantNumeric: "tabular-nums" }}>{ret || "—"}</td>
                            <td style={{ textAlign: "right", color: adj ? "var(--purple)" : "var(--text-3)", fontVariantNumeric: "tabular-nums" }}>{adj || "—"}</td>
                            <td style={{ textAlign: "right", fontWeight: 800, color: bal > 0 ? "var(--purple)" : bal < 0 ? "var(--danger)" : "var(--text-3)", fontVariantNumeric: "tabular-nums", fontSize: 14 }}>{bal}</td>
                            <td style={{ textAlign: "center", fontSize: 11.5, color: "var(--text-3)" }}>
                              <strong style={{ color: "var(--text-1)" }}>{branchesWithStock.length}</strong> / {st.branches.length}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </Card>
            );
          })}
        </div>
      )}

      {view === "dashboard" && (
        <div>
          {stores.length === 0 && <EmptyState icon="store" title="ยังไม่มีร้านค้า" hint="ไปที่ “จัดการร้าน/สาขา”"/>}
          {stores.map(st => (
            <Card key={st.id} style={{ marginBottom: 14 }} padded={false}>
              <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 8 }}>
                <Icon name="store" size={16} style={{ color: "var(--purple)" }}/>
                <div style={{ fontWeight: 700 }}>{st.name}</div>
              </div>
              {st.branches.length === 0 ? (
                <div style={{ padding: 18, color: "var(--text-3)", fontSize: 13 }}>ยังไม่มีสาขา</div>
              ) : (
                <div className="xr-table-scroll">
                  <table className="xr-table">
                    <thead><tr><th>SKU</th>{st.branches.map(b => <th key={b.id} style={{ textAlign: "right" }}>{b.name}</th>)}</tr></thead>
                    <tbody>
                      {activeProd.filter(p => st.branches.some(b => consLedger.some(e => e.branchId === b.id && e.skuId === p.id))).map(p => (
                        <tr key={p.id}>
                          <td><SkuBadge sku={p.sku}/> <span style={{ marginLeft: 6, color: "var(--text-3)", fontSize: 12 }}>{p.name}</span></td>
                          {st.branches.map(b => {
                            const bal = getBalance(b.id, p.id);
                            const hasData = consLedger.some(e => e.branchId === b.id && e.skuId === p.id);
                            return (
                              <td key={b.id} style={{
                                textAlign: "right",
                                fontWeight: bal > 0 ? 700 : 400,
                                color: bal > 0 ? "var(--purple)" : bal < 0 ? "var(--danger)" : "var(--text-3)",
                                fontVariantNumeric: "tabular-nums",
                              }}>
                                <div style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                                  <span>{bal !== 0 ? bal : "—"}</span>
                                  {hasData && <button onClick={() => setAdjModal({ branchId: b.id, skuId: p.id, skuSku: p.sku, skuName: p.name })} title="ปรับยอด" style={{ padding: "1px 6px", borderRadius: 4, background: "var(--purple-bg)", color: "var(--purple)", fontSize: 10, fontWeight: 700 }}>±</button>}
                                </div>
                              </td>
                            );
                          })}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </Card>
          ))}
        </div>
      )}

      {view === "report" && (
        <Card>
          <div style={{ marginBottom: 12 }}>
            <div className="xr-label" style={{ marginBottom: 6 }}>ร้านค้า</div>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {stores.map(s => (
                <button key={s.id} onClick={() => { setSelStore(s.id); setSelBranch(s.branches[0]?.id || ""); }}
                  className="xr-btn" style={{
                    background: selStore === s.id ? "var(--purple-bg)" : undefined,
                    color: selStore === s.id ? "var(--purple)" : undefined,
                    borderColor: selStore === s.id ? "var(--purple-border)" : undefined,
                  }}>
                  <Icon name="store" size={13}/>{s.name}
                </button>
              ))}
            </div>
          </div>
          {store && (
            <div style={{ marginBottom: 12 }}>
              <div className="xr-label" style={{ marginBottom: 6 }}>สาขา</div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {store.branches.map(b => (
                  <button key={b.id} onClick={() => setSelBranch(b.id)} className="xr-btn xr-btn--sm" style={{
                    background: selBranch === b.id ? "var(--purple-bg)" : undefined,
                    color: selBranch === b.id ? "var(--purple)" : undefined,
                    borderColor: selBranch === b.id ? "var(--purple-border)" : undefined,
                  }}>{b.name}</button>
                ))}
              </div>
            </div>
          )}
          <div style={{ marginBottom: 16 }}>
            <div className="xr-label" style={{ marginBottom: 6 }}>ปี</div>
            <Segmented options={[THIS_YEAR - 1, THIS_YEAR, THIS_YEAR + 1].map(y => ({ value: y, label: String(y) }))} value={selYear} onChange={setSelYear}/>
          </div>

          {branch && (
            <div className="xr-table-scroll">
              <table className="xr-table" style={{ fontSize: 11.5, minWidth: 900 }}>
                <thead><tr>
                  <th style={{ minWidth: 100 }}>SKU</th>
                  {MONTHS_TH.map((m, i) => <th key={i} style={{ textAlign: "center", minWidth: 64 }}>{m}</th>)}
                  <th style={{ textAlign: "right", color: "var(--purple)" }}>คงเหลือ</th>
                </tr></thead>
                <tbody>
                  {activeProd.map(p => {
                    const totalBal = getBalance(branch.id, p.id);
                    return (
                      <tr key={p.id}>
                        <td>
                          <div style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                            <SkuBadge sku={p.sku}/>
                            <button onClick={() => setAdjModal({ branchId: branch.id, skuId: p.id, skuSku: p.sku, skuName: p.name })} title="ปรับยอด" style={{ padding: "1px 6px", borderRadius: 4, background: "var(--purple-bg)", color: "var(--purple)", fontSize: 10, fontWeight: 700 }}>±</button>
                          </div>
                        </td>
                        {MONTHS_TH.map((_, mi) => {
                          const mo = mi + 1;
                          const e = getEntry(branch.id, p.id, mo, selYear);
                          const isCur = mo === THIS_MONTH && selYear === THIS_YEAR;
                          return (
                            <td key={mi} style={{ padding: "4px 3px", background: isCur ? "var(--accent-subtle-2)" : undefined }}>
                              <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                                <input type="number" min="0" placeholder="ฝาก" defaultValue={e.sentQty || ""} onBlur={v => updateEntry(branch.id, p.id, mo, selYear, "sentQty", v.target.value)}
                                  style={{ width: "100%", border: "1px solid var(--info-border)", borderRadius: 3, padding: "2px 3px", fontSize: 10, textAlign: "center", color: "var(--info)", background: "var(--surface)" }}/>
                                <input type="number" min="0" placeholder="ขาย" defaultValue={e.soldQty || ""} onBlur={v => updateEntry(branch.id, p.id, mo, selYear, "soldQty", v.target.value)}
                                  style={{ width: "100%", border: "1px solid var(--warn-border)", borderRadius: 3, padding: "2px 3px", fontSize: 10, textAlign: "center", color: "var(--warn)", background: "var(--surface)" }}/>
                                <input type="number" min="0" placeholder="คืน" defaultValue={e.returnQty || ""} onBlur={v => updateEntry(branch.id, p.id, mo, selYear, "returnQty", v.target.value)}
                                  style={{ width: "100%", border: "1px solid var(--success-border)", borderRadius: 3, padding: "2px 3px", fontSize: 10, textAlign: "center", color: "var(--success)", background: "var(--surface)" }}/>
                                {(e.adjQty || 0) !== 0 && <div style={{ textAlign: "center", fontSize: 9, color: "var(--purple)", fontWeight: 700 }}>{e.adjQty > 0 ? "+" : ""}{e.adjQty}</div>}
                              </div>
                            </td>
                          );
                        })}
                        <td style={{ textAlign: "right", fontWeight: 800, color: totalBal > 0 ? "var(--purple)" : totalBal < 0 ? "var(--danger)" : "var(--text-3)", fontSize: 14, fontVariantNumeric: "tabular-nums" }}>{totalBal}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              <div style={{ display: "flex", gap: 14, marginTop: 12, fontSize: 11 }}>
                <span style={{ color: "var(--info)" }}>● ฝาก (sent)</span>
                <span style={{ color: "var(--warn)" }}>● ขาย (sold)</span>
                <span style={{ color: "var(--success)" }}>● คืน (return)</span>
                <span style={{ color: "var(--purple)" }}>● ปรับยอด (adj)</span>
              </div>
            </div>
          )}
        </Card>
      )}

      {view === "stores" && (
        <div>
          <Card style={{ marginBottom: 14 }}>
            <div style={{ fontWeight: 700, marginBottom: 12 }}>เพิ่มร้านค้าใหม่</div>
            <div style={{ display: "flex", gap: 8 }}>
              <input className="xr-input" value={newStoreName} onChange={e => setNewStoreName(e.target.value)} placeholder="ชื่อร้านค้า" onKeyDown={e => e.key === "Enter" && addStore()}/>
              <Btn variant="accent" icon="plus" onClick={addStore}>เพิ่ม</Btn>
            </div>
          </Card>
          {stores.map(st => (
            <Card key={st.id} style={{ marginBottom: 12 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <Icon name="store" size={16} style={{ color: "var(--purple)" }}/>
                  <div style={{ fontWeight: 700 }}>{st.name}</div>
                </div>
                <Btn variant="danger-soft" size="sm" icon="trash" onClick={() => delStore(st.id, st.name)}>ลบร้าน</Btn>
              </div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 8 }}>
                {st.branches.map(b => (
                  <div key={b.id} style={{
                    padding: "5px 6px 5px 10px", background: "var(--purple-bg)", borderRadius: "var(--r-sm)",
                    display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--purple)", fontWeight: 600,
                  }}>
                    <span>{b.name}</span>
                    <button onClick={() => { setInitModal({ storeId: st.id, branchId: b.id, branchName: b.name }); setInitRows([{ skuId: "", qty: "" }]); }}
                      title="ตั้งยอดตั้งต้น"
                      style={{ color: "var(--purple)", fontSize: 10, fontWeight: 700, padding: "1px 6px", border: "1px solid var(--purple-border)", borderRadius: 4, background: "var(--surface)" }}>
                      +ตั้งต้น
                    </button>
                    <button onClick={() => delBranch(st.id, b.id, b.name)} style={{ color: "var(--purple)", opacity: .5 }}>
                      <Icon name="x" size={12}/>
                    </button>
                  </div>
                ))}
              </div>
              <AddBranchInput onAdd={name => addBranch(st.id, name)}/>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

function AddBranchInput({ onAdd }) {
  const [name, setName] = useState("");
  return (
    <div style={{ display: "flex", gap: 6 }}>
      <input className="xr-input xr-input--sm" value={name} onChange={e => setName(e.target.value)}
        placeholder="ชื่อสาขาใหม่" onKeyDown={e => { if (e.key === "Enter" && name.trim()) { onAdd(name); setName(""); } }}/>
      <Btn variant="soft" size="sm" icon="plus" onClick={() => { if (name.trim()) { onAdd(name); setName(""); } }}>สาขา</Btn>
    </div>
  );
}

Object.assign(window, { ForecastPage, ConsignmentModule });
