// ============ P&L Monthly Report (Print-Ready) ============

const PL_EXP_LABELS = {
  rent:'ค่าเช่า', utilities:'ค่าไฟ/น้ำ', labor:'ค่าแรงงาน',
  marketing:'การตลาด', maintenance:'ซ่อมบำรุง', supplies:'อุปกรณ์สิ้นเปลือง', other:'อื่นๆ',
};

function plCalcWaste(db, events) {
  const items = typeof stockBuildItems === 'function' ? stockBuildItems(db) : [];
  return events.reduce((s, e) => {
    const qty = Math.abs(Number(e.qty) || 0);
    if (!qty) return s;
    if (e.menuId) {
      const cost = typeof computeMenuCost === 'function' ? computeMenuCost(db, e.menuId).total : 0;
      return s + qty * cost;
    }
    const si = items.find(x => x.id === e.stockItemId);
    if (!si) return s;
    let cpu = 0;
    if (si.refType === 'ingredient') { const ing = (db.ingredients||[]).find(i=>i.id===si.refId); cpu = Number(ing?.costPerUnit)||0; }
    else if (si.refType === 'package') { const pkg = (db.packages||[]).find(p=>p.id===si.refId); cpu = Number(pkg?.costPerPiece)||0; }
    return s + qty * cpu;
  }, 0);
}

function PLReportPage({ go }) {
  const { fdb:db, settings, THAI_MONTHS, flash } = useData();
  const months = aggregateByMonth(db);
  const [selKey, setSelKey] = React.useState(() => months.length ? months[months.length-1].key : '');

  if (!months.length) return (
    <Empty icon="sales" title="ยังไม่มีข้อมูลยอดขาย" sub="เริ่มบันทึกยอดขายเพื่อสร้างรายงาน"
      action={<Button icon="plus" onClick={()=>go('sales')}>บันทึกยอดขาย</Button>}/>
  );

  const sel = months.find(m => m.key === selKey) || months[months.length-1];
  const oh = overheadTotal(db);
  const actualExp = typeof expenseMonthTotal === 'function' ? expenseMonthTotal(db, sel.key) : 0;
  const effectiveOH = actualExp > 0 ? actualExp : oh;
  const expOverBudget = actualExp > 0 && actualExp > oh;

  const gpStats = typeof recipeGPStats === 'function' ? recipeGPStats(db) : {weightedAvgGPpct:0,count:0};
  const gpPct = gpStats.weightedAvgGPpct > 0 ? gpStats.weightedAvgGPpct : (settings.estGP || 0.65);
  const gpSrc = gpStats.weightedAvgGPpct > 0 ? `weighted avg จากสูตร ${gpStats.count} เมนู` : `estGP ${fmtPct(settings.estGP||0.65,0)}`;

  const rev = sel.total;
  const cogs = rev * (1 - gpPct);
  const grossProfit = rev * gpPct;
  const gpPctActual = rev > 0 ? grossProfit / rev : 0;

  const expEvents = (db.expenseEvents||[]).filter(e => String(e.paidAt||e.createdAt||'').startsWith(sel.key));
  const expByCat = Object.entries(PL_EXP_LABELS).map(([value,label]) => ({
    value, label,
    total: expEvents.filter(e=>e.category===value).reduce((s,e)=>s+(Number(e.amount)||0),0),
  })).filter(x=>x.total>0);

  const wasteEvents = (db.wasteEvents||[]).filter(e => String(e.wastedAt||e.createdAt||'').startsWith(sel.key));
  const wasteValue = plCalcWaste(db, wasteEvents);

  const prodEvents = (db.productionEvents||[]).filter(e => String(e.producedAt||'').startsWith(sel.key));
  const prodCost = prodEvents.reduce((s,e)=>s+(e.totalCost||0),0);

  const totalOpEx = effectiveOH + wasteValue;
  const net = grossProfit - totalOpEx;
  const netMargin = rev > 0 ? net / rev : 0;
  const monthLabel = `${THAI_MONTHS[sel.monthIdx]} ${parseInt(sel.year)+543}`;

  const plLines = [
    {label:'รายได้รวม', value:rev, bold:true, indent:0},
    sel.store>0  && {label:'หน้าร้าน', value:sel.store, indent:1, dim:true},
    sel.line>0   && {label:'LINE MAN / Delivery', value:sel.line, indent:1, dim:true},
    sel.other>0  && {label:'อื่นๆ', value:sel.other, indent:1, dim:true},
    'sep',
    {label:'ต้นทุนสินค้า (COGS)', value:-cogs, indent:0, neg:true},
    'sep',
    {label:'กำไรขั้นต้น', value:grossProfit, bold:true, indent:0, border:true},
    {label:`GP% = ${fmtPct(gpPctActual,1)}`, value:null, indent:0, sub:true},
    'gap',
    {label:'ค่าใช้จ่ายดำเนินงาน', value:null, indent:0, hdr:true},
    ...(actualExp>0
      ? expByCat.map(x=>({label:x.label, value:-x.total, indent:1, neg:true, dim:true}))
      : [{label:'โสหุ้ยคงที่ (งบประมาณ)', value:-oh, indent:1, neg:true, dim:true}]
    ),
    wasteValue>0 && {label:'มูลค่าของเสีย', value:-wasteValue, indent:1, neg:true, dim:true},
    'sep',
    {label:'ค่าใช้จ่ายรวม', value:-totalOpEx, indent:0, neg:true, bold:true},
    'sep',
    {label:'กำไรสุทธิ', value:net, bold:true, indent:0, border:true, lg:true, green:net>=0, rneg:net<0},
    {label:`Net Margin = ${fmtPct(netMargin,1)}`, value:null, indent:0, sub:true},
  ].filter(Boolean);

  const histMonths = months.slice(-6);

  const exportCSV = () => {
    const header = ['เดือน','รายได้','COGS','กำไรขั้นต้น','GP%','ค่าใช้จ่าย','ของเสีย','กำไรสุทธิ','Net%'];
    const rows = months.map(m => {
      const ae = typeof expenseMonthTotal==='function' ? expenseMonthTotal(db,m.key) : 0;
      const eff = ae>0 ? ae : oh;
      const gp = m.total*gpPct;
      const wev = (db.wasteEvents||[]).filter(e=>String(e.wastedAt||e.createdAt||'').startsWith(m.key));
      const wv = plCalcWaste(db,wev);
      const nt = gp-eff-wv;
      return [
        `${THAI_MONTHS[m.monthIdx]} ${parseInt(m.year)+543}`,
        m.total.toFixed(0),(m.total-gp).toFixed(0),gp.toFixed(0),(gpPct*100).toFixed(1)+'%',
        eff.toFixed(0),wv.toFixed(0),nt.toFixed(0),(m.total>0?(nt/m.total*100).toFixed(1):0)+'%',
      ];
    });
    const csv = '﻿'+[header,...rows].map(r=>r.map(v=>`"${String(v??'').replace(/"/g,'""')}"`).join(',')).join('\n');
    const a=document.createElement('a');
    a.href=URL.createObjectURL(new Blob([csv],{type:'text/csv;charset=utf-8'}));
    a.download=`pl-${sel.key}.csv`; a.click(); flash('ส่งออก P&L CSV แล้ว');
  };

  return (
    <div className="view-enter">
      {/* Controls */}
      <div className="no-print" style={{display:'flex',gap:10,flexWrap:'wrap',alignItems:'center',marginBottom:18}}>
        <Select value={sel.key} onChange={e=>setSelKey(e.target.value)}
          options={[...months].reverse().map(m=>({value:m.key,label:`${THAI_MONTHS[m.monthIdx]} ${parseInt(m.year)+543}`}))}/>
        <div style={{flex:1}}/>
        <Button variant="secondary" icon="download" onClick={exportCSV}>CSV</Button>
        <Button icon="print" onClick={()=>window.print()}>พิมพ์ / PDF</Button>
      </div>

      <Card className="print-area force-light" pad={36} style={{maxWidth:880,margin:'0 auto'}}>
        {/* Header */}
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',borderBottom:'2px solid var(--ink)',paddingBottom:16,marginBottom:24}}>
          <div style={{display:'flex',alignItems:'center',gap:14}}>
            {settings.logo && <img src={settings.logo} alt="logo" style={{height:50,maxWidth:140,objectFit:'contain'}}/>}
            <div style={{borderLeft:settings.logo?'1px solid var(--line)':'none',paddingLeft:settings.logo?14:0}}>
              <div style={{fontSize:20,fontWeight:700}}>{settings.shopName||'JE BAR'}</div>
              <div style={{fontSize:13,color:'var(--ink-2)'}}>รายงานกำไร-ขาดทุน (P&L) · {monthLabel}</div>
            </div>
          </div>
          <div style={{textAlign:'right',fontSize:12,color:'var(--ink-2)'}}>ออกรายงาน<br/>{fmtDate(new Date().toISOString().slice(0,10))}</div>
        </div>

        {/* Body: Income Statement + KPI */}
        <div className="r-stack" style={{display:'grid',gridTemplateColumns:'1.2fr 1fr',gap:36,marginBottom:28}}>
          {/* Left: P&L */}
          <div>
            <div style={{fontSize:13.5,fontWeight:700,marginBottom:10,paddingBottom:8,borderBottom:'1px solid var(--line-2)',color:'var(--ink-2)',letterSpacing:'.04em',textTransform:'uppercase'}}>งบกำไร-ขาดทุน</div>
            {plLines.map((row,i)=>{
              if(row==='sep') return <div key={i} style={{height:1,background:'var(--line-2)',margin:'5px 0'}}/>;
              if(row==='gap') return <div key={i} style={{height:10}}/>;
              return <div key={i} style={{
                display:'flex',justifyContent:'space-between',alignItems:'center',
                padding:`${row.border?'9px 0 6px':row.hdr?'10px 0 4px':'4px 0'}`,
                paddingLeft:row.indent*18,
                borderTop:row.border?'2px solid var(--ink)':undefined,
              }}>
                <span style={{fontSize:row.lg?15:row.hdr?11:13.5,fontWeight:row.bold?700:row.hdr?600:400,
                  color:row.hdr?'var(--ink-2)':row.dim?'var(--ink-2)':'var(--ink)',
                  fontStyle:row.sub?'italic':undefined,
                  textTransform:row.hdr?'uppercase':undefined,letterSpacing:row.hdr?'.05em':undefined}}>
                  {row.label}
                </span>
                {row.value!=null && <span className="tnum" style={{fontSize:row.lg?16:13.5,fontWeight:row.bold?700:500,
                  color:row.green?'var(--green)':row.rneg?'var(--red)':row.value<0?'var(--red)':'var(--ink)'}}>
                  {row.value>=0?'':'-'}{fmtB(Math.abs(row.value))}
                </span>}
              </div>;
            })}
          </div>

          {/* Right: KPI + Expense chart */}
          <div>
            <div style={{fontSize:13.5,fontWeight:700,marginBottom:10,paddingBottom:8,borderBottom:'1px solid var(--line-2)',color:'var(--ink-2)',letterSpacing:'.04em',textTransform:'uppercase'}}>ตัวชี้วัดหลัก</div>
            {[
              {label:'รายได้รวม',     val:fmtB(rev),       tone:'var(--ink)'},
              {label:'กำไรขั้นต้น',   val:`${fmtB(grossProfit)} (${fmtPct(gpPctActual,1)})`, tone:'var(--accent)'},
              {label:'ค่าใช้จ่ายรวม', val:fmtB(totalOpEx), tone:'var(--orange)'},
              {label:'กำไรสุทธิ',     val:`${fmtB(net)} (${fmtPct(netMargin,1)})`,           tone:net>=0?'var(--green)':'var(--red)'},
              {label:'บันทึก',        val:`${sel.days} วัน`,    tone:'var(--ink-2)'},
              {label:'เฉลี่ย/วัน',    val:sel.days>0?fmtB(rev/sel.days,0):'—', tone:'var(--ink-2)'},
            ].map((k,i)=>(
              <div key={i} style={{display:'flex',justifyContent:'space-between',padding:'6px 10px',
                background:i%2===0?'var(--surface-2)':'transparent',borderRadius:6,marginBottom:2}}>
                <span style={{fontSize:12.5,color:'var(--ink-2)'}}>{k.label}</span>
                <span className="tnum" style={{fontSize:13,fontWeight:700,color:k.tone}}>{k.val}</span>
              </div>
            ))}

            {expByCat.length>0 && <div style={{marginTop:16}}>
              <div style={{fontSize:12,fontWeight:600,color:'var(--ink-2)',marginBottom:8,textTransform:'uppercase',letterSpacing:'.04em'}}>สัดส่วนค่าใช้จ่าย</div>
              {expByCat.map(x=>(
                <div key={x.value} style={{marginBottom:7}}>
                  <div style={{display:'flex',justifyContent:'space-between',fontSize:12,marginBottom:2}}>
                    <span style={{color:'var(--ink-2)'}}>{x.label}</span>
                    <span className="tnum" style={{fontWeight:600}}>{fmtB(x.total)}</span>
                  </div>
                  <div style={{height:5,background:'var(--chip)',borderRadius:3}}>
                    <div style={{height:'100%',width:`${effectiveOH>0?Math.min(100,x.total/effectiveOH*100):0}%`,
                      background:'var(--accent)',borderRadius:3,transition:'width .6s'}}/>
                  </div>
                </div>
              ))}
            </div>}

            {expOverBudget && <div style={{marginTop:12,padding:'8px 10px',background:'var(--red-soft)',borderRadius:8,fontSize:12,color:'var(--red)',fontWeight:600}}>
              ⚠️ ค่าใช้จ่ายเกินงบ {fmtB(actualExp-oh)}<br/>
              <span style={{fontWeight:400}}>จริง {fmtB(actualExp)} · งบ {fmtB(oh)}</span>
            </div>}

            {prodCost>0 && <div style={{marginTop:12,padding:'8px 10px',background:'var(--accent-soft)',borderRadius:8,fontSize:12,color:'var(--accent)'}}>
              <b>ต้นทุนการผลิต</b> {fmtB(prodCost)} ({prodEvents.length} รอบ)
              <div style={{fontSize:11,color:'var(--ink-2)',marginTop:2}}>ต้นทุนนี้รวมอยู่ใน COGS แล้ว ไม่นับซ้ำใน OpEx</div>
            </div>}
          </div>
        </div>

        {/* 6-month trend table */}
        <div style={{borderTop:'1px solid var(--line-2)',paddingTop:18}}>
          <div style={{fontSize:13.5,fontWeight:700,marginBottom:12,color:'var(--ink-2)',textTransform:'uppercase',letterSpacing:'.04em'}}>แนวโน้ม 6 เดือน</div>
          <table style={{width:'100%',borderCollapse:'collapse',fontSize:12.5}}>
            <thead><tr style={{borderBottom:'1.5px solid var(--ink)',color:'var(--ink-2)'}}>
              {['เดือน','รายได้','GP%','ค่าใช้จ่าย','ของเสีย','กำไรสุทธิ','Net %'].map(h=>
                <th key={h} style={{textAlign:h==='เดือน'?'left':'right',padding:'7px 6px',fontWeight:600}}>{h}</th>)}
            </tr></thead>
            <tbody>{histMonths.map((m,i)=>{
              const ae=typeof expenseMonthTotal==='function'?expenseMonthTotal(db,m.key):0;
              const eff=ae>0?ae:oh;
              const gp=m.total*gpPct;
              const wev=(db.wasteEvents||[]).filter(e=>String(e.wastedAt||e.createdAt||'').startsWith(m.key));
              const wv=plCalcWaste(db,wev);
              const nt=gp-eff-wv;
              const nm=m.total>0?nt/m.total:0;
              const isSel=m.key===sel.key;
              return <tr key={m.key} onClick={()=>setSelKey(m.key)} style={{
                borderBottom:'1px solid var(--line-2)',cursor:'pointer',
                background:isSel?'var(--accent-soft)':i%2===1?'var(--surface-2)':'transparent',
              }}>
                <td style={{padding:'7px 6px',fontWeight:isSel?700:500}}>{THAI_MONTHS[m.monthIdx]} {parseInt(m.year)+543}{isSel&&' ◀'}</td>
                <td className="tnum" style={{textAlign:'right',padding:'7px 6px',fontWeight:700}}>{fmtB(m.total,0)}</td>
                <td className="tnum" style={{textAlign:'right',padding:'7px 6px',color:'var(--accent)'}}>{fmtPct(gpPct,0)}</td>
                <td className="tnum" style={{textAlign:'right',padding:'7px 6px',color:'var(--orange)'}}>{fmtB(eff,0)}</td>
                <td className="tnum" style={{textAlign:'right',padding:'7px 6px',color:'var(--red)',opacity:wv>0?1:.3}}>{wv>0?fmtB(wv,0):'—'}</td>
                <td className="tnum" style={{textAlign:'right',padding:'7px 6px',fontWeight:700,color:nt>=0?'var(--green)':'var(--red)'}}>{fmtB(nt,0)}</td>
                <td className="tnum" style={{textAlign:'right',padding:'7px 6px',color:nm>=0.1?'var(--green)':nm>=0?'var(--orange)':'var(--red)'}}>{fmtPct(nm,0)}</td>
              </tr>;
            })}</tbody>
          </table>
        </div>

        <p style={{fontSize:11,color:'var(--ink-3)',marginTop:18,borderTop:'1px solid var(--line-2)',paddingTop:10}}>
          หมายเหตุ: GP คิดจาก{gpSrc} · ค่าใช้จ่าย{actualExp>0?`จริงตาม ${expByCat.length} หมวดที่บันทึก`:`งบประมาณ ${fmtB(oh)}/เดือน`}{wasteValue>0?` · ของเสีย ${fmtB(wasteValue,0)}`:''} · ระบบ JEBAR Operate
        </p>
      </Card>
    </div>
  );
}

Object.assign(window, { PLReportPage });
