// Dashboard + Daily Cash Flow (main page from image 1)

function Sparkline({ data, color="#1f2a8e", h=30, w=100, fill=true }){
  const max = Math.max(...data), min = Math.min(...data);
  const range = (max-min) || 1;
  const stepX = w/(data.length-1);
  const pts = data.map((v,i)=>[i*stepX, h - ((v-min)/range)*(h-4) - 2]);
  const d = pts.map((p,i)=> (i?'L':'M')+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ');
  const area = d + ` L ${w} ${h} L 0 ${h} Z`;
  const gid = "spk-"+color.replace('#','');
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${h}`}>
      <defs>
        <linearGradient id={gid} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor={color} stopOpacity=".35"/>
          <stop offset="1" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {fill && <path d={area} fill={`url(#${gid})`}/>}
      <path d={d} fill="none" stroke={color} strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round"/>
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.5" fill={color}/>
    </svg>
  );
}

function StatusBadge({ s }){
  if (s==='ok')   return <span className="status ok"><I.Check size={12}/> OK</span>;
  if (s==='warn') return <span className="status warn"><I.AlertCircle size={12}/> Watch</span>;
  return <span className="status bad"><I.BanCircle size={12}/> Critical</span>;
}

function NewEntryForm({ onSubmit }){
  const [f, setF] = useState({ date: new Date().toISOString().slice(0,10), sales:0, expense:0, interest:0, note:'' });
  const set = (k,v) => setF(x => ({...x, [k]:v}));
  return (
    <div style={{display:'grid',gap:12}}>
      <div className="field">
        <label>Date <span className="req">*</span></label>
        <div className="dateinput">
          <I.Cal size={14} stroke="#7b87a8"/>
          <input type="date" value={f.date} onChange={e=>set('date',e.target.value)}/>
        </div>
      </div>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:10}}>
        <div className="field">
          <label>Sales</label>
          <input className="input" type="number" value={f.sales} onChange={e=>set('sales',parseFloat(e.target.value)||0)}/>
        </div>
        <div className="field">
          <label>Expense</label>
          <input className="input" type="number" value={f.expense} onChange={e=>set('expense',parseFloat(e.target.value)||0)}/>
        </div>
        <div className="field">
          <label>Interest</label>
          <input className="input" type="number" value={f.interest} onChange={e=>set('interest',parseFloat(e.target.value)||0)}/>
        </div>
      </div>
      <div className="field">
        <label>Note</label>
        <input className="input" value={f.note} onChange={e=>set('note',e.target.value)} placeholder="Optional reference…"/>
      </div>
      <div style={{background:'#f7f8fc',padding:12,borderRadius:10,display:'flex',justifyContent:'space-between',fontSize:13}}>
        <span style={{color:'var(--muted)'}}>Net impact</span>
        <span className="mono" style={{fontWeight:800, color: (f.sales-f.expense-f.interest)>=0?'#15803d':'#b91c1c'}}>
          {fmt(f.sales-f.expense-f.interest)} THB
        </span>
      </div>
      <button className="btn primary" style={{justifyContent:'center'}}
              onClick={()=>{ onSubmit && onSubmit(f); window.closeModal(); }}>
        <I.Check size={14}/> Create entry
      </button>
    </div>
  );
}

function DashboardView({ onNav }){
  const today = '2026-05-07';
  const clock = useSystemClock();
  const [tick, setTick] = useState(0);   // bumps when settings change to force re-render
  const [refreshing, setRefreshing] = useState(false);
  const [from, setFrom] = useState('');
  const [to, setTo]     = useState('');
  const [grain, setGrain] = useState('');
  const [page, setPage] = useState(1);
  const [showFilters, setShowFilters] = useState(true);
  const [extraRows, setExtraRows] = useState([]); // new entries
  const [data, setData] = useState(CASHFLOW);
  const pageSize = 7;

  // Load live data from Cloudflare D1 on mount
  useEffect(() => {
    const month = new Date().toISOString().slice(0, 7);
    window.finxDB.getCashflow(month).then(rows => {
      if (rows && rows.length > 0) setData(rows);
    }).catch(() => {});
  }, []);

  const datesReady = !!from && !!to;
  const allRows = [...data, ...extraRows].sort((a,b)=> a.iso<b.iso?-1:1);
  const filtered = datesReady ? allRows.filter(r => r.iso >= from && r.iso <= to) : [];
  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const start = (page-1)*pageSize;
  const rows  = filtered.slice(start, start+pageSize);

  useEffect(()=>{ if (page > totalPages) setPage(1); }, [from, to, totalPages]);

  const spkBal     = CASHFLOW.slice(0,14).map(r=>r.cashBalance);
  const spkSales   = CASHFLOW.slice(0,14).map(r=>r.sales);
  const spkExpense = CASHFLOW.slice(0,14).map(r=>r.expense);
  const spkInt     = CASHFLOW.slice(0,14).map(r=>r.interest);

  // % vs previous period — split current dataset into two halves and compare averages.
  // For Cash Balance we compare END-of-period values (last day vs midpoint), since balance is a running total.
  const calcDelta = (key, useLast=false) => {
    const mid  = Math.floor(CASHFLOW.length/2);
    const prev = CASHFLOW.slice(0, mid);
    const curr = CASHFLOW.slice(mid);
    if (prev.length===0 || curr.length===0) return { pct: 0, dir: 'up', prevVal: 0, currVal: 0 };
    let prevVal, currVal;
    if (useLast){
      prevVal = prev[prev.length-1][key];
      currVal = curr[curr.length-1][key];
    } else {
      prevVal = prev.reduce((s,r)=>s+r[key],0) / prev.length;
      currVal = curr.reduce((s,r)=>s+r[key],0) / curr.length;
    }
    const pct = prevVal === 0 ? 0 : ((currVal - prevVal) / Math.abs(prevVal)) * 100;
    return { pct, dir: pct >= 0 ? 'up' : 'down', prevVal, currVal };
  };

  const dBal   = calcDelta('cashBalance', true);
  const dSales = calcDelta('sales');
  const dExp   = calcDelta('expense');
  const dInt   = calcDelta('interest');

  const KPIS = [
    { tone:'blue',    label:'Cash Balance',  value:SUMMARY.cashBalance, delta:dBal,   spk:spkBal,     color:'#1f2a8e' },
    { tone:'green',   label:'Total Sales',   value:SUMMARY.totalSales,  delta:dSales, spk:spkSales,   color:'#16a34a' },
    { tone:'red',     label:'Total Expense', value:SUMMARY.totalExpense,delta:dExp,   spk:spkExpense, color:'#dc2626' },
    { tone:'magenta', label:'Total Interest',value:SUMMARY.totalInterest,delta:dInt,  spk:spkInt,     color:'#c026d3' },
  ];

  const explainDelta = (kpi) => {
    const d = kpi.delta;
    window.openModal({
      title: kpi.label + ' — เปรียบเทียบกับช่วงก่อนหน้า',
      size: 'md',
      message: (
        <div style={{display:'flex',flexDirection:'column',gap:12}}>
          <div style={{fontSize:13.5,color:'var(--ink-2)',lineHeight:1.55}}>
            แสดงการเปลี่ยนแปลงของ <b>{kpi.label}</b> เทียบกับช่วงครึ่งแรกของรอบเดือนปัจจุบัน
          </div>
          <div style={{background:'linear-gradient(135deg,#eef0ff,#f0fbfa)',border:'1px solid #dde5f7',borderRadius:10,padding:'12px 14px'}}>
            <div style={{fontSize:11,color:'var(--muted)',letterSpacing:'.06em',textTransform:'uppercase',marginBottom:6}}>Formula</div>
            <div className="mono" style={{fontSize:14,fontWeight:700,color:'var(--brand)'}}>
              ((Current − Previous) ÷ |Previous|) × 100
            </div>
          </div>
          <div>
            <div style={{fontSize:11,color:'var(--muted)',letterSpacing:'.06em',textTransform:'uppercase',marginBottom:6}}>Values used</div>
            <div style={{display:'flex',flexDirection:'column',gap:4}}>
              {[
                [kpi.label==='Cash Balance' ? 'Previous balance (mid-month)' : 'Average prev. half',      fmt(d.prevVal)+' THB'],
                [kpi.label==='Cash Balance' ? 'Current balance (latest day)' : 'Average current half',   fmt(d.currVal)+' THB'],
                ['Difference', (d.currVal-d.prevVal>=0?'+':'') + fmt(d.currVal-d.prevVal)+' THB'],
                ['Result',     (d.pct>=0?'+':'') + d.pct.toFixed(1)+'%'],
              ].map(([k,v],i,arr)=>(
                <div key={i} style={{
                  display:'flex',justifyContent:'space-between',padding:'8px 12px',
                  background: i===arr.length-1 ? 'linear-gradient(90deg,#eef0ff,#fff)' : '#f7f8fc',
                  borderRadius:8,fontSize:13,
                  fontWeight: i===arr.length-1 ? 700 : 500,
                  color: i===arr.length-1 ? kpi.color : 'var(--ink-2)',
                }}>
                  <span>{k}</span><span className="mono">{v}</span>
                </div>
              ))}
            </div>
          </div>
          <div style={{background:'#fffbeb',border:'1px solid #fde68a',color:'#92400e',padding:'10px 12px',borderRadius:8,fontSize:12,lineHeight:1.5}}>
            <b>ช่วงเทียบ · </b>ครึ่งแรก ({CASHFLOW[0].date}–{CASHFLOW[Math.floor(CASHFLOW.length/2)-1].date}) vs ครึ่งหลัง ({CASHFLOW[Math.floor(CASHFLOW.length/2)].date}–{CASHFLOW[CASHFLOW.length-1].date})
          </div>
        </div>
      ),
      actions:[{ label:'Close', kind:'primary' }]
    });
  };

  const exportCSV = () => {
    if (!datesReady){ window.toast('กรุณาเลือก Start Date และ End Date ก่อน', {tone:'warn'}); return; }
    const head = ['Date','Sales','Expense','Interest','Total Amount','Cash Balance','Status'];
    const data = filtered.map(r => [r.date, r.sales.toFixed(2), r.expense.toFixed(2), r.interest.toFixed(2), r.totalAmount.toFixed(2), r.cashBalance.toFixed(2), r.status]);
    window.downloadCSV(`cashflow_${from}_${to}.csv`, [head, ...data]);
    window.toast(`Exported ${filtered.length} rows`, { tone:'success', title:'CSV downloaded' });
  };

  const newEntry = () => {
    window.openModal({
      title:'New Cash Flow Entry',
      size:'md',
      message: <NewEntryForm onSubmit={(f)=>{
        const sales=+f.sales, expense=+f.expense, interest=+f.interest;
        const total = sales-expense-interest;
        const prevBal = (extraRows[extraRows.length-1]?.cashBalance) ?? SUMMARY.cashBalance;
        const cashBalance = prevBal + total;
        const date = f.date;
        const [y,m,d] = date.split('-');
        const row = {
          date:`${+d}/${+m}/${y.slice(2)}`, iso:date,
          sales, expense, interest,
          payChq:0, payMNI:0, payJS:0,
          totalAmount:total, cashBalance,
          status: cashBalance<0?'bad':cashBalance<11000?'warn':'ok',
          reqNo:'CF-NEW'+Math.floor(Math.random()*9999).toString().padStart(4,'0')
        };
        setExtraRows(r => [...r, row]);
        window.finxDB.saveCashflowEntry(row).catch(() => {});
        window.toast('Entry created · '+row.reqNo, { tone:'success', title:'Saved' });
      }}/>
    });
  };

  const newPeriod = (g) => {
    setGrain(g);
    if (g==='day'){ setFrom('2026-05-01'); setTo('2026-05-07'); }
    if (g==='week'){ setFrom('2026-05-01'); setTo('2026-05-15'); }
    if (g==='month'){ setFrom('2026-05-01'); setTo('2026-05-31'); }
    setPage(1);
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Daily Cash Flow Overview</div>
          <div className="page-sub">Fiscal year 2026 · May · all amounts in THB</div>
        </div>
        <div className="row" style={{gap:10}}>
          <span className="pill"><I.Pin size={12}/> Period: May 2026</span>
          <button className="btn" disabled={refreshing} onClick={()=>{
            setRefreshing(true);
            window.toast('กำลังโหลดข้อมูลล่าสุด…',{tone:'info', ttl:1000});
            // Simulate a backend round-trip — actually re-read fresh data
            setTimeout(()=>{
              setData([...CASHFLOW]);   // replace reference so React re-renders
              setExtraRows([]);
              setTick(t=>t+1);
              setRefreshing(false);
              window.toast(
                `Refreshed · โหลด ${CASHFLOW.length} entries · ${new Date().toLocaleTimeString()}`,
                {tone:'success', title:'Daily Cash Flow'});
            }, 700);
          }}>
            <span style={{display:'inline-flex',animation:refreshing?'spin 0.8s linear infinite':'none'}}>
              <I.Refresh size={14}/>
            </span>
            {refreshing ? 'Refreshing…' : 'Refresh'}
          </button>
          <button className="btn" onClick={exportCSV}><I.Download size={14}/> Export</button>
          <button className="btn primary" onClick={newEntry}><I.Plus size={14}/> New entry</button>
        </div>
      </div>

      <div className="kpi-grid">
        {KPIS.map((k,i)=>(
          <div className={"kpi "+k.tone} key={i} onClick={()=> onNav && onNav('analytics')} style={{cursor:'pointer'}}>
            <div className="label">
              <span>{k.label}</span>
              <span className="cur">THB</span>
            </div>
            <div className="value mono">{fmt(k.value)}</div>
            <div className="foot">
              <span className={"delta "+k.delta.dir}
                    onClick={(e)=>{ e.stopPropagation(); explainDelta(k); }}
                    title="คลิกเพื่อดูวิธีคำนวณ"
                    style={{cursor:'help'}}>
                {k.delta.dir==='up' ? <I.TrendUp size={12}/> : <I.TrendDown size={12}/>}
                {(k.delta.pct>=0?'+':'') + k.delta.pct.toFixed(1)}% vs prev.
              </span>
              <Sparkline data={k.spk} color={k.color}/>
            </div>
          </div>
        ))}
      </div>

      <div className="grid-2">
        <div className="card elev">
          <div className="card-head">
            <div className="row" style={{gap:10}}>
              <span style={{width:8,height:22,borderRadius:3,background:'linear-gradient(180deg,#2cb8b0,#1f2a8e)'}}/>
              <div className="card-title">Daily Cash Flow</div>
              <span className="chip">{filtered.length} entries</span>
            </div>
            <div className="row" style={{gap:8}}>
              <div className="seg">
                <button className={grain==='day'?'on':''}   onClick={()=>newPeriod('day')}>Day</button>
                <button className={grain==='week'?'on':''}  onClick={()=>newPeriod('week')}>Week</button>
                <button className={grain==='month'?'on':''} onClick={()=>newPeriod('month')}>Month</button>
              </div>
              <button className="btn sm primary" onClick={()=> onNav && onNav('decision')}>View All <I.Chev size={12}/></button>
            </div>
          </div>
          {showFilters && (
          <div style={{padding:'14px 20px',display:'flex',gap:14,alignItems:'flex-end',flexWrap:'wrap'}}>
            <div className="field" style={{flex:'1 1 180px'}}>
              <label>Start Date</label>
              <div className="dateinput">
                <I.Cal size={14} stroke="#7b87a8"/>
                <input type="date" value={from} onChange={e=>setFrom(e.target.value)}/>
              </div>
            </div>
            <div className="field" style={{flex:'1 1 180px'}}>
              <label>End Date</label>
              <div className="dateinput">
                <I.Cal size={14} stroke="#7b87a8"/>
                <input type="date" value={to} onChange={e=>setTo(e.target.value)}/>
              </div>
            </div>
            <div className="row" style={{gap:8,marginLeft:'auto'}}>
              <button className="btn sm" onClick={()=>setShowFilters(false)}><I.Filter size={12}/> Hide filters</button>
              <button className="btn sm" onClick={exportCSV}><I.Download size={12}/> CSV</button>
            </div>
          </div>
          )}
          {!showFilters && (
            <div style={{padding:'10px 20px'}}>
              <button className="btn sm" onClick={()=>setShowFilters(true)}><I.Filter size={12}/> Show filters</button>
            </div>
          )}

          <div className="tbl-wrap" style={{padding:'0 8px 8px'}}>
            <table className="t">
              <thead>
                <tr>
                  <th>Date</th>
                  <th className="num">Sales</th>
                  <th className="num">Expense</th>
                  <th className="num">Interest</th>
                  <th className="num">Total Amount</th>
                  <th className="num">Cash Balance</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((r,i)=>(
                  <tr key={r.iso} style={{animation:`fadein .25s ${i*30}ms both`,cursor:'pointer'}}
                      onClick={()=> window.openModal({
                        title:'Cash flow detail · '+r.date,
                        size:'md',
                        message: <CashflowDetail r={r}/>,
                        actions:[{label:'Close', kind:'ghost'}]
                      })}>
                    <td className="mono" style={{fontWeight:600}}>{r.date}</td>
                    <td className="num">{fmt(r.sales)}</td>
                    <td className="num">{fmt(r.expense)}</td>
                    <td className="num">{fmt(r.interest)}</td>
                    <td className="num" style={{fontWeight:700}}>{fmt(r.totalAmount)}</td>
                    <td className={"num "+(r.cashBalance<0?'neg':'')} style={{fontWeight:700}}>{fmt(r.cashBalance)}</td>
                    <td><StatusBadge s={r.status}/></td>
                  </tr>
                ))}
                {rows.length===0 && (
                  <tr><td colSpan="7" style={{textAlign:'center',padding:40,color:'var(--muted)'}}>
                    {!datesReady
                      ? <div style={{display:'flex',flexDirection:'column',alignItems:'center',gap:8}}>
                          <I.Cal size={28} stroke="#cfd5e8"/>
                          <div style={{fontWeight:600,color:'var(--ink-2)'}}>กรุณาเลือก Start Date และ End Date</div>
                          <div style={{fontSize:12}}>เลือกช่วงวันที่ที่ต้องการดูข้อมูล Daily Cash Flow</div>
                        </div>
                      : 'No entries in this date range.'}
                  </td></tr>
                )}
              </tbody>
            </table>
          </div>

          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'14px 20px',borderTop:'1px solid var(--line)'}}>
            <div className="muted" style={{fontSize:12.5}}>
              Showing {filtered.length===0?0:start+1} to {Math.min(start+pageSize, filtered.length)} of {filtered.length} entries
            </div>
            <div className="row" style={{gap:4}}>
              <button className="btn sm" disabled={page<=1} onClick={()=>setPage(p=>p-1)}>Previous</button>
              {Array.from({length: totalPages}).slice(0,5).map((_,i)=>(
                <button key={i} className={"btn sm"+(page===i+1?' primary':'')} onClick={()=>setPage(i+1)}>{i+1}</button>
              ))}
              <button className="btn sm" disabled={page>=totalPages} onClick={()=>setPage(p=>p+1)}>Next</button>
            </div>
          </div>
        </div>

        <div className="stack">
          <div className="card">
            <div className="card-head">
              <div className="card-title">Recent Updates</div>
              <span className="chip">Live</span>
            </div>
            <div className="card-body activity">
              {USERS.map((u,i) => {
                const action = RECENT_ACTIONS[i % RECENT_ACTIONS.length];
                const minutesAgo = RECENT_TIME_OFFSETS[i % RECENT_TIME_OFFSETS.length];
                return (
                  <div className="act-item" key={u.id}
                       onClick={()=>window.toast(action+' — '+u.name)}>
                    <div className="act-av" style={{background:u.color}}>{u.name.trim()[0]}</div>
                    <div style={{flex:1,minWidth:0}}>
                      <div className="act-name thai">{u.name}</div>
                      <div className="act-meta">{action}</div>
                      <div className="act-meta" style={{marginTop:4,opacity:.8}}>{relativeTimeLabel(minutesAgo)}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <div className="card-title">Cash Health</div>
              <span className="chip green"><I.Spark size={11}/> Stable</span>
            </div>
            <div className="card-body">
              {(() => {
                // Calculations
                const target            = parseFloat(localStorage.getItem('finx_monthly_target')) || 500000;
                const salesTargetPct    = Math.min(100, (SUMMARY.totalSales/target)*100);
                const expenseRatioPct   = (SUMMARY.totalExpense/SUMMARY.totalSales)*100;
                const netCashFlow       = SUMMARY.totalSales - SUMMARY.totalExpense - SUMMARY.totalInterest;
                const cashFlowRatioPct  = (netCashFlow/SUMMARY.totalSales)*100;

                return (
                  <>
                    <div className="row between" style={{marginBottom:10}}>
                      <span className="muted" style={{fontSize:12}}>Working capital</span>
                      <span className="mono" style={{fontWeight:700}}>{fmt(SUMMARY.cashBalance)} THB</span>
                    </div>
                    <HealthMeter
                      label="Sales target"
                      pct={salesTargetPct}
                      color="#1f2a8e"
                      editable={true}
                      onOpen={() => openSalesTargetModal({
                        totalSales: SUMMARY.totalSales,
                        currentTarget: target,
                        onSave: (newTarget) => {
                          localStorage.setItem('finx_monthly_target', String(newTarget));
                          window.toast('Monthly target updated · '+fmt(newTarget)+' THB', {tone:'success'});
                          setTick(t=>t+1);   // re-render dashboard
                        }
                      })}/>
                    <HealthMeter
                      label="Expense ratio"
                      pct={expenseRatioPct}
                      color="#dc2626"
                      explain={{
                        what:'สัดส่วนค่าใช้จ่ายต่อยอดขาย — ยิ่งต่ำยิ่งดี',
                        formula:'(Total Expense ÷ Total Sales) × 100',
                        values:[
                          ['Total Expense', fmt(SUMMARY.totalExpense)+' THB'],
                          ['Total Sales',   fmt(SUMMARY.totalSales)+' THB'],
                          ['Result', expenseRatioPct.toFixed(1)+'%'],
                        ],
                        good:'< 50% = ดี · 50–70% = ระวัง · > 70% = อันตราย'
                      }}/>
                    <HealthMeter
                      label="Cash Flow Ratio"
                      pct={cashFlowRatioPct}
                      color="#16a34a"
                      explain={{
                        what:'อัตราส่วนกระแสเงินสดสุทธิจากการดำเนินงาน ต่อยอดขายรวม — สะท้อนว่ายอดขาย 100 บาท เหลือเป็นเงินสดเข้าธุรกิจกี่บาท',
                        formula:'(Net Cash Flow ÷ Total Sales) × 100\nNet Cash Flow = Total Sales − Total Expense − Total Interest',
                        values:[
                          ['Total Sales',     fmt(SUMMARY.totalSales)+' THB'],
                          ['Total Expense',   fmt(SUMMARY.totalExpense)+' THB'],
                          ['Total Interest',  fmt(SUMMARY.totalInterest)+' THB'],
                          ['Net Cash Flow',   fmt(netCashFlow)+' THB'],
                          ['Result',          cashFlowRatioPct.toFixed(1)+'%'],
                        ],
                        good:'≥ 20% = ดีมาก · 10–20% = ปกติ · < 10% = ต้องระวัง · < 0% = ขาดทุนเงินสด'
                      }}/>
                  </>
                );
              })()}
            </div>
          </div>
        </div>
      </div>

      <div style={{marginTop:18,display:'flex',justifyContent:'space-between',color:'var(--muted)',fontSize:12}}>
        <span>{clock}</span>
        <span>v 2.4.1 · build a91f</span>
      </div>
    </div>
  );
}

function CashflowDetail({ r }){
  const rows = [
    ['Request No.', r.reqNo],
    ['Date', r.date],
    ['Sales', fmt(r.sales)+' THB'],
    ['Expense', fmt(r.expense)+' THB'],
    ['Interest', fmt(r.interest)+' THB'],
    ['Pay Cheque', fmt(r.payChq)+' THB'],
    ['Pay MNI', fmt(r.payMNI)+' THB'],
    ['Pay JS', fmt(r.payJS)+' THB'],
    ['Total Amount', fmt(r.totalAmount)+' THB'],
    ['Cash Balance', fmt(r.cashBalance)+' THB'],
  ];
  return (
    <div style={{display:'grid',gap:6}}>
      {rows.map(([k,v],i)=>(
        <div key={i} style={{display:'flex',justifyContent:'space-between',padding:'8px 12px',background:i%2?'#f7f8fc':'transparent',borderRadius:6,fontSize:13}}>
          <span style={{color:'var(--muted)'}}>{k}</span>
          <span className="mono" style={{fontWeight:600}}>{v}</span>
        </div>
      ))}
      <div style={{marginTop:6}}><StatusBadge s={r.status}/></div>
    </div>
  );
}

function Meter({ pct, color, label, right }){
  return (
    <div style={{margin:'10px 0'}}>
      <div className="row between" style={{marginBottom:4}}>
        <span style={{fontSize:12,color:'var(--ink-2)',fontWeight:600}}>{label}</span>
        <span className="mono" style={{fontSize:12,fontWeight:700,color}}>{right}</span>
      </div>
      <div style={{height:8,background:'#eef1f8',borderRadius:8,overflow:'hidden'}}>
        <div style={{
          width:pct+'%',height:'100%',
          background:`linear-gradient(90deg, ${color}, ${color}aa)`,
          borderRadius:8,transition:'width .6s ease'
        }}/>
      </div>
    </div>
  );
}

// Specialized modal for Sales Target — has Edit / Save flow on Monthly target only.
function openSalesTargetModal({ totalSales, currentTarget, onSave }){
  window.openModal({
    title: 'Sales target — วิธีคำนวณ',
    size:'md',
    message: <SalesTargetBody totalSales={totalSales} currentTarget={currentTarget} onSave={onSave}/>,
  });
}

function SalesTargetBody({ totalSales, currentTarget, onSave }){
  const [editing, setEditing] = useState(false);
  const [target, setTarget] = useState(currentTarget);
  const [draft, setDraft] = useState(String(currentTarget));

  const pct = Math.min(100, (totalSales/target)*100);

  const startEdit = () => { setDraft(String(target)); setEditing(true); };
  const cancel    = () => { setDraft(String(target)); setEditing(false); };
  const save      = () => {
    const n = parseFloat(String(draft).replace(/,/g,''));
    if (!n || n <= 0){ window.toast('กรุณากรอกเป้าหมายเป็นตัวเลขมากกว่า 0', {tone:'warn'}); return; }
    setTarget(n); setEditing(false);
    onSave && onSave(n);
  };

  return (
    <div style={{display:'flex',flexDirection:'column',gap:12}}>
      <div style={{fontSize:13.5,color:'var(--ink-2)',lineHeight:1.55}}>
        อัตราส่วนยอดขายจริงต่อเป้าหมายของเดือน
      </div>

      <div style={{
        background:'linear-gradient(135deg,#eef0ff,#f0fbfa)',
        border:'1px solid #dde5f7',borderRadius:10,padding:'12px 14px'
      }}>
        <div style={{fontSize:11,color:'var(--muted)',letterSpacing:'.06em',textTransform:'uppercase',marginBottom:6}}>Formula</div>
        <div className="mono" style={{fontSize:14,fontWeight:700,color:'var(--brand)'}}>
          (Total Sales ÷ Target) × 100
        </div>
      </div>

      <div>
        <div style={{fontSize:11,color:'var(--muted)',letterSpacing:'.06em',textTransform:'uppercase',marginBottom:6}}>Values used</div>
        <div style={{display:'flex',flexDirection:'column',gap:4}}>
          <div style={{display:'flex',justifyContent:'space-between',padding:'8px 12px',background:'#f7f8fc',borderRadius:8,fontSize:13}}>
            <span>Total Sales</span>
            <span className="mono">{fmt(totalSales)} THB</span>
          </div>

          {/* Monthly target — editable row */}
          <div style={{
            display:'flex',alignItems:'center',justifyContent:'space-between',
            padding:'8px 12px',
            background: editing ? 'linear-gradient(90deg,#fffbeb,#fff)' : '#f7f8fc',
            border: editing ? '1px solid #fde68a' : '1px solid transparent',
            borderRadius:8,fontSize:13,gap:8,
            transition:'.15s'
          }}>
            <span>Monthly target {editing && <span className="chip amber" style={{marginLeft:6,fontSize:10}}>Editing</span>}</span>
            <div className="row" style={{gap:8}}>
              {editing ? (
                <>
                  <input className="input mono"
                         autoFocus
                         type="text" inputMode="decimal"
                         value={draft}
                         onChange={e=>{
                           const raw = e.target.value.replace(/[^\d.\-]/g,'');
                           const parts = raw.split('.');
                           setDraft(parts.length>1 ? parts[0]+'.'+parts.slice(1).join('').slice(0,2) : raw);
                         }}
                         onKeyDown={e=>{ if (e.key==='Enter') save(); if (e.key==='Escape') cancel(); }}
                         style={{height:32,width:140,textAlign:'right',fontWeight:700,color:'#1f2a8e'}}/>
                  <span className="suffix" style={{fontSize:11,padding:'0 10px'}}>THB</span>
                  <button className="btn sm" onClick={cancel}>Cancel</button>
                  <button className="btn sm success" onClick={save}>
                    <I.Save size={11}/> Save
                  </button>
                </>
              ) : (
                <>
                  <span className="mono" style={{fontWeight:700,color:'#1f2a8e'}}>{fmt(target)} THB</span>
                  <button className="btn sm" onClick={startEdit}>
                    <I.Edit size={11}/> Edit
                  </button>
                </>
              )}
            </div>
          </div>

          <div style={{
            display:'flex',justifyContent:'space-between',
            padding:'8px 12px',
            background:'linear-gradient(90deg,#eef0ff,#fff)',
            borderRadius:8,fontSize:13,fontWeight:700,color:'#1f2a8e'
          }}>
            <span>Result</span>
            <span className="mono">{pct.toFixed(1)}%</span>
          </div>
        </div>
      </div>

      <div style={{
        background:'#fffbeb',border:'1px solid #fde68a',color:'#92400e',
        padding:'10px 12px',borderRadius:8,fontSize:12,lineHeight:1.5
      }}>
        <b>Benchmark · </b>≥ 80% = ดี · 50–80% = พอใช้ · &lt; 50% = ต้องเร่ง
      </div>

      <div style={{display:'flex',justifyContent:'flex-end',marginTop:4}}>
        <button className="btn primary" onClick={window.closeModal} disabled={editing}>Close</button>
      </div>
    </div>
  );
}
function HealthMeter({ label, pct, color, explain, onOpen }){
  const showExplain = () => {
    if (onOpen){ onOpen(); return; }
    window.openModal({
    title: label + ' — วิธีคำนวณ',
    size:'md',
    message: (
      <div style={{display:'flex',flexDirection:'column',gap:12}}>
        <div style={{fontSize:13.5,color:'var(--ink-2)',lineHeight:1.55}}>
          {explain.what}
        </div>
        <div style={{
          background:'linear-gradient(135deg,#eef0ff,#f0fbfa)',
          border:'1px solid #dde5f7',borderRadius:10,padding:'12px 14px'
        }}>
          <div style={{fontSize:11,color:'var(--muted)',letterSpacing:'.06em',textTransform:'uppercase',marginBottom:6}}>Formula</div>
          <div className="mono" style={{fontSize:14,fontWeight:700,color:'var(--brand)',whiteSpace:'pre-line'}}>{explain.formula}</div>
        </div>
        <div>
          <div style={{fontSize:11,color:'var(--muted)',letterSpacing:'.06em',textTransform:'uppercase',marginBottom:6}}>Values used</div>
          <div style={{display:'flex',flexDirection:'column',gap:4}}>
            {explain.values.map(([k,v],i)=>(
              <div key={i} style={{
                display:'flex',justifyContent:'space-between',
                padding:'8px 12px',
                background: i===explain.values.length-1 ? 'linear-gradient(90deg,#eef0ff,#fff)' : '#f7f8fc',
                borderRadius:8,fontSize:13,
                fontWeight: i===explain.values.length-1 ? 700 : 500,
                color: i===explain.values.length-1 ? color : 'var(--ink-2)',
              }}>
                <span>{k}</span>
                <span className="mono">{v}</span>
              </div>
            ))}
          </div>
        </div>
        <div style={{
          background:'#fffbeb',border:'1px solid #fde68a',color:'#92400e',
          padding:'10px 12px',borderRadius:8,fontSize:12,lineHeight:1.5
        }}>
          <b>Benchmark · </b>{explain.good}
        </div>
      </div>
    ),
    actions:[{ label:'Close', kind:'primary' }]
  });
  };

  return (
    <div style={{margin:'10px 0'}}>
      <div className="row between" style={{marginBottom:4}}>
        <span className="row" style={{gap:5,fontSize:12,color:'var(--ink-2)',fontWeight:600}}>
          {label}
          <button onClick={showExplain}
                  title="วิธีคำนวณ"
                  style={{
                    border:0,padding:0,width:16,height:16,borderRadius:50,
                    background:'#eef1f8',color:'#7b87a8',cursor:'pointer',
                    display:'inline-grid',placeItems:'center',
                    fontSize:10,fontWeight:800,fontStyle:'italic',
                    lineHeight:1,fontFamily:'serif'
                  }}>i</button>
        </span>
        <span className="mono" style={{fontSize:12,fontWeight:700,color}}>{pct.toFixed(1)}%</span>
      </div>
      <div style={{height:8,background:'#eef1f8',borderRadius:8,overflow:'hidden'}}>
        <div style={{
          width:Math.min(100,Math.max(0,pct))+'%',height:'100%',
          background:`linear-gradient(90deg, ${color}, ${color}aa)`,
          borderRadius:8,transition:'width .6s ease'
        }}/>
      </div>
    </div>
  );
}

window.DashboardView = DashboardView;
window.Sparkline = Sparkline;
