// month-picker.jsx — shared sheet for picking month via calendar grid
const ES_MP = window.ExpenseStore;

function MonthPicker({ open, value, onClose, onPick, expenses }) {
  const [year, setYear] = React.useState(() => parseInt(value.split("-")[0], 10));
  React.useEffect(() => {
    if (open) setYear(parseInt(value.split("-")[0], 10));
  }, [open, value]);

  if (!open) return null;

  // monthly totals for this year
  const totals = {};
  (expenses || []).forEach(e => {
    if (e.deleted_at) return;
    const [y, m] = e.date.split("-");
    if (parseInt(y) === year) totals[m] = (totals[m] || 0) + e.amount;
  });

  const today = ES_MP.todayISO();
  const todayYM = today.slice(0, 7);

  return (
    <div className="scrim" onClick={onClose}>
      <div className="sheet" onClick={e => e.stopPropagation()}>
        <div className="sheet-handle"></div>
        <div style={{display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16, padding: "0 4px"}}>
          <button className="ystep" onClick={() => setYear(y => y - 1)}>‹</button>
          <div style={{fontSize: 20, fontWeight: 600, fontFamily: "var(--font-num)"}}>{year} 年</div>
          <button className="ystep" onClick={() => setYear(y => y + 1)}>›</button>
        </div>

        <div className="mp-grid">
          {Array.from({length: 12}, (_, i) => {
            const m = String(i + 1).padStart(2, "0");
            const ym = `${year}-${m}`;
            const total = totals[m] || 0;
            const isSel = ym === value;
            const isToday = ym === todayYM;
            const hasData = total > 0;
            return (
              <button key={m}
                className={"mp-tile" + (isSel ? " sel" : "") + (isToday ? " today" : "") + (hasData ? " has-data" : "")}
                onClick={() => { onPick(ym); onClose(); }}>
                <div className="mp-month">{i + 1}月</div>
                <div className="mp-total">{hasData ? ES_MP.fmtHKD(Math.round(total)) : "—"}</div>
              </button>
            );
          })}
        </div>

        <div style={{display: "flex", justifyContent: "space-between", marginTop: 14, gap: 8}}>
          <button className="toolbtn" onClick={() => { onPick(todayYM); onClose(); }}>↺ 跳到本月</button>
          <button className="toolbtn" onClick={onClose}>關閉</button>
        </div>
      </div>
    </div>
  );
}

window.MonthPicker = MonthPicker;
