// Shared mock data + helpers
const fmt = (n, d=2) => {
  if (n === null || n === undefined || isNaN(n)) return '—';
  const neg = n < 0;
  const s = Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: d, maximumFractionDigits: d });
  return neg ? `-${s}` : s;
};
const fmtCompact = (n) => {
  const abs = Math.abs(n);
  if (abs >= 1e6) return (n/1e6).toFixed(2)+'M';
  if (abs >= 1e3) return (n/1e3).toFixed(1)+'K';
  return n.toString();
};

// Daily cash flow (Nov 2025) — generated, kept deterministic
const seedRand = (() => {
  let s = 42;
  return () => { s = (s*9301 + 49297) % 233280; return s/233280; };
})();

const buildCashflow = () => {
  const rows = [];
  let bal = 87000;
  for (let i = 1; i <= 31; i++) {     // May has 31 days
    const sales   = 35000 + Math.round(seedRand()*45000*100)/100;
    const expense = 18000 + Math.round(seedRand()*22000*100)/100;
    const interest= 2000  + Math.round(seedRand()*3500*100)/100;
    const payChq  = 1500  + Math.round(seedRand()*42000*100)/100;
    const payMNI  = 28000 + Math.round(seedRand()*55000*100)/100;
    const payJS   = 30000 + Math.round(seedRand()*50000*100)/100;
    const total   = sales - expense - interest;
    bal += (sales - expense - interest);
    const status = bal < 0 ? 'bad' : (bal < 11000 ? 'warn' : 'ok');
    rows.push({
      date: `${i}/5/26`,
      iso: `2026-05-${String(i).padStart(2,'0')}`,
      sales, expense, interest, payChq, payMNI, payJS,
      totalAmount: total,
      cashBalance: bal,
      status,
      reqNo: `CF-2605${String(i).padStart(4,'0')}`,
    });
  }
  return rows;
};

const CASHFLOW = buildCashflow();

const SUMMARY = {
  cashBalance: 97177.57,
  totalSales: 359285.67,
  totalExpense: 236807.68,
  totalInterest: 25300.42,
};

const USERS = [
  { id:1, name:'ธงชัย โฮ่หิ้น',         email:'thongchai.h@finx.co',  role:'Admin',   dept:'Finance & Accounting', status:'active',   last:'2 min ago',   color:'#1f2a8e' },
  { id:2, name:'ณัฐรดา เจริญสุข',       email:'natrada.j@finx.co',    role:'Manager', dept:'Finance & Accounting', status:'inactive', last:'4 days ago',  color:'#ec4899' },
  { id:3, name:'อรวรรณ เชาวตะ',         email:'orawan.c@finx.co',     role:'Manager', dept:'Finance & Accounting', status:'active',   last:'1 hr ago',    color:'#10b981' },
  { id:4, name:'กมลชนก เสนาปรึกษ์',     email:'kamonchanok.s@finx.co',role:'Editor',  dept:'Finance & Accounting', status:'active',   last:'3 hr ago',    color:'#f59e0b' },
  { id:5, name:'ขนิษฐา พุ่มเอี่ยม',      email:'kanittha.p@finx.co',   role:'Editor',  dept:'Finance & Accounting', status:'pending',  last:'5 min ago',   color:'#6366f1' },
  { id:6, name:'สายใย ศรีเปารยะ',       email:'saiyai.s@finx.co',     role:'Editor',  dept:'Finance & Accounting', status:'pending',  last:'1 hr ago',    color:'#0ea5e9' },
];

// Recent updates auto-derived from the current USERS list.
// Picks the first N users and pairs them with rotating actions so it always
// stays in sync with Settings → Team Members.
const RECENT_ACTIONS = [
  'Approved CF-26050007',
  'Created decision item',
  'Updated daily cash flow',
  'Locked May 4 entry',
  'Exported monthly report',
  'Reviewed selling expenses',
];
const RECENT_TIME_OFFSETS = [2, 27, 1*60+12, 2*60+45, 4*60+18, 5*60+33];   // minutes ago

const buildRecent = () => USERS.slice(0,5).map((u,i) => ({
  name: u.name,
  role: u.role,
  color: u.color,
  initial: (u.name || '?').trim()[0],
  action: RECENT_ACTIONS[i % RECENT_ACTIONS.length],
  minutesAgo: RECENT_TIME_OFFSETS[i % RECENT_TIME_OFFSETS.length],
}));
const RECENT = buildRecent();

// Friendly "minutes ago" relative to the current page-load time.
const relativeTimeLabel = (minutesAgo) => {
  const now = new Date(Date.now() - minutesAgo*60*1000);
  const hh = String(now.getHours()).padStart(2,'0');
  const mm = String(now.getMinutes()).padStart(2,'0');
  if (minutesAgo < 60) return `${minutesAgo} min ago · ${hh}:${mm}`;
  const h = Math.floor(minutesAgo/60), m = minutesAgo%60;
  return `${h}h ${m?m+'m ':''}ago · ${hh}:${mm}`;
};
// Live system clock — formats current date/time as "7 Nov 25 · 19:42 PM"
function useSystemClock(){
  const [now, setNow] = useState(new Date());
  useEffect(()=>{
    const t = setInterval(()=> setNow(new Date()), 30*1000);  // tick every 30s
    return ()=> clearInterval(t);
  },[]);
  const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const yy = String(now.getFullYear()).slice(2);
  const hh24 = now.getHours();
  const hh = String(hh24).padStart(2,'0');
  const mm = String(now.getMinutes()).padStart(2,'0');
  const ampm = hh24 < 12 ? 'AM' : 'PM';
  return `System · ${now.getDate()} ${MONTHS[now.getMonth()]} ${yy} · ${hh}:${mm} ${ampm}`;
}
window.useSystemClock = useSystemClock;

window.fmt = fmt;
window.fmtCompact = fmtCompact;
window.CASHFLOW = CASHFLOW;
window.SUMMARY = SUMMARY;
window.RECENT = RECENT;
window.USERS = USERS;

// Recompute SUMMARY from any row array
window.calcSummary = function(rows) {
  if (!rows || !rows.length) return SUMMARY;
  return {
    cashBalance:   rows[rows.length - 1].cashBalance,
    totalSales:    rows.reduce((s, r) => s + r.sales, 0),
    totalExpense:  rows.reduce((s, r) => s + r.expense, 0),
    totalInterest: rows.reduce((s, r) => s + r.interest, 0),
  };
};
