/* Stock / Purchases / Issues / Reports views */

function SortTh({ label, k, sortKey, sortDir, onSort, align }) {
  const active = sortKey === k;
  return (
    <button
      type="button"
      className={`th-sort ${active ? 'active' : ''} ${align === 'right' ? 'th-right' : ''}`}
      onClick={() => onSort(k)}
    >
      <span>{label}</span>
      <span className="th-sort-icon" aria-hidden="true">
        {active ? (
          sortDir === 'asc' ? (
            <svg width="10" height="10" viewBox="0 0 10 10"><path d="M5 2.5 L8 7 L2 7 Z" fill="currentColor"/></svg>
          ) : (
            <svg width="10" height="10" viewBox="0 0 10 10"><path d="M5 7.5 L2 3 L8 3 Z" fill="currentColor"/></svg>
          )
        ) : (
          <svg width="10" height="12" viewBox="0 0 10 12" opacity="0.4">
            <path d="M5 1.5 L8 5 L2 5 Z" fill="currentColor"/>
            <path d="M5 10.5 L2 7 L8 7 Z" fill="currentColor"/>
          </svg>
        )}
      </span>
    </button>
  );
}
window.SortTh = SortTh;

const { useMemo: useMemo2, useState: useState2 } = React;

function StockView({ products, onAddPurchase, onAddIssue, onExport, initialFilter }) {
  const [filter, setFilter] = useState2(initialFilter || 'all');
  const [q, setQ] = useState2('');
  const [sortKey, setSortKey] = useState2('sku');
  const [sortDir, setSortDir] = useState2('asc');

  const toggleSort = (key) => {
    if (sortKey === key) {
      setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    } else {
      setSortKey(key);
      setSortDir(key === 'stock' || key === 'value' || key === 'price' ? 'desc' : 'asc');
    }
  };

  const filtered = products
    .filter(p => p.name.toLowerCase().includes(q.toLowerCase()) || p.sku.toLowerCase().includes(q.toLowerCase()))
    .filter(p => {
      if (filter === 'all') return true;
      if (filter === 'low') return p.stock < p.min;
      if (filter === 'ok') return p.stock >= p.min;
      return true;
    });

  const sorted = [...filtered].sort((a, b) => {
    let av, bv;
    switch (sortKey) {
      case 'sku': av = a.sku; bv = b.sku; break;
      case 'name': av = a.name; bv = b.name; break;
      case 'kind': av = a.kind; bv = b.kind; break;
      case 'stock': av = a.stock; bv = b.stock; break;
      case 'min': av = a.min; bv = b.min; break;
      case 'price': av = a.price; bv = b.price; break;
      case 'value': av = a.stock * a.price; bv = b.stock * b.price; break;
      default: av = a.sku; bv = b.sku;
    }
    if (typeof av === 'string') {
      const cmp = av.localeCompare(bv, 'th', { numeric: true });
      return sortDir === 'asc' ? cmp : -cmp;
    }
    return sortDir === 'asc' ? av - bv : bv - av;
  });

  const counts = {
    all: products.length,
    low: products.filter(p => p.stock < p.min).length,
    ok: products.filter(p => p.stock >= p.min).length,
  };

  return (
    <div>
      <div className="flex" style={{marginBottom: 12, gap: 8}}>
        <div className="search" style={{width: 280}}>
          {I.search}
          <input placeholder="ค้นหาชื่อ หรือรหัส SKU..." value={q} onChange={e => setQ(e.target.value)}/>
        </div>
        <div style={{flex: 1}}/>
        <button className="btn" onClick={onExport}>{I.download} Export Excel</button>
        <button className="btn btn-primary" onClick={onAddPurchase}>{I.plus} บันทึกซื้อเข้า</button>
      </div>

      <div className="tabs">
        {[
          {k: 'all', label: 'ทั้งหมด'},
          {k: 'low', label: 'ใกล้หมด'},
          {k: 'ok', label: 'เพียงพอ'},
        ].map(t => (
          <button key={t.k} className={`tab ${filter === t.k ? 'active' : ''}`} onClick={() => setFilter(t.k)}>
            {t.label}<span className="count mono">{counts[t.k]}</span>
          </button>
        ))}
      </div>

      <div className="card">
        <table className="tbl tbl-sortable">
          <thead>
            <tr>
              <th><SortTh label="รหัส / ชื่อสินค้า" k="sku" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th><SortTh label="ประเภท" k="kind" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th style={{textAlign: 'right'}}><SortTh label="คงเหลือ" k="stock" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} align="right"/></th>
              <th>ระดับสต็อก</th>
              <th style={{textAlign: 'right'}}><SortTh label="ขั้นต่ำ" k="min" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} align="right"/></th>
              <th style={{textAlign: 'right'}}><SortTh label="ราคา/หน่วย" k="price" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} align="right"/></th>
              <th style={{textAlign: 'right'}}><SortTh label="มูลค่า" k="value" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} align="right"/></th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {sorted.map(p => {
              const lvl = stockLevel(p);
              const pct = Math.min(100, (p.stock / Math.max(p.min * 2, 1)) * 100);
              return (
                <tr key={p.id}>
                  <td>
                    <div className="fw-500">{p.name}</div>
                    <div className="text-xs muted mono">{p.sku}</div>
                  </td>
                  <td>
                    <span className="pill">{p.kind === 'toner' ? 'ตลับ' : 'ขวด'}</span>
                  </td>
                  <td className="num">
                    <span className="mono fw-600" style={{fontSize: 14}}>{p.stock}</span>
                    <span className="text-xs muted" style={{marginLeft: 4}}>{p.unit}</span>
                  </td>
                  <td style={{width: 160}}>
                    <div className="flex gap-8">
                      <div className="stock-bar" style={{flex: 1}}>
                        <div className={`stock-bar-fill ${lvl}`} style={{width: pct + '%'}}/>
                      </div>
                      {lvl === 'crit' && <span className="pill pill-red">วิกฤต</span>}
                      {lvl === 'low' && <span className="pill pill-amber">ใกล้หมด</span>}
                      {lvl === 'ok' && <span className="pill pill-green">เพียงพอ</span>}
                      {lvl === 'out' && <span className="pill pill-red">หมด</span>}
                    </div>
                  </td>
                  <td className="num mono muted">{p.min}</td>
                  <td className="num mono">฿{fmtMoney(p.price)}</td>
                  <td className="num mono fw-500">฿{fmtMoney(p.stock * p.price)}</td>
                  <td style={{width: 1, whiteSpace: 'nowrap'}}>
                    <button className="btn btn-sm" onClick={onAddIssue}>เบิก</button>
                  </td>
                </tr>
              );
            })}
            {filtered.length === 0 && (
              <tr><td colSpan="8"><div className="empty">ไม่พบรายการ</div></td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function PurchasesView({ purchases, products, onAdd, onExport }) {
  const productById = Object.fromEntries(products.map(p => [p.id, p]));
  const [q, setQ] = useState2('');
  const [sortKey, setSortKey] = useState2('date');
  const [sortDir, setSortDir] = useState2('desc');

  const toggleSort = (key) => {
    if (sortKey === key) setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    else { setSortKey(key); setSortDir(key === 'date' || key === 'qty' || key === 'price' || key === 'total' ? 'desc' : 'asc'); }
  };

  const list = purchases
    .filter(t => {
      const p = productById[t.pid];
      if (!p) return false;
      const s = q.toLowerCase();
      return p.name.toLowerCase().includes(s)
        || p.sku.toLowerCase().includes(s)
        || t.supplier.toLowerCase().includes(s)
        || t.ref.toLowerCase().includes(s);
    })
    .sort((a, b) => {
      const pa = productById[a.pid], pb = productById[b.pid];
      let av, bv;
      switch (sortKey) {
        case 'date': av = a.date; bv = b.date; break;
        case 'ref': av = a.ref; bv = b.ref; break;
        case 'product': av = pa?.name || ''; bv = pb?.name || ''; break;
        case 'supplier': av = a.supplier; bv = b.supplier; break;
        case 'qty': av = a.qty; bv = b.qty; break;
        case 'price': av = a.price; bv = b.price; break;
        case 'total': av = a.qty * a.price; bv = b.qty * b.price; break;
        default: av = a.date; bv = b.date;
      }
      if (typeof av === 'string') {
        const cmp = av.localeCompare(bv, 'th', { numeric: true });
        return sortDir === 'asc' ? cmp : -cmp;
      }
      return sortDir === 'asc' ? av - bv : bv - av;
    });

  const totalQty = list.reduce((s,t) => s + t.qty, 0);
  const totalValue = list.reduce((s,t) => s + t.qty * t.price, 0);

  return (
    <div>
      <div className="flex" style={{marginBottom: 12, gap: 8}}>
        <div className="search" style={{width: 320}}>
          {I.search}
          <input placeholder="ค้นหา supplier, PO, สินค้า..." value={q} onChange={e => setQ(e.target.value)}/>
        </div>
        <div style={{flex: 1}}/>
        <button className="btn" onClick={onExport}>{I.download} Export</button>
        <button className="btn btn-primary" onClick={onAdd}>{I.plus} บันทึกซื้อเข้า</button>
      </div>

      <div className="grid-3" style={{marginBottom: 14}}>
        <div className="kpi">
          <div className="kpi-label">รวมรายการ</div>
          <div className="kpi-value">{list.length}<span className="kpi-unit">ครั้ง</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">จำนวนรวม</div>
          <div className="kpi-value">{fmtNum(totalQty)}<span className="kpi-unit">ขวด/ตลับ</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">มูลค่ารวม</div>
          <div className="kpi-value">฿{fmtMoney(totalValue)}</div>
        </div>
      </div>

      <div className="card">
        <table className="tbl tbl-sortable">
          <thead>
            <tr>
              <th><SortTh label="วันที่" k="date" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th><SortTh label="เลขที่ PO" k="ref" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th><SortTh label="สินค้า" k="product" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th><SortTh label="Supplier" k="supplier" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th style={{textAlign: 'right'}}><SortTh label="จำนวน" k="qty" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} align="right"/></th>
              <th style={{textAlign: 'right'}}><SortTh label="ราคา/หน่วย" k="price" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} align="right"/></th>
              <th style={{textAlign: 'right'}}><SortTh label="รวม" k="total" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} align="right"/></th>
            </tr>
          </thead>
          <tbody>
            {list.map(t => {
              const p = productById[t.pid];
              return (
                <tr key={t.id}>
                  <td className="mono text-sm">{fmtDate(t.date)}</td>
                  <td className="mono text-sm fw-500">{t.ref}</td>
                  <td>
                    <div className="fw-500">{p.name}</div>
                    <div className="text-xs muted mono">{p.sku}</div>
                  </td>
                  <td className="text-sm">{t.supplier}</td>
                  <td className="num mono fw-600">+{t.qty}</td>
                  <td className="num mono">฿{fmtMoney(t.price)}</td>
                  <td className="num mono fw-500">฿{fmtMoney(t.qty * t.price)}</td>
                </tr>
              );
            })}
            {list.length === 0 && (
              <tr><td colSpan="7"><div className="empty">ไม่พบรายการ</div></td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function IssuesView({ issues, products, departments, onAdd, onExport }) {
  const productById = Object.fromEntries(products.map(p => [p.id, p]));
  const deptById = Object.fromEntries(departments.map(d => [d.id, d]));
  const [q, setQ] = useState2('');
  const [deptFilter, setDeptFilter] = useState2('all');
  const [monthFilter, setMonthFilter] = useState2('all');
  const [yearFilter, setYearFilter] = useState2('2026');
  const [sortKey, setSortKey] = useState2('date');
  const [sortDir, setSortDir] = useState2('desc');

  const toggleSort = (key) => {
    if (sortKey === key) setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    else { setSortKey(key); setSortDir(key === 'date' || key === 'qty' ? 'desc' : 'asc'); }
  };

  const list = issues
    .filter(t => deptFilter === 'all' || t.dept === deptFilter)
    .filter(t => {
      const d = new Date(t.date);
      const y = d.getFullYear().toString();
      const m = monthKey(t.date);
      if (yearFilter !== 'all' && y !== yearFilter) return false;
      if (monthFilter !== 'all' && m !== monthFilter) return false;
      return true;
    })
    .filter(t => {
      const p = productById[t.pid];
      if (!p) return false;
      const s = q.toLowerCase();
      return p.name.toLowerCase().includes(s)
        || p.sku.toLowerCase().includes(s)
        || t.user.toLowerCase().includes(s)
        || t.note.toLowerCase().includes(s);
    })
    .sort((a, b) => {
      const pa = productById[a.pid], pb = productById[b.pid];
      const da = deptById[a.dept], db = deptById[b.dept];
      let av, bv;
      switch (sortKey) {
        case 'date': av = a.date; bv = b.date; break;
        case 'product': av = pa?.name || ''; bv = pb?.name || ''; break;
        case 'dept': av = da?.name || ''; bv = db?.name || ''; break;
        case 'user': av = a.user; bv = b.user; break;
        case 'note': av = a.note; bv = b.note; break;
        case 'qty': av = a.qty; bv = b.qty; break;
        default: av = a.date; bv = b.date;
      }
      if (typeof av === 'string') {
        const cmp = av.localeCompare(bv, 'th', { numeric: true });
        return sortDir === 'asc' ? cmp : -cmp;
      }
      return sortDir === 'asc' ? av - bv : bv - av;
    });

  const totalQty = list.reduce((s,t) => s + t.qty, 0);
  const counts = {
    all: issues.length,
    ...Object.fromEntries(departments.map(d => [d.id, issues.filter(t => t.dept === d.id).length]))
  };

  return (
    <div>
      <div className="flex" style={{marginBottom: 12, gap: 8}}>
        <div className="search" style={{width: 320}}>
          {I.search}
          <input placeholder="ค้นหา ผู้ทำเบิก, สินค้า, หมายเหตุ..." value={q} onChange={e => setQ(e.target.value)}/>
        </div>
        <select className="input" style={{width: 180}} value={deptFilter} onChange={e => setDeptFilter(e.target.value)}>
          <option value="all">ทุกสาขา ({counts.all})</option>
          {departments.map(d => (
            <option key={d.id} value={d.id}>{d.name} ({counts[d.id]})</option>
          ))}
        </select>
        <select className="input" style={{width: 120}} value={monthFilter} onChange={e => setMonthFilter(e.target.value)}>
          <option value="all">ทุกเดือน</option>
          {MONTHS.map(m => (
            <option key={m.key} value={m.key}>{m.label}</option>
          ))}
        </select>
        <select className="input" style={{width: 100}} value={yearFilter} onChange={e => setYearFilter(e.target.value)}>
          <option value="all">ทุกปี</option>
          <option value="2026">2026</option>
          <option value="2025">2025</option>
        </select>
        <div style={{flex: 1}}/>
        <button className="btn" onClick={onExport}>{I.download} Export</button>
        <button className="btn btn-primary" onClick={onAdd}>{I.plus} บันทึกเบิกออก</button>
      </div>


      <div className="grid-3" style={{marginBottom: 14}}>
        <div className="kpi">
          <div className="kpi-label">รวมการเบิก</div>
          <div className="kpi-value">{list.length}<span className="kpi-unit">ครั้ง</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">จำนวนรวม</div>
          <div className="kpi-value">{fmtNum(totalQty)}<span className="kpi-unit">ขวด/ตลับ</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">สาขาที่เบิกมากสุด</div>
          {(() => {
            const byDept = departments.map(d => ({...d, qty: issues.filter(t => t.dept === d.id).reduce((s,t) => s + t.qty, 0)}));
            const top = byDept.sort((a,b) => b.qty - a.qty)[0];
            return <div className="kpi-value" style={{fontSize: 22}}>{top.name}<span className="kpi-unit">{top.qty} ตลับ</span></div>;
          })()}
        </div>
      </div>

      <div className="card">
        <table className="tbl tbl-sortable">
          <thead>
            <tr>
              <th><SortTh label="วันที่" k="date" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th><SortTh label="สินค้า" k="product" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th><SortTh label="สาขา/หน่วยงาน" k="dept" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th><SortTh label="ผู้ทำเบิก" k="user" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th><SortTh label="เครื่อง/หมายเหตุ" k="note" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort}/></th>
              <th style={{textAlign: 'right'}}><SortTh label="จำนวน" k="qty" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} align="right"/></th>
            </tr>
          </thead>
          <tbody>
            {list.map(t => {
              const p = productById[t.pid];
              const d = deptById[t.dept];
              return (
                <tr key={t.id}>
                  <td className="mono text-sm">{fmtDate(t.date)}</td>
                  <td>
                    <div className="fw-500">{p.name}</div>
                    <div className="text-xs muted mono">{p.sku}</div>
                  </td>
                  <td>
                    <span className="pill" style={{background: d.color + '18', color: d.color, borderColor: 'transparent'}}>
                      <span className="dot" style={{background: d.color}}></span>{d.name}
                    </span>
                  </td>
                  <td className="text-sm">{t.user}</td>
                  <td className="text-sm muted">{t.note}</td>
                  <td className="num mono fw-600" style={{color: 'var(--amber)'}}>−{t.qty}</td>
                </tr>
              );
            })}
            {list.length === 0 && (
              <tr><td colSpan="6"><div className="empty">ไม่พบรายการ</div></td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ReportsView({ products, purchases, issues, departments, onExport }) {
  const [scope, setScope] = useState2('all');
  const [yearFilter, setYearFilter] = useState2('2026');
  const [costMode, setCostMode] = useState2('fifo'); // 'fifo' or 'current'
  const [expanded, setExpanded] = useState2({}); // key: `${branchId}_${pid}` => bool
  const [search, setSearch] = useState2('');
  const [kindFilter, setKindFilter] = useState2('all');

  // Filter issues by selected year + scope
  const filteredIssues = issues
    .filter(t => {
      if (yearFilter === 'all') return true;
      return new Date(t.date).getFullYear().toString() === yearFilter;
    })
    .filter(t => {
      if (scope === 'all') return true;
      return monthKey(t.date) === scope;
    });

  // Build per-branch breakdown
  const productById = Object.fromEntries(products.map(p => [p.id, p]));
  const branchReports = departments.map(d => {
    const rows = filteredIssues.filter(t => t.dept === d.id);
    // Group by product
    const byProduct = {};
    rows.forEach(t => {
      const p = productById[t.pid];
      if (!p) return;
      if (!byProduct[t.pid]) byProduct[t.pid] = { p, qty: 0, value: 0, count: 0, lastDate: t.date, batches: {} };
      byProduct[t.pid].qty += t.qty;
      // Use FIFO cost when available + mode is fifo
      if (costMode === 'fifo' && t.consumedBatches && t.consumedBatches.length > 0) {
        t.consumedBatches.forEach(c => {
          byProduct[t.pid].value += c.qty * c.price;
          const k = String(c.price) + '_' + (c.overdraw ? 'over' : 'ok');
          if (!byProduct[t.pid].batches[k]) byProduct[t.pid].batches[k] = { price: c.price, qty: 0, overdraw: !!c.overdraw };
          byProduct[t.pid].batches[k].qty += c.qty;
        });
      } else if (costMode === 'fifo' && t.fifoCost !== undefined) {
        byProduct[t.pid].value += t.fifoCost;
      } else {
        byProduct[t.pid].value += p.price * t.qty;
        const k = String(p.price) + '_ok';
        if (!byProduct[t.pid].batches[k]) byProduct[t.pid].batches[k] = { price: p.price, qty: 0, overdraw: false };
        byProduct[t.pid].batches[k].qty += t.qty;
      }
      byProduct[t.pid].count += 1;
      if (t.date > byProduct[t.pid].lastDate) byProduct[t.pid].lastDate = t.date;
    });
    const items = Object.values(byProduct).map(i => ({
      ...i,
      batchList: Object.values(i.batches).sort((a,b) => a.price - b.price),
    })).sort((a,b) => b.qty - a.qty);
    const totalQty = items.reduce((s,i) => s + i.qty, 0);
    const totalValue = items.reduce((s,i) => s + i.value, 0);
    return { ...d, items, totalQty, totalValue, count: rows.length };
  })
    .filter(d => d.totalQty > 0)
    .filter(d => kindFilter === 'all' || d.kind === kindFilter)
    .filter(d => !search || d.name.toLowerCase().includes(search.toLowerCase()) || d.id.toLowerCase().includes(search.toLowerCase()))
    .sort((a,b) => b.name.localeCompare(a.name, 'th') * -1);  // Sort by branch name asc

  function exportBranchReport() {
    const yearLabel = yearFilter === 'all' ? 'ทุกปี' : yearFilter;
    const scopeLabel = scope === 'all' ? `ทุกเดือน ${yearLabel}` : (MONTHS.find(m => m.key === scope)?.label || scope) + ' ' + yearLabel;
    const modeLabel = costMode === 'fifo' ? 'FIFO' : 'ราคาปัจจุบัน';

    // Sort branches alphabetically by name
    const sortedBranches = [...branchReports].sort((a, b) => a.name.localeCompare(b.name, 'th'));

    let csv = '\ufeff';
    csv += `รายงานการเบิกหมึก - ${scopeLabel} (${modeLabel})\n\n`;
    csv += 'สาขา,รหัสหมึก,ชื่อรุ่นหมึก,จำนวนที่เบิก,ราคา/หน่วย,มูลค่ารวม,จำนวนครั้งที่เบิก,เบิกล่าสุด\n';

    sortedBranches.forEach(d => {
      let isFirstRowOfBranch = true;
      d.items.forEach(({ p, qty, value, count, lastDate, batchList }) => {
        if (costMode === 'fifo' && batchList && batchList.length > 0) {
          // One row per FIFO batch
          batchList.forEach(b => {
            csv += [
              isFirstRowOfBranch ? `"${d.name}"` : '',
              p.sku,
              `"${p.name}"`,
              b.qty,
              b.price,
              b.qty * b.price,
              '',
              '',
            ].join(',') + '\n';
            isFirstRowOfBranch = false;
          });
        } else {
          csv += [
            isFirstRowOfBranch ? `"${d.name}"` : '',
            p.sku,
            `"${p.name}"`,
            qty,
            p.price,
            value,
            count,
            fmtDate(lastDate),
          ].join(',') + '\n';
          isFirstRowOfBranch = false;
        }
      });
      // Subtotal per branch
      csv += [
        `"รวม ${d.name}"`,
        '',
        '',
        d.totalQty,
        '',
        d.totalValue,
        d.count,
        '',
      ].join(',') + '\n';
      csv += '\n'; // blank line between branches
    });

    // Grand total
    const grandQtySum = sortedBranches.reduce((s, d) => s + d.totalQty, 0);
    const grandValueSum = sortedBranches.reduce((s, d) => s + d.totalValue, 0);
    const grandCount = sortedBranches.reduce((s, d) => s + d.count, 0);
    csv += `"รวมทั้งหมด",,,${grandQtySum},,${grandValueSum},${grandCount},\n`;

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `รายงานเบิกหมึก-${costMode}-${scope === 'all' ? 'ทุกเดือน' : scope}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  const grandQty = branchReports.reduce((s,d) => s + d.totalQty, 0);
  const grandValue = branchReports.reduce((s,d) => s + d.totalValue, 0);

  const scopeLabel = scope === 'all' ? `ทุกเดือน (${yearFilter === 'all' ? 'ทุกปี' : yearFilter})`
    : (MONTHS.find(m => m.key === scope)?.label || scope) + ' ' + (yearFilter === 'all' ? '' : yearFilter);

  const counts = {
    all: departments.length,
    branch: departments.filter(d => d.kind === 'branch').length,
    hq: departments.filter(d => d.kind === 'hq').length,
  };

  return (
    <div className="row-gap">
      {/* Filter bar */}
      <div className="card">
        <div className="card-pad" style={{display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center'}}>
          <div>
            <div className="text-xs muted" style={{marginBottom: 4}}>เดือน</div>
            <div className="flex gap-6">
              <button className={`btn btn-sm ${scope === 'all' ? 'btn-primary' : ''}`} onClick={() => setScope('all')}>
                ทุกเดือน
              </button>
              {MONTHS.map(m => (
                <button key={m.key}
                        className={`btn btn-sm ${scope === m.key ? 'btn-primary' : ''}`}
                        onClick={() => setScope(m.key)}>
                  {m.label}
                </button>
              ))}
            </div>
          </div>
          <div>
            <div className="text-xs muted" style={{marginBottom: 4}}>ปี</div>
            <select value={yearFilter} onChange={e => setYearFilter(e.target.value)} style={{minWidth: 90}}>
              <option value="all">ทุกปี</option>
              <option value="2026">2026</option>
              <option value="2025">2025</option>
            </select>
          </div>
          <div>
            <div className="text-xs muted" style={{marginBottom: 4}}>วิธีคำนวณราคา</div>
            <div className="flex gap-6">
              <button className={`btn btn-sm ${costMode === 'fifo' ? 'btn-primary' : ''}`} onClick={() => setCostMode('fifo')}>
                FIFO
              </button>
              <button className={`btn btn-sm ${costMode === 'current' ? 'btn-primary' : ''}`} onClick={() => setCostMode('current')}>
                ราคาปัจจุบัน
              </button>
            </div>
          </div>
          <div style={{flex: 1}}/>
          <div className="search" style={{width: 240}}>
            {I.search}
            <input placeholder="ค้นหาสาขา..." value={search} onChange={e => setSearch(e.target.value)}/>
          </div>
          <button className="btn btn-primary" onClick={exportBranchReport}>{I.download} Export CSV</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="kpi-grid" style={{gridTemplateColumns: 'repeat(4, 1fr)'}}>
        <div className="kpi">
          <div className="kpi-label">{I.cal} ช่วงเวลา</div>
          <div className="kpi-value" style={{fontSize: 18}}>{scopeLabel}</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">{I.users} สาขาที่มีการเบิก</div>
          <div className="kpi-value">{branchReports.length}<span className="kpi-unit">/ {departments.length}</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">{I.arrow_out} จำนวนรวม</div>
          <div className="kpi-value">{fmtNum(grandQty)}<span className="kpi-unit">ตลับ</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">{I.chart} มูลค่ารวม</div>
          <div className="kpi-value">฿{fmtMoney(grandValue)}</div>
        </div>
      </div>

      {/* Branch type filter tabs */}
      <div className="tabs">
        <button className={`tab ${kindFilter === 'all' ? 'active' : ''}`} onClick={() => setKindFilter('all')}>
          ทั้งหมด<span className="count mono">{counts.all}</span>
        </button>
        <button className={`tab ${kindFilter === 'branch' ? 'active' : ''}`} onClick={() => setKindFilter('branch')}>
          สาขา<span className="count mono">{counts.branch}</span>
        </button>
        <button className={`tab ${kindFilter === 'hq' ? 'active' : ''}`} onClick={() => setKindFilter('hq')}>
          สำนักงานใหญ่<span className="count mono">{counts.hq}</span>
        </button>
      </div>

      {/* Per-branch detail cards */}
      {branchReports.length === 0 ? (
        <div className="card">
          <div className="empty" style={{padding: '60px 20px'}}>
            ไม่มีการเบิกในช่วงเวลานี้
          </div>
        </div>
      ) : branchReports.map((d, idx) => (
        <div key={d.id} className="card">
          <div className="card-head">
            <div className="flex gap-12" style={{alignItems: 'center'}}>
              <span className="mono muted text-sm" style={{width: 22, textAlign: 'right'}}>{idx + 1}</span>
              <span style={{width: 8, height: 8, borderRadius: '50%', background: d.color, flexShrink: 0}}></span>
              <div>
                <h3 className="card-title">{d.name}</h3>
                <div className="card-sub mono">{d.id} · {d.kind === 'hq' ? 'สำนักงานใหญ่' : 'สาขา'}</div>
              </div>
            </div>
            <div style={{marginLeft: 'auto', textAlign: 'right'}}>
              <div className="mono fw-600" style={{fontSize: 18, color: d.color}}>{fmtNum(d.totalQty)} <span style={{fontSize: 12, fontWeight: 400, color: 'var(--text-3)'}}>ตลับ</span></div>
              <div className="text-xs muted mono">฿{fmtMoney(d.totalValue)} · {d.count} ครั้ง</div>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th style={{width: 110}}>รหัสหมึก</th>
                <th>ชื่อรุ่นหมึก</th>
                <th style={{textAlign: 'right', width: 90}}>จำนวน</th>
                <th style={{textAlign: 'right', width: 110}}>ราคา/หน่วย</th>
                <th style={{textAlign: 'right', width: 120}}>มูลค่ารวม</th>
                <th style={{textAlign: 'right', width: 80}}>ครั้ง</th>
                <th style={{textAlign: 'right', width: 110}}>เบิกล่าสุด</th>
              </tr>
            </thead>
            <tbody>
              {d.items.map(({ p, qty, value, count, lastDate, batchList }) => {
                const key = d.id + '_' + p.id;
                const isOpen = !!expanded[key];
                const hasBreakdown = batchList && batchList.length > 0;
                return (
                  <React.Fragment key={p.id}>
                    <tr>
                      <td className="mono fw-500 text-sm">
                        {hasBreakdown ? (
                          <button onClick={() => setExpanded({ ...expanded, [key]: !isOpen })}
                                  className="btn btn-sm btn-ghost"
                                  style={{padding: '2px 6px', fontFamily: 'inherit', color: 'var(--ink)'}}>
                            <span style={{display: 'inline-block', width: 12, transition: 'transform 0.2s', transform: isOpen ? 'rotate(90deg)' : 'rotate(0deg)'}}>›</span>
                            {p.sku}
                          </button>
                        ) : p.sku}
                      </td>
                  <td><span className="fw-500">{p.name}</span></td>
                  <td className="num mono fw-600">{fmtNum(qty)}</td>
                  <td className="num mono muted">฿{fmtMoney(p.price)}</td>
                  <td className="num mono fw-500">฿{fmtMoney(value)}</td>
                  <td className="num mono muted">{count}</td>
                  <td className="num mono text-xs muted">{fmtDate(lastDate)}</td>
                </tr>
                {isOpen && hasBreakdown && (
                  <tr style={{background: 'var(--surface-2)'}}>
                    <td></td>
                    <td colSpan="6" style={{padding: '10px 14px'}}>
                      <div className="text-xs muted fw-600" style={{marginBottom: 6}}>📋 FIFO breakdown</div>
                      {batchList.map((b, i) => (
                        <div key={i} className="flex-between text-sm" style={{padding: '2px 0', maxWidth: 420}}>
                          <span style={{color: b.overdraw ? 'var(--red)' : 'var(--text-2)'}}>
                            {b.overdraw ? '⚠ เกินสต็อก ' : '• '}
                            <span className="mono fw-500">{fmtNum(b.qty)}</span> ตลับ × ฿<span className="mono">{fmtMoney(b.price)}</span>
                          </span>
                          <span className="mono fw-500">= ฿{fmtMoney(b.qty * b.price)}</span>
                        </div>
                      ))}
                      <div className="flex-between text-sm fw-600" style={{padding: '6px 0 0', marginTop: 4, borderTop: '1px solid var(--border)', maxWidth: 420}}>
                        <span>รวม</span>
                        <span className="mono" style={{color: 'var(--ink)'}}>฿{fmtMoney(value)}</span>
                      </div>
                    </td>
                  </tr>
                )}
                </React.Fragment>
                );
              })}
            </tbody>
          </table>
        </div>
      ))}
    </div>
  );
}

function Donut({ data, total }) {
  const R = 56, sw = 18, cx = 70, cy = 70;
  const C = 2 * Math.PI * R;
  let acc = 0;
  if (total === 0) {
    return <svg width="140" height="140"><circle cx={cx} cy={cy} r={R} fill="none" stroke="var(--border)" strokeWidth={sw}/></svg>;
  }
  return (
    <svg width="140" height="140">
      <circle cx={cx} cy={cy} r={R} fill="none" stroke="var(--bg)" strokeWidth={sw}/>
      {data.filter(d => d.qty > 0).map(d => {
        const frac = d.qty / total;
        const dash = frac * C;
        const offset = acc;
        acc += dash;
        return (
          <circle key={d.id}
            cx={cx} cy={cy} r={R}
            fill="none"
            stroke={d.color}
            strokeWidth={sw}
            strokeDasharray={`${dash} ${C - dash}`}
            strokeDashoffset={-offset}
            transform={`rotate(-90 ${cx} ${cy})`}
          />
        );
      })}
      <text x={cx} y={cy + 4} textAnchor="middle" className="mono" style={{fontSize: 18, fontWeight: 600, fill: 'var(--text)'}}>{total}</text>
      <text x={cx} y={cy + 22} textAnchor="middle" style={{fontSize: 10, fill: 'var(--text-3)'}}>เบิกทั้งหมด</text>
    </svg>
  );
}

Object.assign(window, { StockView, PurchasesView, IssuesView, ReportsView, Donut });

