const {useState,useEffect,useRef,useCallback,useId}=React;

/* Live view of a store key: re-renders whenever ANY device changes it (no more stale lists).
   Returns [value, refresh]; S.set() already updated the store, refresh() just repaints. */
const useStoreState=(key,def=[])=>{
  const[,tick]=useState(0);
  useEffect(()=>S.subscribe(key,()=>tick(x=>x+1)),[key]);
  return[S.get(key,def)||def,()=>tick(x=>x+1)];
};
/* ── Role helper: the two owner profiles are flagged protected:true in the database ── */
const isProtectedSuperAdmin = u => !!u && u.protected===true;

/* ══════════════════════════════════════════════════════════
   🧾  PDF INVOICE GENERATOR
   Draws a full professional tax invoice directly with jsPDF's
   vector API (no HTML capture, no external images) — so it
   always includes the header, logo, totals and terms, and
   never depends on any network resource.
   ══════════════════════════════════════════════════════════ */
const ARCTIC_MARK_PNG='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADqCAYAAADnPAqjAABBa0lEQVR42u29eZhkVZXu/a69zxCRmTVQQCkCAooMVYgllIKiVhXdDi3aOGXKJGIr8NjXvvb9+nbf29fujkxte7oO1w8/fcCrgoJCpmKrjQ3amlUN4gSIQBVQDDIVUxUUVZUZEWfYe31/nIjIGM4UcSIyIzNjP09SSWbkiRPn7N9511p77bWAwRiMwRiMwRiMwRiMwRiMwRiMwVhmg2lykmWhUBDMTIXCtMHMNLgug7GsR6HAolCYNqJ+H0DDYnClFm4Yg0uwEGoBsX07eGKCNAB9eeG2oZKPs8D4CANDUsiverOlH4yN0fMAwMw0NQUxOgZNIB5cw/kbAxmfR7UAtoqJiS1+9Wef+5tfrRdsnA/w+y0z9zJmDTBDCgOuM/sUCN8h8Df+7B9Ou61eVergGowBIEtKLRCohTyLoS8C+M05e8j03BI831UABTeENQxhyJw1BMctAkTboPkq1/G//xeff/1AVQaALHa1KAhgc5Na/Ha9YJwP6Pebpv0ygFF2ZkEMH4AAQQTTnAHmgACQArFhW0MQwoDjFJ+C4O8QqEFVAj9msx6oygCQRaUWhcJ07iBv5VlE4k90RS1ctwjPdxQACCJRvQf1cDT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67nbZuhh4kDQ7GYNSZYs2qMhiDMRiDMRiDMRiDMRiDscTG/w8QZuWtJqHpDgAAAABJRU5ErkJggg==';
const ARCTIC_LOGO_URI="data:image/svg+xml;utf8,%3Csvg width=%22640%22 height=%22160%22 viewBox=%220 0 640 160%22 xmlns=%22http://www.w3.org/2000/svg%22%3E%3Cdefs%3E%3ClinearGradient id=%22iconGrad%22 x1=%220%22 y1=%220%22 x2=%22512%22 y2=%22512%22 gradientUnits=%22userSpaceOnUse%22%3E%3Cstop offset=%220%25%22 stop-color=%22%234F6FE8%22/%3E%3Cstop offset=%22100%25%22 stop-color=%22%23F1495C%22/%3E%3C/linearGradient%3E%3ClinearGradient id=%22iconShine%22 x1=%220%22 y1=%220%22 x2=%221%22 y2=%221%22%3E%3Cstop offset=%220%25%22 stop-color=%22rgba(255,255,255,0.18)%22/%3E%3Cstop offset=%22100%25%22 stop-color=%22rgba(255,255,255,0)%22/%3E%3C/linearGradient%3E%3ClinearGradient id=%22textGrad%22 x1=%220%25%22 y1=%220%25%22 x2=%22100%25%22 y2=%220%25%22%3E%3Cstop offset=%220%25%22 stop-color=%22%234F6FE8%22/%3E%3Cstop offset=%22100%25%22 stop-color=%22%23F1495C%22/%3E%3C/linearGradient%3E%3C/defs%3E%3C%21-- Shield mark --%3E%3Cg transform=%22translate(18,18) scale(0.2344)%22%3E%3Cpath d=%22M256 36 L72 110 V262 C72 368 160 456 256 480 C352 456 440 368 440 262 V110 Z%22 fill=%22url(%23iconGrad)%22/%3E%3Cpath d=%22M256 36 L72 110 V262 C72 368 160 456 256 480 C352 456 440 368 440 262 V110 Z%22 fill=%22url(%23iconShine)%22/%3E%3Crect x=%22174%22 y=%22168%22 width=%22164%22 height=%2223%22 rx=%2211.5%22 fill=%22%23FFFFFF%22 fill-opacity=%220.95%22/%3E%3Crect x=%22174%22 y=%22212%22 width=%22128%22 height=%2223%22 rx=%2211.5%22 fill=%22%23FFFFFF%22 fill-opacity=%220.75%22/%3E%3Crect x=%22174%22 y=%22256%22 width=%22146%22 height=%2223%22 rx=%2211.5%22 fill=%22%23FFFFFF%22 fill-opacity=%220.75%22/%3E%3Cpath d=%22M256 316 L270 338 L295 330 L282 352 L298 372 L273 370 L256 392 L239 370 L214 372 L230 352 L217 330 L242 338 Z%22 fill=%22%23FCD34D%22 fill-opacity=%220.97%22/%3E%3C/g%3E%3C%21-- Wordmark --%3E%3Ctext x=%22180%22 y=%2288%22 font-family=%22'Sora','Poppins','Segoe UI',Arial,sans-serif%22 font-weight=%22800%22 font-size=%2254%22 letter-spacing=%22-1%22 fill=%22url(%23textGrad)%22%3EArctic Books%3C/text%3E%3Ctext x=%22181%22 y=%22112%22 font-family=%22'DM Sans','Segoe UI',Arial,sans-serif%22 font-weight=%22600%22 font-size=%2213%22 letter-spacing=%221.8%22 fill=%22%238A8AA3%22%3ECOMPLETE ACCOUNTING SOFTWARE%3C/text%3E%3C/svg%3E%0A";
const drawGymLogo = (doc,x,y,size,settings)=>{
  if(settings&&settings.logo){
    try{
      const w=settings.logoW||1, h=settings.logoH||1;
      const ratio=w/h;
      let dw=size, dh=size;
      if(ratio>1){dh=size/ratio;} else if(ratio<1){dw=size*ratio;}
      const dx=x+(size-dw)/2, dy=y+(size-dh)/2;
      doc.addImage(settings.logo,'PNG',dx,dy,dw,dh);
      return;
    }catch(e){
      console.warn('Custom logo failed to render in PDF, using default mark:',e.message);
    }
  }
  // Default: the Arctic Books shield mark (pre-rendered PNG so jsPDF can embed it
  // synchronously, keeping the brand gradient).
  try{
    const mh=size, mw=size*200/234;
    doc.addImage(ARCTIC_MARK_PNG,'PNG',x+(size-mw)/2,y,mw,mh);
  }catch(e){
    console.warn('Arctic mark failed to render in PDF:',e.message);
  }
};

const downloadInvoicePDF = (inv,settings)=>{
  if(!window.jspdf){toast.error('PDF library failed to load. Check your internet connection and reload.');return;}
  const{jsPDF}=window.jspdf;
  const doc=new jsPDF({unit:'mm',format:'a4'});
  const pageW=210, marginX=18;
  let y=20;

  // ── Header: logo + business info (left), TAX INVOICE + no/date (right) ──
  drawGymLogo(doc,marginX,y-4,16,settings);
  const textX=marginX+22;
  doc.setFont('helvetica','bold');doc.setFontSize(15);doc.setTextColor(18,23,46);
  doc.text(settings.name||'Arctic Gym Management',textX,y+2);
  doc.setFont('helvetica','normal');doc.setFontSize(9);doc.setTextColor(110,118,129);
  let addrY=y+7;
  if(settings.address){
    const addrLines=doc.splitTextToSize(settings.address,95);
    doc.text(addrLines,textX,addrY);
    addrY+=addrLines.length*4;
  }
  if(settings.gstin){doc.text(`GSTIN: ${settings.gstin}`,textX,addrY);addrY+=4;}
  if(settings.phone){doc.text(settings.phone,textX,addrY);addrY+=4;}

  doc.setFont('helvetica','bold');doc.setFontSize(16);doc.setTextColor(67,56,202);
  doc.text(inv.gstEnabled?'TAX INVOICE':'INVOICE',pageW-marginX,y,{align:'right'});
  doc.setFont('helvetica','normal');doc.setFontSize(9);doc.setTextColor(110,118,129);
  doc.text('No.',pageW-marginX,y+6,{align:'right'});
  doc.setFont('helvetica','bold');doc.setTextColor(18,23,46);
  doc.text(inv.number,pageW-marginX,y+11,{align:'right'});
  doc.setFont('helvetica','normal');doc.setTextColor(110,118,129);
  doc.text(`Date: ${fmtD(inv.date)}`,pageW-marginX,y+16,{align:'right'});

  y=Math.max(addrY,y+16)+6;
  doc.setDrawColor(231,234,243);doc.setLineWidth(0.4);
  doc.line(marginX,y,pageW-marginX,y);
  y+=9;

  // ── Billed to (left) / Membership period (right) ──
  doc.setFont('helvetica','normal');doc.setFontSize(9);doc.setTextColor(110,118,129);
  doc.text('Billed to',marginX,y);
  doc.text('Membership period',pageW-marginX,y,{align:'right'});
  y+=6;
  doc.setFont('helvetica','bold');doc.setFontSize(12);doc.setTextColor(18,23,46);
  doc.text(inv.memberName||'—',marginX,y);
  doc.setFont('helvetica','normal');doc.setFontSize(10);
  doc.text(`${fmtD(inv.startDate)} -> ${fmtD(inv.expiryDate)}`,pageW-marginX,y,{align:'right'});
  y+=5.5;
  doc.setFontSize(9);doc.setTextColor(110,118,129);
  if(inv.memberPhone){doc.text(inv.memberPhone,marginX,y);y+=5;}
  if(inv.memberEmail){doc.text(inv.memberEmail,marginX,y);y+=5;}
  y+=6;

  // ── Line items table ──
  const showHsn=!!inv.gstEnabled;
  const col1X=marginX, col2X=pageW-marginX-38, col3X=pageW-marginX;
  doc.setFillColor(244,246,251);
  doc.rect(marginX,y-5.5,pageW-2*marginX,8,'F');
  doc.setFont('helvetica','bold');doc.setFontSize(9);doc.setTextColor(110,118,129);
  doc.text('DESCRIPTION',col1X+2,y);
  if(showHsn)doc.text('HSN',col2X,y,{align:'center'});
  doc.text('AMOUNT',col3X,y,{align:'right'});
  y+=8;
  doc.setFont('helvetica','normal');doc.setFontSize(10.5);doc.setTextColor(18,23,46);
  (inv.lineItems||[]).forEach(li=>{
    doc.text(li.name,col1X+2,y);
    if(showHsn){doc.setFontSize(9);doc.setTextColor(110,118,129);doc.text(String(li.hsn||''),col2X,y,{align:'center'});doc.setFontSize(10.5);doc.setTextColor(18,23,46);}
    doc.text(fmtPdf(li.amount),col3X,y,{align:'right'});
    y+=7.5;
    doc.setDrawColor(231,234,243);doc.setLineWidth(0.2);
    doc.line(marginX,y-4.5,pageW-marginX,y-4.5);
  });
  y+=4;

  // ── Totals ──
  const totalsX=pageW-marginX-55;
  doc.setFont('helvetica','normal');doc.setFontSize(10);doc.setTextColor(110,118,129);
  doc.text('Subtotal',totalsX,y);
  doc.text(fmtPdf(inv.subtotal),pageW-marginX,y,{align:'right'});
  y+=6;
  if(inv.discountAmount>0){
    doc.text(`Discount (${inv.discountPercent}%)`,totalsX,y);
    doc.text('-'+fmtPdf(inv.discountAmount),pageW-marginX,y,{align:'right'});
    y+=6;
  }
  if(inv.gstEnabled){
    doc.text(`GST (${inv.gstRate||18}%)`,totalsX,y);
    doc.text(fmtPdf(inv.gstAmount),pageW-marginX,y,{align:'right'});
    y+=6;
  }
  doc.setDrawColor(18,23,46);doc.setLineWidth(0.5);
  doc.line(totalsX,y-3.5,pageW-marginX,y-3.5);
  y+=2;
  doc.setFont('helvetica','bold');doc.setFontSize(13);doc.setTextColor(18,23,46);
  doc.text('Total',totalsX,y+4);
  doc.text(fmtPdf(inv.total),pageW-marginX,y+4,{align:'right'});
  y+=14;

  // ── Payment mode / UPI ──
  doc.setDrawColor(231,234,243);doc.setLineWidth(0.4);
  doc.line(marginX,y,pageW-marginX,y);
  y+=7;
  doc.setFont('helvetica','bold');doc.setFontSize(9.5);doc.setTextColor(18,23,46);
  doc.text('Payment mode',marginX,y);
  if(settings.upiId){doc.text(`UPI: ${settings.upiId}`,pageW-marginX,y,{align:'right'});}
  y+=5.5;
  doc.setFont('helvetica','normal');doc.setTextColor(110,118,129);
  doc.text(inv.paymentMode||'—',marginX,y);
  if(inv.paymentRef){y+=5;doc.text(`Reference No: ${inv.paymentRef}`,marginX,y);}
  y+=10;

  // ── Terms & Conditions ──
  doc.setDrawColor(231,234,243);
  doc.line(marginX,y,pageW-marginX,y);
  y+=8;
  doc.setFont('helvetica','bold');doc.setFontSize(10.5);doc.setTextColor(18,23,46);
  doc.text('Terms & Conditions',marginX,y);
  y+=6.5;
  doc.setFont('helvetica','normal');doc.setFontSize(8.5);doc.setTextColor(110,118,129);
  const defaultTerms=[
    'Payment must be made by the due date mentioned on the invoice. Late payments may result in suspension of gym access.',
    'Membership fees are non-refundable and non-transferable once the membership has commenced.',
    'Memberships are strictly personal and cannot be shared or transferred to another person.',
    'Members are responsible for ensuring they are physically fit to exercise and must follow all gym safety rules and staff instructions.',
    'The gym is not responsible for any loss, theft, or damage to members\' personal belongings.'
  ];
  const termsList=settings.terms&&settings.terms.trim()
    ? settings.terms.split(/\n+/).map(t=>t.trim()).filter(Boolean)
    : defaultTerms;
  termsList.forEach((t,i)=>{
    if(y>275){doc.addPage();y=20;}
    const lines=doc.splitTextToSize(`${i+1}. ${t}`,pageW-2*marginX);
    doc.text(lines,marginX,y);
    y+=lines.length*4.2+2.5;
  });

  doc.save(inv.number+'.pdf');
};

/* ══════════════════════════════════════════════════════════
   📊  GSTR-1 EXCEL EXPORT
   Builds a 3-sheet workbook (Invoice register, HSN summary,
   B2CS rate-wise summary) covering a date range — a ready
   reference for filing GSTR-1, not a certified filing tool.
   Assumes intra-state supply (CGST+SGST split), since gym
   membership services are consumed at the gym's own location.
   ══════════════════════════════════════════════════════════ */
/* ══════════════════════════════════════════════════════════
   💬  WHATSAPP SEND
   Opens a WhatsApp chat with the invoice's customer, pre-filled
   with a summary message. WhatsApp's click-to-chat link can't
   attach a file, so this also triggers the PDF download and
   tells the person to attach it themselves in the chat.
   ══════════════════════════════════════════════════════════ */
/* ══════════════════════════════════════════════════════════
   📊  GOOGLE SHEET SYNC (for automated renewal-reminder emails)
   Fire-and-forget POST to a Google Apps Script Web App URL,
   configured in Gym Settings. Uses mode:'no-cors' + text/plain
   because Apps Script Web Apps don't handle CORS preflight —
   this is the standard pattern for posting to Apps Script from
   a plain static page. We can't read the response in this mode,
   so failures here never block or interrupt invoice generation.
   ══════════════════════════════════════════════════════════ */
const syncToGoogleSheet = (payload,settings)=>{
  const url=(settings.sheetWebhookUrl||'').trim();
  if(!url)return;
  try{
    fetch(url,{
      method:'POST',
      mode:'no-cors',
      headers:{'Content-Type':'text/plain;charset=utf-8'},
      body:JSON.stringify({...payload,secret:(settings.sheetWebhookSecret||'').trim()})
    }).catch(e=>console.warn('Google Sheet sync failed (network):',e.message));
  }catch(e){ console.warn('Google Sheet sync failed:',e.message); }
};

/* ══════════════════════════════════════════════════════════
   📧  MANUAL EMAIL REMINDER (mailto: — zero setup required)
   Opens the person's own email client pre-filled with a renewal
   reminder for one member. Works immediately with no backend,
   as an instant fallback alongside the Google Sheet automation.
   ══════════════════════════════════════════════════════════ */
const mailtoRenewalReminder = (member,settings)=>{
  if(!member.email){toast.error(`${member.name} has no email address saved.`);return;}
  const gymName=settings.name||'Arctic Gym Management';
  const subject=`Your membership at ${gymName} is expiring soon`;
  const body=`Hi ${member.name},\n\nJust a friendly reminder that your ${member.planName||''} membership at ${gymName} `+
    `is expiring on ${fmtD(member.expiryDate)}. Please renew soon to keep your access active without interruption.\n\n`+
    `If you have any questions, just reply to this email.\n\nThank you,\n${gymName}`;
  window.location.href=`mailto:${member.email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
};


const sendInvoiceWhatsApp = (inv,settings)=>{
  const digits=(inv.memberPhone||'').replace(/\D/g,'');
  if(!digits){toast.error(`${inv.memberName||'This member'} has no phone number saved — add one on their profile first.`);return;}
  const cc=(settings.whatsappCountryCode||'91').replace(/\D/g,'')||'91';
  const fullNumber=digits.length>10?digits:cc+digits;
  const gymName=settings.name||'Arctic Gym Management';
  const message=`Hi ${inv.memberName}, here's your invoice ${inv.number} for ${fmt(inv.total)} from ${gymName}. `+
    `Membership valid ${fmtD(inv.startDate)} to ${fmtD(inv.expiryDate)}. Thank you!`;
  try{ downloadInvoicePDF(inv,settings); }
  catch(e){ console.warn('PDF pre-download for WhatsApp failed:',e.message); }
  window.open(`https://wa.me/${fullNumber}?text=${encodeURIComponent(message)}`,'_blank');
  toast.success('PDF downloaded — attach it in the WhatsApp chat that just opened.');
};


/* ══════════════════════════════════════════════════════════
   💳  PAYMENT REFERENCE
   UPI / Card / Bank Transfer / Cheque payments must carry a
   reference number (UTR, approval code, cheque no.) so every
   rupee in the books can be matched to the bank statement.
   ══════════════════════════════════════════════════════════ */
window.PAYMENT_REF_MODES=null; const PAYMENT_REF_MODES={
  'UPI':{label:'UPI Transaction ID / UTR *',ph:'e.g. 412345678901',short:'UPI transaction ID'},
  'Card':{label:'Card Transaction / Approval Code *',ph:'Approval code or transaction ID (never the full card number)',short:'card approval code'},
  'Bank Transfer':{label:'Bank Reference / UTR No. *',ph:'e.g. SBIN52026101200123',short:'bank reference / UTR'},
  'Cheque':{label:'Cheque Number *',ph:'e.g. 004512',short:'cheque number'},
};
const needsPaymentRef=mode=>Object.prototype.hasOwnProperty.call(PAYMENT_REF_MODES,mode);

/* ══════════════════════════════════════════════════════════
   📊  REPORTS — shared helpers (period presets, Excel sheets)
   ══════════════════════════════════════════════════════════ */
const ymd=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
/* Returns [from,to] as YYYY-MM-DD. Financial year = 1 Apr → 31 Mar (India). */
const periodPreset=key=>{
  const n=new Date(),y=n.getFullYear(),m=n.getMonth();
  const fy=m>=3?y:y-1;
  switch(key){
    case 'thisMonth':return[ymd(new Date(y,m,1)),ymd(new Date(y,m+1,0))];
    case 'lastMonth':return[ymd(new Date(y,m-1,1)),ymd(new Date(y,m,0))];
    case 'thisQuarter':{const q=Math.floor(m/3)*3;return[ymd(new Date(y,q,1)),ymd(new Date(y,q+3,0))];}
    case 'thisFY':return[ymd(new Date(fy,3,1)),ymd(new Date(fy+1,2,31))];
    case 'lastFY':return[ymd(new Date(fy-1,3,1)),ymd(new Date(fy,2,31))];
    case 'all':return['',''];
    default:return null;
  }
};
const inPeriod=(d,from,to)=>!!d&&(!from||d>=from)&&(!to||d<=to);
const invTax=i=>{
  const taxable=round2((i.subtotal||0)-(i.discountAmount||0));
  const gst=i.gstEnabled?round2(i.gstAmount||0):0;
  const cgst=round2(gst/2);
  return{taxable,gst,cgst,sgst:round2(gst-cgst)};
};
/* Sheet with auto-fitted column widths. `headers` fixes column order even when there are no rows. */
const makeSheet=(rows,headers)=>{
  const ws=rows.length?XLSX.utils.json_to_sheet(rows,{header:headers}):XLSX.utils.aoa_to_sheet([headers]);
  ws['!cols']=headers.map(h=>{
    let w=String(h).length;
    rows.forEach(r=>{const l=String(r[h]??'').length;if(l>w)w=l;});
    return{wch:Math.min(46,w+2)};
  });
  return ws;
};

/* ══════════════════════════════════════════════════════════
   📊  GSTR-1 EXCEL EXPORT
   Workbook: Summary · Invoices (register) · B2CS · HSN Summary ·
   Documents Issued. A ready reference for filing GSTR-1, not a
   certified filing tool. Assumes intra-state supply (CGST+SGST).
   ══════════════════════════════════════════════════════════ */
const exportGstr1=(invoices,settings,fromDate,toDate)=>{
  if(!window.XLSX){toast.error('Excel library failed to load. Check your internet connection and reload.');return false;}
  const filtered=(invoices||[]).filter(i=>inPeriod(i.date,fromDate,toDate))
    .sort((a,b)=>String(a.number).localeCompare(String(b.number)));
  if(filtered.length===0){toast.error('No invoices found in that period.');return false;}

  const stateName=stateFromGstin(settings.gstin);
  const pos=stateName?`${settings.gstin.slice(0,2)}-${stateName}`:'Not set — add GSTIN in Gym Settings';

  // Sheet: Invoices (register)
  const invHeaders=['Invoice No','Date','Customer Name','Phone','Email','Place of Supply','Plan','Gross Amount','Discount Given','Taxable Value','GST Rate (%)','CGST','SGST','IGST','Cess','Invoice Value','Payment Mode','Payment Reference','Raised By'];
  const invoiceRows=filtered.map(i=>{
    const t=invTax(i);
    return{'Invoice No':i.number,'Date':fmtD(i.date),'Customer Name':i.memberName||'','Phone':i.memberPhone||'','Email':i.memberEmail||'',
      'Place of Supply':pos,'Plan':[i.planName,i.ptPlanName&&`PT ${i.ptPlanName}`].filter(Boolean).join(' + '),
      'Gross Amount':round2(i.subtotal||0),'Discount Given':round2(i.discountAmount||0),'Taxable Value':t.taxable,
      'GST Rate (%)':i.gstEnabled?(i.gstRate||18):0,'CGST':t.cgst,'SGST':t.sgst,'IGST':0,'Cess':0,
      'Invoice Value':round2(i.total||0),'Payment Mode':i.paymentMode||'','Payment Reference':i.paymentRef||'','Raised By':i.raisedBy||''};
  });

  // Sheet: B2CS (rate-wise, as the GST portal's offline tool expects)
  const rateMap={};
  filtered.forEach(i=>{
    const rate=i.gstEnabled?(i.gstRate||18):0;
    rateMap[rate]=(rateMap[rate]||0)+invTax(i).taxable;
  });
  const b2csHeaders=['Type','Place Of Supply','Rate','Applicable % of Tax Rate','Taxable Value','Cess Amount','E-Commerce GSTIN'];
  const b2csRows=Object.entries(rateMap).map(([rate,taxable])=>({
    'Type':'OE','Place Of Supply':pos,'Rate':Number(rate),'Applicable % of Tax Rate':'','Taxable Value':round2(taxable),'Cess Amount':0,'E-Commerce GSTIN':''}));

  // Sheet: HSN summary (Table 12), grouped by HSN + rate
  const hsnMap={};
  filtered.forEach(i=>{
    const rate=i.gstEnabled?(i.gstRate||18):0;
    const keep=1-((i.discountPercent||0)/100); // discount reduces taxable value of every line
    (i.lineItems||[]).forEach(li=>{
      const hsn=li.hsn||'999723',k=hsn+'|'+rate;
      if(!hsnMap[k])hsnMap[k]={hsn,rate,qty:0,taxable:0,cgst:0,sgst:0};
      const net=(li.amount||0)*keep;
      const tax=i.gstEnabled?net*rate/100:0;
      hsnMap[k].qty+=1;hsnMap[k].taxable+=net;hsnMap[k].cgst+=tax/2;hsnMap[k].sgst+=tax/2;
    });
  });
  const hsnHeaders=['HSN','Description','UQC','Total Quantity','Total Value','Rate','Taxable Value','Integrated Tax Amount','Central Tax Amount','State/UT Tax Amount','Cess Amount'];
  const hsnRows=Object.values(hsnMap).map(v=>({
    'HSN':v.hsn,'Description':'Fitness / Gym Membership Services','UQC':'NOS-NUMBERS','Total Quantity':v.qty,
    'Total Value':round2(v.taxable+v.cgst+v.sgst),'Rate':v.rate,'Taxable Value':round2(v.taxable),
    'Integrated Tax Amount':0,'Central Tax Amount':round2(v.cgst),'State/UT Tax Amount':round2(v.sgst),'Cess Amount':0}));

  // Sheet: Documents issued (Table 13) — gaps in the numbering = deleted/cancelled invoices
  const series={};
  const allNums={}; // every invoice number ever raised, by series prefix — so a back-dated invoice isn't mistaken for a cancelled one
  (invoices||[]).forEach(i=>{const m=String(i.number||'').match(/^(.*?)(\d+)$/);if(m)(allNums[m[1]]=allNums[m[1]]||new Set()).add(parseInt(m[2],10));});
  filtered.forEach(i=>{
    const m=String(i.number||'').match(/^(.*?)(\d+)$/);
    if(!m)return;
    const p=m[1],n=parseInt(m[2],10);
    if(!series[p])series[p]={min:n,max:n,len:m[2].length};
    const s=series[p];s.min=Math.min(s.min,n);s.max=Math.max(s.max,n);
  });
  const docHeaders=['Nature of Document','Sr. No. From','Sr. No. To','Total Number','Cancelled','Net Issued'];
  const docRows=Object.entries(series).map(([p,s])=>{
    const total=s.max-s.min+1;
    let cancelled=0;
    for(let n=s.min;n<=s.max;n++)if(!allNums[p].has(n))cancelled++;
    return{'Nature of Document':'Invoices for outward supply','Sr. No. From':p+String(s.min).padStart(s.len,'0'),
      'Sr. No. To':p+String(s.max).padStart(s.len,'0'),'Total Number':total,'Cancelled':cancelled,'Net Issued':total-cancelled};
  });

  // Sheet: Summary
  const sum=k=>round2(filtered.reduce((a,i)=>a+(k(i)||0),0));
  const byMode={};
  filtered.forEach(i=>{const m=i.paymentMode||'Other';byMode[m]=round2((byMode[m]||0)+(i.total||0));});
  const summaryAoa=[
    ['GSTR-1 export — reference sheet'],[],
    ['Business',settings.name||''],['GSTIN',settings.gstin||'Not set'],['Place of supply',pos],
    ['Period',`${fromDate?fmtD(fromDate):'Beginning'} to ${toDate?fmtD(toDate):'Today'}`],
    ['Generated on',fmtD(today())],[],
    ['Invoices',filtered.length],['Gross amount',sum(i=>i.subtotal)],['Discounts',sum(i=>i.discountAmount)],
    ['Taxable value',sum(i=>invTax(i).taxable)],['CGST',sum(i=>invTax(i).cgst)],['SGST',sum(i=>invTax(i).sgst)],
    ['Total invoice value',sum(i=>i.total)],[],['Collections by payment mode'],
    ...Object.entries(byMode).map(([m,v])=>[m,v]),
  ];
  const wsSum=XLSX.utils.aoa_to_sheet(summaryAoa);
  wsSum['!cols']=[{wch:28},{wch:36}];

  const wb=XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb,wsSum,'Summary');
  XLSX.utils.book_append_sheet(wb,makeSheet(invoiceRows,invHeaders),'Invoices');
  XLSX.utils.book_append_sheet(wb,makeSheet(b2csRows,b2csHeaders),'B2CS');
  XLSX.utils.book_append_sheet(wb,makeSheet(hsnRows,hsnHeaders),'HSN Summary');
  XLSX.utils.book_append_sheet(wb,makeSheet(docRows,docHeaders),'Documents Issued');
  XLSX.writeFile(wb,`GSTR1_Export_${fromDate||'all'}_to_${toDate||'all'}.xlsx`);
  toast.success(`GSTR-1 Excel exported — ${filtered.length} invoice${filtered.length===1?'':'s'}`);
  return true;
};
/* Kept under the old name so the "Export for GSTR-1" button in Invoice History still works. */
const exportInvoicesToExcel=exportGstr1;

/* ══════════════════════════════════════════════════════════
   👥  MEMBERS DETAILS EXCEL EXPORT
   basis: 'invoiced' = members billed (joined/renewed) in the period
          'start'    = membership start date in the period
          'expiry'   = membership expiry date in the period
          'all'      = every member (period ignored for selection)
   ══════════════════════════════════════════════════════════ */
const selectReportMembers=(members,invoices,from,to,basis)=>{
  const billed=new Set((invoices||[]).filter(i=>inPeriod(i.date,from,to)).map(i=>i.memberId));
  return(members||[]).filter(m=>{
    if(basis==='all')return true;
    if(basis==='start')return inPeriod(m.startDate,from,to);
    if(basis==='expiry')return inPeriod(m.expiryDate,from,to);
    return billed.has(m.id);
  }).sort((a,b)=>(a.name||'').localeCompare(b.name||''));
};
const exportMembersExcel=(members,invoices,settings,from,to,basis)=>{
  if(!window.XLSX){toast.error('Excel library failed to load. Check your internet connection and reload.');return false;}
  const list=selectReportMembers(members,invoices,from,to,basis);
  if(list.length===0){toast.error('No members match that period.');return false;}

  const byMember={};
  (invoices||[]).forEach(i=>{(byMember[i.memberId]=byMember[i.memberId]||[]).push(i);});
  const t0=today();
  const headers=['Member ID','Name','Email','Phone','Address','Status','Current Plan','Trainer','Membership Start','Membership Expiry','Days Left',
    'Frozen Until','Notes','First Invoice Date','Last Invoice No','Last Invoice Date','Last Plan Billed','Last Payment Mode','Last Payment Reference',
    'Invoices (All Time)','Total Paid (All Time)','Invoices (This Period)','Paid (This Period)','Last Invoice Total','Raised By (Last Invoice)'];
  const rows=list.map(m=>{
    const inv=(byMember[m.id]||[]).slice().sort((a,b)=>String(a.date).localeCompare(String(b.date))||String(a.number).localeCompare(String(b.number)));
    const last=inv[inv.length-1],first=inv[0];
    const per=inv.filter(i=>inPeriod(i.date,from,to));
    return{'Member ID':m.id,'Name':m.name||'','Email':m.email||'','Phone':m.phone||'','Address':m.address||'','Status':m.status||'active',
      'Current Plan':m.planName||'','Trainer':m.trainerName||'','Membership Start':fmtD(m.startDate).replace('—',''),'Membership Expiry':fmtD(m.expiryDate).replace('—',''),
      'Days Left':m.expiryDate?daysBetween(t0,m.expiryDate):'','Frozen Until':m.freezeUntil?fmtD(m.freezeUntil):'','Notes':m.note||'',
      'First Invoice Date':first?fmtD(first.date):'','Last Invoice No':last?.number||'','Last Invoice Date':last?fmtD(last.date):'',
      'Last Plan Billed':last?.planName||'','Last Payment Mode':last?.paymentMode||'','Last Payment Reference':last?.paymentRef||'',
      'Invoices (All Time)':inv.length,'Total Paid (All Time)':round2(inv.reduce((a,i)=>a+(i.total||0),0)),
      'Invoices (This Period)':per.length,'Paid (This Period)':round2(per.reduce((a,i)=>a+(i.total||0),0)),
      'Last Invoice Total':last?round2(last.total||0):'','Raised By (Last Invoice)':last?.raisedBy||''};
  });

  // Every invoice in the period for the selected members — the payment trail
  const ids=new Set(list.map(m=>m.id));
  const invHeaders=['Invoice No','Date','Member','Phone','Email','Plan','PT Plan','Start','Expiry','Subtotal','Discount','GST','Total','Payment Mode','Payment Reference','Raised By'];
  const invRows=(invoices||[]).filter(i=>ids.has(i.memberId)&&inPeriod(i.date,from,to))
    .sort((a,b)=>String(a.date).localeCompare(String(b.date))||String(a.number).localeCompare(String(b.number)))
    .map(i=>({'Invoice No':i.number,'Date':fmtD(i.date),'Member':i.memberName||'','Phone':i.memberPhone||'','Email':i.memberEmail||'',
      'Plan':i.planName||'','PT Plan':i.ptPlanName||'','Start':fmtD(i.startDate),'Expiry':fmtD(i.expiryDate),'Subtotal':round2(i.subtotal||0),
      'Discount':round2(i.discountAmount||0),'GST':i.gstEnabled?round2(i.gstAmount||0):0,'Total':round2(i.total||0),
      'Payment Mode':i.paymentMode||'','Payment Reference':i.paymentRef||'','Raised By':i.raisedBy||''}));

  const basisLabel={invoiced:'Billed (joined / renewed) in the period',start:'Membership started in the period',expiry:'Membership expires in the period',all:'All members'}[basis]||basis;
  const count=s=>list.filter(m=>(m.status||'active')===s).length;
  const summaryAoa=[
    ['Members details report'],[],['Business',settings.name||''],
    ['Period',basis==='all'?'All members':`${from?fmtD(from):'Beginning'} to ${to?fmtD(to):'Today'}`],
    ['Members included',basisLabel],['Generated on',fmtD(today())],[],
    ['Members in this report',list.length],['Active',count('active')],['Expired',count('expired')],['Frozen',count('frozen')],
    ['Collected in period (these members)',round2(invRows.reduce((a,r)=>a+r.Total,0))],
  ];
  const wsSum=XLSX.utils.aoa_to_sheet(summaryAoa);wsSum['!cols']=[{wch:36},{wch:40}];

  const wb=XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb,wsSum,'Summary');
  XLSX.utils.book_append_sheet(wb,makeSheet(rows,headers),'Members');
  XLSX.utils.book_append_sheet(wb,makeSheet(invRows,invHeaders),'Member Invoices');
  XLSX.writeFile(wb,`Members_Report_${basis==='all'?'all':(from||'start')+'_to_'+(to||'today')}.xlsx`);
  toast.success(`Members sheet exported — ${list.length} member${list.length===1?'':'s'}`);
  return true;
};

/* ══════════════════════════════════════════════════════════
   🎨  ICONS (SVG line icons)
   ══════════════════════════════════════════════════════════ */
const Ic=({n,s=16})=>{
  const p={stroke:'currentColor',strokeWidth:'1.8',fill:'none',width:s,height:s,viewBox:'0 0 24 24'};
  const icons={
    dashboard:<svg {...p}><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg>,
    users:<svg {...p}><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></svg>,
    dumbbell:<svg {...p}><rect x="1.5" y="10" width="2.5" height="4" rx="1"/><rect x="4.5" y="8" width="3" height="8" rx="1.5"/><rect x="9" y="10.5" width="6" height="3" rx="1"/><rect x="16.5" y="8" width="3" height="8" rx="1.5"/><rect x="20" y="10" width="2.5" height="4" rx="1"/></svg>,
    kettlebell:<svg {...p}><circle cx="12" cy="14.5" r="7"/><path d="M9 8a3 3 0 0 1 6 0v2H9V8z"/></svg>,
    barbell:<svg {...p}><line x1="2" y1="12" x2="22" y2="12"/><rect x="4" y="7" width="3" height="10" rx="1"/><rect x="17" y="7" width="3" height="10" rx="1"/><rect x="8.5" y="9" width="2" height="6" rx="0.5"/><rect x="13.5" y="9" width="2" height="6" rx="0.5"/></svg>,
    receipt:<svg {...p}><path d="M4 2h16v20l-3-2-3 2-3-2-3 2-3-2-1 1zM9 7h6M9 11h6M9 15h4"/></svg>,
    kanban:<svg {...p}><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18M15 3v18"/></svg>,
    settings:<svg {...p}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9"/></svg>,
    logout:<svg {...p}><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9"/></svg>,
    plus:<svg {...p}><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>,
    trash:<svg {...p}><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6h14z"/></svg>,
    edit:<svg {...p}><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"/></svg>,
    search:<svg {...p}><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.3-4.3"/></svg>,
    calendar:<svg {...p}><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>,
    rupee:<svg {...p}><path d="M6 3h12M6 8h12M6 13l8.5 8M6 13h3c3 0 5-1.5 5-5"/></svg>,
    alert:<svg {...p}><path d="M12 9v4M12 17h.01M10.29 3.86l-8.4 14.55A1 1 0 0 0 2.75 20h18.5a1 1 0 0 0 .87-1.6l-8.4-14.55a1 1 0 0 0-1.72 0z"/></svg>,
    download:<svg {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>,
    sun:<svg {...p}><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>,
    moon:<svg {...p}><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8z"/></svg>,
    bell:<svg {...p}><path d="M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9M13.7 21a2 2 0 0 1-3.4 0"/></svg>,
    shield:<svg {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>,
    usercog:<svg {...p}><circle cx="9" cy="7" r="4"/><path d="M2 21v-2a4 4 0 0 1 4-4h3"/><circle cx="19" cy="17" r="2.5"/><path d="M19 14.5v.5m0 4v.5m2.5-2.5h-.5m-4 0h-.5"/></svg>,
    check:<svg {...p}><path d="M20 6L9 17l-5-5"/></svg>,
    eye:<svg {...p}><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>,
    eyeoff:<svg {...p}><path d="M17.94 17.94A10.94 10.94 0 0 1 12 20c-7 0-11-8-11-8a18.9 18.9 0 0 1 4.22-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.86 18.86 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>,
    mail:<svg {...p}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 6l-10 7L2 6"/></svg>,
    lock:<svg {...p}><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,
    upload:<svg {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>,
    whatsapp:<svg {...p} fill="currentColor" stroke="none" viewBox="0 0 24 24"><path d="M12.04 2c-5.46 0-9.9 4.44-9.9 9.9 0 1.75.46 3.45 1.32 4.95L2 22l5.25-1.38a9.87 9.87 0 0 0 4.79 1.22h.01c5.46 0 9.9-4.44 9.9-9.9 0-2.64-1.03-5.13-2.9-6.99A9.82 9.82 0 0 0 12.04 2zm0 1.8c2.16 0 4.2.84 5.72 2.37a8.06 8.06 0 0 1 2.37 5.73c0 4.46-3.63 8.09-8.1 8.09h-.01a8.1 8.1 0 0 1-4.13-1.13l-.3-.17-3.12.82.83-3.04-.19-.31a8.02 8.02 0 0 1-1.24-4.3c0-4.47 3.64-8.06 8.17-8.06zm-4.5 4.6c-.16 0-.42.06-.64.31-.22.25-.85.83-.85 2.02s.87 2.35.99 2.51c.12.16 1.68 2.7 4.16 3.68 2.06.81 2.48.65 2.93.61.45-.04 1.45-.59 1.65-1.16.2-.57.2-1.06.14-1.16-.06-.1-.22-.16-.46-.28-.24-.12-1.45-.71-1.67-.79-.22-.08-.39-.12-.55.12-.16.24-.63.79-.77.95-.14.16-.28.18-.52.06-.24-.12-1.02-.38-1.95-1.21-.72-.64-1.21-1.44-1.35-1.68-.14-.24-.01-.37.11-.49.11-.11.24-.28.36-.42.12-.14.16-.24.24-.4.08-.16.04-.3-.02-.42-.06-.12-.55-1.34-.76-1.83-.2-.48-.4-.42-.55-.42h-.03z"/></svg>,
    key:<svg {...p}><circle cx="7.5" cy="15.5" r="5.5"/><path d="M21 2l-9.6 9.6M15.5 7.5l3 3"/></svg>,
    refresh:<svg {...p}><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>,
    freeze:<svg {...p}><line x1="12" y1="2" x2="12" y2="22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>,
    chart:<svg {...p}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>,
    menu:<svg {...p}><path d="M3 12h18M3 6h18M3 18h18"/></svg>,
    close:<svg {...p}><path d="M18 6L6 18M6 6l12 12"/></svg>,
    wallet:<svg {...p}><path d="M20 12V8a2 2 0 0 0-2-2H5a2 2 0 0 1 0-4h12"/><path d="M3 5v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-4"/><path d="M21 12h-4a2 2 0 0 0 0 4h4v-4z"/></svg>,
    invoice:<svg {...p}><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>,
    reports:<svg {...p}><path d="M3 3v18h18"/><rect x="7" y="12" width="3" height="6"/><rect x="12" y="8" width="3" height="10"/><rect x="17" y="5" width="3" height="13"/></svg>,
  };
  return icons[n]||<svg {...p}/>;
};

/* ── Gym logo badge (used in sidebar, login screen, error screen) ──
   Renders a gym's uploaded custom logo when present, otherwise the
   Arctic Books shield logo. */
const GymLogo=({size=32,radius,src}) =>(
  src
  ? <div style={{width:size,height:size,borderRadius:radius??size*0.28,background:'#fff',
      border:'1px solid var(--border)',display:'flex',alignItems:'center',justifyContent:'center',
      flexShrink:0,overflow:'hidden'}}>
      <img src={src} alt="Gym logo" style={{width:'100%',height:'100%',objectFit:'contain'}}/>
    </div>
  : <div style={{width:size,height:size,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
      <ArcticLogoMark size={size} tight/>
    </div>
);

/* ── Arctic Books logo mark — the real brand icon (shield/book with
   gradient + star). Gradient ids are namespaced per-instance via useId
   so the mark can safely appear more than once on the same page. ── */
const ArcticLogoMark=({size=18,tight=false})=>{
  const uid=useId().replace(/[:]/g,'');
  return(
    <svg width={tight?size*400/468:size} height={size} viewBox={tight?"56 24 400 468":"0 0 512 512"} xmlns="http://www.w3.org/2000/svg" style={{flexShrink:0}}>
      <defs>
        <linearGradient id={`ab-grad-${uid}`} x1="0" y1="0" x2="512" y2="512" gradientUnits="userSpaceOnUse">
          <stop offset="0%" stopColor="#4F6FE8"/>
          <stop offset="100%" stopColor="#F1495C"/>
        </linearGradient>
        <linearGradient id={`ab-shine-${uid}`} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="rgba(255,255,255,0.18)"/>
          <stop offset="100%" stopColor="rgba(255,255,255,0)"/>
        </linearGradient>
      </defs>
      <path d="M256 36 L72 110 V262 C72 368 160 456 256 480 C352 456 440 368 440 262 V110 Z" fill={`url(#ab-grad-${uid})`}/>
      <path d="M256 36 L72 110 V262 C72 368 160 456 256 480 C352 456 440 368 440 262 V110 Z" fill={`url(#ab-shine-${uid})`}/>
      <rect x="174" y="168" width="164" height="23" rx="11.5" fill="#FFFFFF" fillOpacity="0.95"/>
      <rect x="174" y="212" width="128" height="23" rx="11.5" fill="#FFFFFF" fillOpacity="0.75"/>
      <rect x="174" y="256" width="146" height="23" rx="11.5" fill="#FFFFFF" fillOpacity="0.75"/>
      <path d="M256 316 L270 338 L295 330 L282 352 L298 372 L273 370 L256 392 L239 370 L214 372 L230 352 L217 330 L242 338 Z" fill="#FCD34D" fillOpacity="0.97"/>
    </svg>
  );
};

/* ── Arctic Books brand badge — links out to arcticbooks-in.web.app.
   Shown on the login screen and in the sidebar of every dashboard. ── */
const ARCTIC_BOOKS_URL='https://arcticbooks-in.web.app/';
const ArcticBooksBadge=({compact=false})=>(
  <a href={ARCTIC_BOOKS_URL} target="_blank" rel="noopener noreferrer" className="arctic-badge" title="Visit Arctic Books">
    <ArcticLogoMark size={compact?15:16}/>
    <span>{compact?'Arctic Books':<>Powered by <b>Arctic Books</b></>}</span>
  </a>
);

/* ══════════════════════════════════════════════════════════
   🔍  GLOBAL SEARCH (topbar)
   A real, working search across Members and Invoices — not a
   shortcut button. Typing shows a live dropdown of matches;
   picking one navigates to the right page/tab with that query
   already applied there (via the searchSeed prop pattern).
   ══════════════════════════════════════════════════════════ */
const GlobalSearch=({onNavigate})=>{
  useXp();
  const[query,setQuery]=useState('');
  const[open,setOpen]=useState(false);
  const wrapRef=useRef(null);

  useEffect(()=>{
    const onDocClick=e=>{ if(wrapRef.current&&!wrapRef.current.contains(e.target))setOpen(false); };
    document.addEventListener('mousedown',onDocClick);
    return()=>document.removeEventListener('mousedown',onDocClick);
  },[]);

  // Older invoices aren't loaded — look them up on demand once the person pauses typing.
  useEffect(()=>{
    const t=query.trim();
    if(t.length<3||InvDB.isComplete())return;
    const h=setTimeout(()=>{InvDB.search(t,S.get(SK.MEMBERS,[])||[]).catch(()=>{});},350);
    return()=>clearTimeout(h);
  },[query]);

  const q=query.trim().toLowerCase();
  let memberMatches=[],invoiceMatches=[];
  if(q.length>0){
    const members=S.get(SK.MEMBERS,[])||[];
    const invoices=InvDB.all();
    memberMatches=members.filter(m=>
      m.name?.toLowerCase().includes(q)||m.phone?.includes(q)||m.email?.toLowerCase().includes(q)
    ).slice(0,5);
    invoiceMatches=invoices.filter(i=>
      i.number?.toLowerCase().includes(q)||i.memberName?.toLowerCase().includes(q)
    ).slice(0,5);
  }
  const hasResults=memberMatches.length>0||invoiceMatches.length>0;

  const go=(page,seedQuery)=>{ onNavigate(page,seedQuery); setQuery(''); setOpen(false); };

  return(
    <div className="topbar-search" style={{marginLeft:20}} ref={wrapRef}>
      <span className="topbar-search-icon"><Ic n="search" s={14}/></span>
      <input
        placeholder="Search members, invoices…"
        value={query}
        onChange={e=>{setQuery(e.target.value);setOpen(true);}}
        onFocus={()=>{if(query)setOpen(true);}}
        onKeyDown={e=>{
          if(e.key==='Enter'){
            if(memberMatches[0])go('members',memberMatches[0].name);
            else if(invoiceMatches[0])go('invoices',invoiceMatches[0].number);
          }else if(e.key==='Escape'){setOpen(false);e.currentTarget.blur();}
        }}
      />
      {open&&q.length>0&&(
        <div className="search-dropdown">
          {!hasResults&&<div className="search-dropdown-empty">No matches for "{query}"</div>}
          {memberMatches.length>0&&<>
            <div className="search-dropdown-label">Members</div>
            {memberMatches.map(m=>(
              <div key={m.id} className="search-dropdown-item" onClick={()=>go('members',m.name)}>
                <Ic n="users" s={13}/>
                <div><div className="sdi-title">{m.name}</div><div className="sdi-sub">{m.phone||m.email||'—'}</div></div>
              </div>
            ))}
          </>}
          {invoiceMatches.length>0&&<>
            <div className="search-dropdown-label">Invoices</div>
            {invoiceMatches.map(i=>(
              <div key={i.id} className="search-dropdown-item" onClick={()=>go('invoices',i.number)}>
                <Ic n="invoice" s={13}/>
                <div><div className="sdi-title">{i.number}</div><div className="sdi-sub">{i.memberName||'—'}</div></div>
              </div>
            ))}
          </>}
        </div>
      )}
    </div>
  );
};


let _toast=null;
const toast={success:m=>_toast&&_toast(m,'success'),error:m=>_toast&&_toast(m,'error'),info:m=>_toast&&_toast(m,'info')};
window.toast=toast; window.PAYMENT_REF_MODES=PAYMENT_REF_MODES;
const Toast=()=>{
  const[list,setList]=useState([]);
  useEffect(()=>{_toast=(msg,type)=>{const id=Date.now();setList(p=>[...p,{id,msg,type}]);setTimeout(()=>setList(p=>p.filter(x=>x.id!==id)),3500);};},[]);
  return<div className="toast-wrap">{list.map(t=><div key={t.id} className={`toast-item toast-${t.type}`}><Ic n={t.type==='success'?'check':t.type==='error'?'close':'bell'} s={14}/><span>{t.msg}</span></div>)}</div>;
};

/* ══════════════════════════════════════════════════════════
   🔐  LOGIN PAGE
   ══════════════════════════════════════════════════════════ */

/* ══════════════════════════════════════════════════════════
   🔑  PASSWORDS — change your own (in app) · set new one from e-mail link (in app)
   ══════════════════════════════════════════════════════════ */
const pwProblem=(p,c)=>{
  if((p||'').length<8)return'Use at least 8 characters.';
  if(!/[A-Za-z]/.test(p)||!/[0-9]/.test(p))return'Use letters and at least one number.';
  if(c!==undefined&&p!==c)return'The two new passwords do not match.';
  return'';
};
const PwInput=({label,value,onChange,autoComplete})=>{
  const[show,setShow]=useState(false);
  return(<div className="field"><label className="field-label">{label}</label>
    <div className="input-icon-wrap"><span className="input-icon"><Ic n="lock" s={15}/></span>
      <input className="field-input" type={show?'text':'password'} value={value} autoComplete={autoComplete} onChange={e=>onChange(e.target.value)} style={{paddingRight:38}}/>
      <span className="input-icon-right" onClick={()=>setShow(s=>!s)}><Ic n={show?'eyeoff':'eye'} s={15}/></span></div></div>);
};
const ChangePasswordModal=({onClose})=>{
  const[cur,setCur]=useState('');const[np,setNp]=useState('');const[cp,setCp]=useState('');
  const[err,setErr]=useState('');const[busy,setBusy]=useState(false);const[done,setDone]=useState(false);
  const submit=async()=>{
    setErr('');
    if(!cur){setErr('Enter your current password.');return;}
    const p=pwProblem(np,cp);if(p){setErr(p);return;}
    if(np===cur){setErr('The new password must be different from the current one.');return;}
    setBusy(true);
    try{await Auth.changePassword(cur,np);setDone(true);toast.success('Password changed');}
    catch(e){
      const c=e&&e.code;
      setErr(['auth/wrong-password','auth/invalid-credential','auth/invalid-login-credentials'].includes(c)?'Your current password is not correct.':Auth.friendly(e));
    }finally{setBusy(false);}
  };
  return(
    <div className="overlay" onClick={onClose}>
      <div className="modal" style={{maxWidth:420}} onClick={e=>e.stopPropagation()}>
        <div className="modal-hdr"><div className="modal-title">Change my password</div><button className="close-btn" onClick={onClose}>×</button></div>
        <div className="modal-body">
          {done?<div style={{color:'var(--green)',fontSize:14}}>✅ Your password has been changed. Use the new one next time you log in.</div>:<>
            <PwInput label="Current password" value={cur} onChange={setCur} autoComplete="current-password"/>
            <PwInput label="New password" value={np} onChange={setNp} autoComplete="new-password"/>
            <PwInput label="Repeat new password" value={cp} onChange={setCp} autoComplete="new-password"/>
            <div style={{fontSize:11.5,color:'var(--text3)'}}>At least 8 characters, with letters and a number.</div>
            {err&&<div style={{color:'var(--red)',fontSize:13,marginTop:10,padding:'8px 12px',background:'var(--danger-bg)',borderRadius:8}}>{err}</div>}
          </>}
        </div>
        <div className="modal-ftr">
          <button className="btn btn-outline" onClick={onClose}>{done?'Close':'Cancel'}</button>
          {!done&&<button className="btn btn-primary" disabled={busy} onClick={submit}><Ic n="check" s={13}/>{busy?'Saving…':'Change password'}</button>}
        </div>
      </div>
    </div>);
};
/* Opened by the link in the reset e-mail (…/?mode=resetPassword&oobCode=…). */
const ResetPasswordPage=({oobCode,onDone})=>{
  const[state,setState]=useState('checking');   // checking | ready | bad | done
  const[email,setEmail]=useState('');const[np,setNp]=useState('');const[cp,setCp]=useState('');
  const[err,setErr]=useState('');const[busy,setBusy]=useState(false);
  useEffect(()=>{Auth.verifyResetCode(oobCode).then(e=>{setEmail(e);setState('ready');}).catch(e=>{setErr(Auth.friendly(e));setState('bad');});},[oobCode]);
  const submit=async()=>{
    setErr('');const p=pwProblem(np,cp);if(p){setErr(p);return;}
    setBusy(true);
    try{await Auth.confirmReset(oobCode,np);setState('done');}
    catch(e){setErr(Auth.friendly(e));}finally{setBusy(false);}
  };
  return(
    <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center',padding:16}}>
      <div className="card" style={{width:'100%',maxWidth:420}}>
        <div style={{fontWeight:800,fontSize:18,marginBottom:6}}>Set a new password</div>
        {state==='checking'&&<div style={{color:'var(--text3)'}}>Checking your link…</div>}
        {state==='bad'&&<><div style={{color:'var(--red)',fontSize:13,margin:'8px 0 14px'}}>{err}</div><button className="btn btn-primary fw" onClick={onDone}>Back to login</button></>}
        {state==='ready'&&<>
          <div style={{fontSize:12.5,color:'var(--text3)',marginBottom:12}}>For <b>{email}</b></div>
          <PwInput label="New password" value={np} onChange={setNp} autoComplete="new-password"/>
          <PwInput label="Repeat new password" value={cp} onChange={setCp} autoComplete="new-password"/>
          <div style={{fontSize:11.5,color:'var(--text3)'}}>At least 8 characters, with letters and a number.</div>
          {err&&<div style={{color:'var(--red)',fontSize:13,marginTop:10,padding:'8px 12px',background:'var(--danger-bg)',borderRadius:8}}>{err}</div>}
          <button className="btn btn-primary fw" style={{marginTop:14}} disabled={busy} onClick={submit}>{busy?'Saving…':'Save new password'}</button></>}
        {state==='done'&&<><div style={{color:'var(--green)',fontSize:14,margin:'8px 0 14px'}}>✅ Password updated. You can log in now.</div><button className="btn btn-primary fw" onClick={onDone}>Go to login</button></>}
      </div>
    </div>);
};

const Login=({onLogin,settings={}})=>{
  const[email,setEmail]=useState('');
  const[pass,setPass]=useState('');
  const[showPass,setShowPass]=useState(false);
  const[err,setErr]=useState('');
  const[loading,setLoading]=useState(false);
  const gymName=settings.name||'Arctic Gym Management';
  const[mode,setMode]=useState('login');         // 'login' | 'forgot'
  const[sent,setSent]=useState(false);
  const sendLink=async e=>{
    e.preventDefault();setErr('');
    if(!email.trim()){setErr('Enter your e-mail address first.');return;}
    setLoading(true);
    try{await Auth.sendReset(email.trim());}
    catch(x){ if(!['auth/user-not-found','auth/invalid-email'].includes(x&&x.code)){setErr(Auth.friendly(x));setLoading(false);return;} }
    setSent(true);setLoading(false);   // same message whether or not the e-mail exists (no account guessing)
  };

  const handle=async e=>{
    e.preventDefault();setErr('');setLoading(true);
    try{
      await Auth.signIn(email.trim(),pass);          // App's auth listener loads the data and opens the dashboard
    }catch(e){setErr(Auth.friendly(e));setLoading(false);}
  };

  return(
    <div className="login-shell">
      <div className="login-brand">
        <div className="login-brand-glow2"/>
        <div className="login-deco-left dl1"><Ic n="dumbbell" s={54}/></div>
        <div className="login-deco-left dl2"><Ic n="kettlebell" s={46}/></div>
        <div className="login-deco-left dl3"><Ic n="barbell" s={40}/></div>
        <div className="login-deco-left dl4"><Ic n="dumbbell" s={34}/></div>
        <div className="login-deco-left dl5"><Ic n="kettlebell" s={30}/></div>
        <div className="login-deco-left dl6"><Ic n="barbell" s={52}/></div>
        <div className="login-deco-left dl7"><Ic n="dumbbell" s={26}/></div>
        <div style={{position:'relative',zIndex:1}}><ArcticBooksBadge compact/></div>
        <div style={{display:'flex',alignItems:'center',gap:12}}>
          <GymLogo size={44} radius={13} src={settings.logo}/>
          <span style={{fontFamily:'Sora,sans-serif',fontWeight:800,fontSize:22}}>{gymName}</span>
        </div>
        <h2 style={{fontFamily:'Sora,sans-serif',fontSize:32,lineHeight:1.28,maxWidth:400,fontWeight:800,margin:0}}>
          Run your gym's members, billing and trainers in one place.
        </h2>
      </div>
      <div className="login-form-wrap">
        <div className="login-deco d1"><Ic n="dumbbell" s={64}/></div>
        <div className="login-deco d2"><Ic n="kettlebell" s={54}/></div>
        <div className="login-deco d3"><Ic n="barbell" s={46}/></div>
        <div className="login-deco d4"><Ic n="dumbbell" s={40}/></div>
        <div className="login-deco d5"><Ic n="kettlebell" s={36}/></div>
        <div className="login-deco d6"><Ic n="barbell" s={58}/></div>
        <div className="login-deco d7"><Ic n="dumbbell" s={30}/></div>
        <div className="login-deco d8"><Ic n="kettlebell" s={44}/></div>
        <div style={{display:'flex',flexDirection:'column',alignItems:'center',position:'relative',zIndex:1}}>
        <div className="login-card">
          <div style={{display:'flex',justifyContent:'center',marginBottom:20}}>
            <GymLogo size={52} radius={15} src={settings.logo}/>
          </div>
          <div style={{marginBottom:26,textAlign:'center'}}>
            <div style={{fontSize:23,fontWeight:800,fontFamily:'Sora,sans-serif',color:'var(--text)',marginBottom:5}}>Welcome back</div>
            <div style={{fontSize:13.5,color:'var(--text3)'}}>Log in to {gymName}</div>
          </div>
          {mode==='forgot'?(<form onSubmit={sendLink}>
            <div style={{fontWeight:700,fontSize:16,marginBottom:4}}>Reset your password</div>
            <div style={{fontSize:12.5,color:'var(--text3)',marginBottom:14}}>Enter your login e-mail. We will send you a link to choose a new password.</div>
            {sent?<div style={{color:'var(--green)',fontSize:13,padding:'10px 12px',background:'rgba(34,197,94,0.1)',borderRadius:8,marginBottom:12}}>If this e-mail has a login, a reset link is on its way. Check your inbox and spam folder (it can take a minute).</div>
            :<>
              <div className="field"><label className="field-label">Email</label>
                <div className="input-icon-wrap"><span className="input-icon"><Ic n="mail" s={15}/></span>
                  <input className="field-input" type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@example.com" required/></div></div>
              {err&&<div style={{color:'var(--red)',fontSize:13,marginBottom:12,padding:'8px 12px',background:'var(--danger-bg)',borderRadius:8}}>{err}</div>}
              <button className="btn btn-primary fw" type="submit" disabled={loading}>{loading?'Sending…':'Send reset link'}</button>
            </>}
            <button type="button" className="btn btn-outline fw" style={{marginTop:10}} onClick={()=>{setMode('login');setSent(false);setErr('');}}>← Back to login</button>
          </form>):(<form onSubmit={handle}>
            <div className="field">
              <label className="field-label">Email</label>
              <div className="input-icon-wrap">
                <span className="input-icon"><Ic n="mail" s={15}/></span>
                <input className="field-input" type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@yourgym.com" required autoFocus/>
              </div>
            </div>
            <div className="field">
              <label className="field-label">Password</label>
              <div className="input-icon-wrap">
                <span className="input-icon"><Ic n="lock" s={15}/></span>
                <input className="field-input" type={showPass?'text':'password'} value={pass} onChange={e=>setPass(e.target.value)} placeholder="••••••••" required style={{paddingRight:38}}/>
                <span className="input-icon-right" onClick={()=>setShowPass(s=>!s)} title={showPass?'Hide password':'Show password'}>
                  <Ic n={showPass?'eyeoff':'eye'} s={15}/>
                </span>
              </div>
            </div>
            {err&&<div style={{color:'var(--red)',fontSize:13,marginBottom:12,padding:'8px 12px',background:'var(--danger-bg)',borderRadius:8}}>{err}</div>}
            <div style={{textAlign:'right',marginBottom:8}}><button type="button" onClick={()=>{setMode('forgot');setErr('');}} style={{background:'none',border:'none',color:'var(--blue)',cursor:'pointer',fontSize:12.5,fontWeight:600}}>Forgot password?</button></div>
            <button className="btn btn-primary fw" type="submit" disabled={loading} style={{marginTop:4}}>
              {loading?'Logging in…':'Log In'}
            </button>
          </form>)}
        </div>
        <div className="login-arctic"><ArcticBooksBadge/></div>
        </div>
      </div>
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   📊  DASHBOARD
   ══════════════════════════════════════════════════════════ */

const useXp=()=>{
  const[,setT]=useState(0);
  useEffect(()=>{const f=()=>setT(x=>x+1);_xpListeners.add(f);return()=>{_xpListeners.delete(f);};},[]);
};

const useMedia=q=>{
  const[m,setM]=useState(()=>window.matchMedia(q).matches);
  useEffect(()=>{
    const mq=window.matchMedia(q),h=()=>setM(mq.matches);
    mq.addEventListener?mq.addEventListener('change',h):mq.addListener(h);h();
    return()=>{mq.removeEventListener?mq.removeEventListener('change',h):mq.removeListener(h);};
  },[q]);
  return m;
};
const expCalc=(amount,rate)=>{
  const a=round2(parseFloat(amount)||0);
  const g=round2(a*(Number(rate)||0)/100);
  return{amount:a,gstAmount:g,total:round2(a+g)};
};
const newExpNo=()=>`EXP-${today().replace(/-/g,'')}-${Math.random().toString(36).slice(2,6).toUpperCase()}`;
const sumTotal=list=>round2(list.reduce((s,e)=>s+(e.total||0),0));
const superAdminList=()=>(S.get(SK.USERS,[])||[]).filter(u=>u.role==='superadmin'&&u.active!==false);
const expSort=(a,b)=>((b.date||'').localeCompare(a.date||''))||((b.createdAt||'').localeCompare(a.createdAt||''));
const timeAgo=iso=>{
  if(!iso)return'';
  const s=Math.max(0,(Date.now()-new Date(iso).getTime())/1000);
  if(s<60)return'just now';
  if(s<3600)return Math.floor(s/60)+' min ago';
  if(s<86400)return Math.floor(s/3600)+' hr ago';
  if(s<604800)return Math.floor(s/86400)+' d ago';
  return fmtD(iso.slice(0,10));
};
const pushNotif=(toUserId,type,exp,message)=>xpPut(NT_KEY,{
  id:'NT-'+genId(),toUserId,type,expenseId:exp.id,expNo:exp.expNo,message,
  createdAt:new Date().toISOString(),read:false
});

/* Approve / reject — Super Admin only (enforced here, not just by hiding buttons). */
const reviewExpense=(user,exp,decision,note='')=>{
  if(!user||user.role!=='superadmin'){toast.error('Only a Super Admin can approve or reject expenses.');return false;}
  const fresh=xpMap(XP_KEY)[exp.id]||exp;
  const rec={...fresh,status:decision,reviewedBy:user.name,reviewedById:user.id,
    reviewedAt:new Date().toISOString(),reviewNote:note||''};
  xpPut(XP_KEY,rec,expDeltas(fresh,rec));
  if(rec.createdById&&rec.createdById!==user.id){
    const what=`${rec.expNo} — ${rec.title} (${fmt(rec.total)})`;
    pushNotif(rec.createdById,decision,rec,decision==='approved'
      ?`Your expense ${what} has been approved by ${user.name}.`
      :`Your expense ${what} was rejected by ${user.name}${note?': '+note:'.'}`);
  }
  return true;
};

/* Bill photo → compressed JPEG data-URL (keeps storage small) */
const readBillImage=file=>new Promise((res,rej)=>{
  if(!file||!/^image\//.test(file.type))return rej(new Error('Please attach a photo of the bill (JPG / PNG).'));
  const fr=new FileReader();
  fr.onerror=()=>rej(new Error('Could not read that file.'));
  fr.onload=()=>{
    const img=new Image();
    img.onerror=()=>rej(new Error('That image could not be opened.'));
    img.onload=()=>{
      const max=1000,sc=Math.min(1,max/Math.max(img.width,img.height));
      const c=document.createElement('canvas');
      c.width=Math.round(img.width*sc);c.height=Math.round(img.height*sc);
      c.getContext('2d').drawImage(img,0,0,c.width,c.height);
      res(c.toDataURL('image/jpeg',0.65));
    };
    img.src=fr.result;
  };
  fr.readAsDataURL(file);
});

/* ── Excel: Expenses report ── */
const exportExpensesExcel=(expenses,invoices,settings,from,to,mode)=>{
  const inP=expenses.filter(e=>inPeriod(e.date,from,to));
  const sel=(mode==='all'?inP:inP.filter(e=>e.status===mode)).slice().sort((a,b)=>(a.date||'').localeCompare(b.date||''));
  const approved=inP.filter(e=>e.status==='approved');
  const pending=inP.filter(e=>e.status==='pending');
  const rejected=inP.filter(e=>e.status==='rejected');
  const periodInv=(invoices||[]).filter(i=>inPeriod(i.date,from,to));
  const revenue=round2(periodInv.reduce((s,i)=>s+(i.total||0),0));
  const gstCollected=round2(periodInv.reduce((s,i)=>s+invTax(i).gst,0));
  const periodText=(from||to)?`${from?fmtD(from):'Beginning'} to ${to?fmtD(to):'Today'}`:'All time';
  const basisText={approved:'Approved expenses only (these are in the books)',pending:'Pending approval only',rejected:'Rejected only',all:'All expenses with status'}[mode]||mode;

  const headers=['Expense No','Date','Category','Description','Vendor / Paid To','Bill / Invoice No','Amount (before GST)','GST %','GST Amount','Total Paid','Payment Mode','Payment Reference','Paid From','Recurring','Notes','Status','Submitted By','Submitted On','Reviewed By','Reviewed On','Review Note','Bill Attached'];
  const rows=sel.map(e=>({
    'Expense No':e.expNo||e.id,'Date':fmtD(e.date),'Category':e.category||'','Description':e.title||'',
    'Vendor / Paid To':e.vendor||'','Bill / Invoice No':e.billNo||'','Amount (before GST)':e.amount||0,
    'GST %':e.gstRate||0,'GST Amount':e.gstAmount||0,'Total Paid':e.total||0,
    'Payment Mode':e.paymentMode||'','Payment Reference':e.paymentRef||'','Paid From':e.paidFrom||'',
    'Recurring':e.recurring||'One-time','Notes':e.notes||'','Status':cap1(e.status),
    'Submitted By':e.createdBy||'','Submitted On':e.createdAt?fmtD(e.createdAt.slice(0,10)):'',
    'Reviewed By':e.reviewedBy||'','Reviewed On':e.reviewedAt?fmtD(e.reviewedAt.slice(0,10)):'',
    'Review Note':e.reviewNote||'','Bill Attached':(e.bill||e.hasBill)?'Yes':'No'
  }));
  if(rows.length){
    const t={};headers.forEach(h=>t[h]='');
    t['Description']='TOTAL';
    t['Amount (before GST)']=round2(sel.reduce((s,e)=>s+(e.amount||0),0));
    t['GST Amount']=round2(sel.reduce((s,e)=>s+(e.gstAmount||0),0));
    t['Total Paid']=sumTotal(sel);
    rows.push(t);
  }
  const group=(keyFn,label)=>{
    const m={};
    sel.forEach(e=>{const k=keyFn(e)||'—';m[k]=m[k]||{n:0,amt:0,gst:0,tot:0};m[k].n++;m[k].amt+=e.amount||0;m[k].gst+=e.gstAmount||0;m[k].tot+=e.total||0;});
    const grand=sel.reduce((s,e)=>s+(e.total||0),0)||1;
    return Object.entries(m).sort((a,b)=>b[1].tot-a[1].tot).map(([k,v])=>({
      [label]:k,'No. of Expenses':v.n,'Amount (before GST)':round2(v.amt),'GST Amount':round2(v.gst),
      'Total Paid':round2(v.tot),'% of Total':round2(v.tot/grand*100)+'%'
    }));
  };
  const gh=l=>[l,'No. of Expenses','Amount (before GST)','GST Amount','Total Paid','% of Total'];
  const summaryAoa=[
    ['EXPENSES REPORT'],[],
    ['Gym',settings.name||'Arctic Gym Management'],
    ['Period',periodText],
    ['Report shows',basisText],
    ['Generated on',fmtD(today())],[],
    ['IN THE BOOKS (approved)',''],
    ['Approved expenses (count)',approved.length],
    ['Approved expenses — before GST',round2(approved.reduce((s,e)=>s+(e.amount||0),0))],
    ['GST paid on approved expenses (input GST)',round2(approved.reduce((s,e)=>s+(e.gstAmount||0),0))],
    ['Approved expenses — total paid',sumTotal(approved)],[],
    ['WAITING / NOT IN THE BOOKS',''],
    ['Pending approval (count)',pending.length],
    ['Pending approval — total',sumTotal(pending)],
    ['Rejected (count)',rejected.length],
    ['Rejected — total',sumTotal(rejected)],[],
    ['REVENUE vs EXPENSES (same period)',''],
    ['Invoices raised (count)',periodInv.length],
    ['Revenue collected (incl. GST)',revenue],
    ['GST collected on invoices',gstCollected],
    ['Less: approved expenses (total paid)',sumTotal(approved)],
    ['NET RESULT (revenue − approved expenses)',round2(revenue-sumTotal(approved))],[],
    ['Note','Only Super Admin–approved expenses are counted in the books figures above.'],
  ];
  const wsSum=XLSX.utils.aoa_to_sheet(summaryAoa);wsSum['!cols']=[{wch:44},{wch:46}];
  const wb=XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb,wsSum,'Summary');
  XLSX.utils.book_append_sheet(wb,makeSheet(rows,headers),'Expense Register');
  XLSX.utils.book_append_sheet(wb,makeSheet(group(e=>e.category,'Category'),gh('Category')),'By Category');
  XLSX.utils.book_append_sheet(wb,makeSheet(group(e=>(e.date||'').slice(0,7),'Month').sort((a,b)=>a.Month.localeCompare(b.Month)),gh('Month')),'By Month');
  XLSX.utils.book_append_sheet(wb,makeSheet(group(e=>e.paymentMode,'Payment Mode'),gh('Payment Mode')),'By Payment Mode');
  XLSX.utils.book_append_sheet(wb,makeSheet(group(e=>e.createdBy,'Submitted By'),gh('Submitted By')),'By Staff');
  XLSX.writeFile(wb,`Expenses_Report_${mode}_${from||'all'}_to_${to||'all'}.xlsx`);
};

/* ── Notification bell (top bar) ── */
const NotificationBell=({user,onOpen})=>{
  useXp();
  const[open,setOpen]=useState(false);
  const wrapRef=useRef(null);
  useEffect(()=>{ // close when clicking anywhere outside the bell (doesn't block the rest of the page)
    if(!open)return;
    const h=ev=>{if(wrapRef.current&&!wrapRef.current.contains(ev.target))setOpen(false);};
    document.addEventListener('mousedown',h);
    return()=>document.removeEventListener('mousedown',h);
  },[open]);
  const mountedAt=useRef(new Date().toISOString());
  const seen=useRef(new Set());
  const mine=xpList(NT_KEY).filter(n=>n.toUserId===user.id).sort((a,b)=>(b.createdAt||'').localeCompare(a.createdAt||''));
  const unread=mine.filter(n=>!n.read);
  const unreadRef=useRef(0);unreadRef.current=unread.length;

  useEffect(()=>{ // summary on login
    const t=setTimeout(()=>{if(unreadRef.current)toast.info(`You have ${unreadRef.current} unread notification${unreadRef.current>1?'s':''} — tap the bell`);},1800);
    return()=>clearTimeout(t);
  },[]);
  useEffect(()=>{ // live pop-up for anything that arrives while you're using the app
    mine.forEach(n=>{
      if(seen.current.has(n.id))return;
      seen.current.add(n.id);
      if(!n.read&&(n.createdAt||'')>mountedAt.current){
        (n.type==='rejected'?toast.error:n.type==='approved'?toast.success:toast.info)(n.message);
      }
    });
  });
  const markRead=n=>{if(!n.read)xpPut(NT_KEY,{...n,read:true});};
  const markAll=()=>unread.forEach(markRead);
  const icon={approved:'check',rejected:'close',submitted:'wallet'};
  const color={approved:'var(--green)',rejected:'var(--red)',submitted:'var(--warn)'};

  return(
    <div className="notif-wrap" ref={wrapRef}>
      <div className="topbar-icon-btn" onClick={()=>setOpen(o=>!o)} title="Notifications">
        <Ic n="bell" s={15}/>
        {unread.length>0&&<span className="notif-badge">{unread.length>9?'9+':unread.length}</span>}
      </div>
      {open&&<>
        <div className="notif-pop">
          <div className="notif-hdr">
            <span>Notifications</span>
            {unread.length>0&&<button className="btn btn-sm btn-outline" onClick={markAll}>Mark all read</button>}
          </div>
          {mine.length===0
            ?<div className="tbl-empty" style={{padding:'28px 16px'}}>No notifications yet</div>
            :mine.slice(0,30).map(n=>(
              <div key={n.id} className={`notif-item${n.read?'':' unread'}`}
                onClick={()=>{markRead(n);setOpen(false);onOpen&&onOpen();}}>
                <div className="notif-ico" style={{color:color[n.type]||'var(--text2)'}}><Ic n={icon[n.type]||'bell'} s={14}/></div>
                <div style={{minWidth:0}}>
                  <div className="notif-msg">{n.message}</div>
                  <div className="notif-time">{timeAgo(n.createdAt)}</div>
                </div>
              </div>
            ))}
        </div>
      </>}
    </div>
  );
};

const StatusBadge=({e})=>(
  <span className={`badge ${e.status==='approved'?'badge-active':e.status==='rejected'?'badge-expired':'badge-pending'}`}>
    {e.status==='approved'?'Approved':e.status==='rejected'?'Rejected':'Pending'}
  </span>
);

/* Bill photo loaded only when an expense is opened */
const BillView=({e})=>{
  const[img,setImg]=useState(e.bill||'');
  const[busy,setBusy]=useState(!e.bill&&!!e.hasBill);
  useEffect(()=>{
    let alive=true;
    if(!e.bill&&e.hasBill){setBusy(true);xpGetBill(e.id).then(b=>{if(alive){setImg(b);setBusy(false);}});}
    return()=>{alive=false;};
  },[e.id]);
  if(!e.bill&&!e.hasBill)return null;
  return <div style={{marginTop:14}}><div className="field-label">Bill / receipt</div>
    {busy?<div className="muted">Loading bill photo…</div>
      :img?<img src={img} alt="Bill" style={{maxWidth:'100%',borderRadius:10,border:'1px solid var(--border)'}}/>
      :<div className="muted">Bill photo could not be loaded.</div>}
  </div>;
};

/* ── Expenses page ── */
const EMPTY_EXP=()=>({date:today(),category:'',title:'',vendor:'',amount:'',gstRate:0,paymentMode:'Cash',paymentRef:'',
  paidFrom:'Gym bank account',billNo:'',recurring:'One-time',notes:'',bill:'',billChanged:false,hadBill:false,markApproved:true});

const Expenses=({user,seed})=>{
  useXp();
  const asCards=useMedia('(max-width:1299px)'); // table on wide screens, cards on tablets / phones
  const xt=xpTotals();
  const complete=xpComplete();
  const[olderBusy,setOlderBusy]=useState(false);
  const isSuper=user.role==='superadmin';
  const all=xpList(XP_KEY);
  const base=(isSuper?all:all.filter(e=>e.createdById===user.id)).slice().sort(expSort);
  const settings=S.get(SK.SETTINGS,{})||{};

  const[showForm,setShowForm]=useState(false);
  const[editId,setEditId]=useState(null);
  const[form,setForm]=useState(EMPTY_EXP());
  const[statusF,setStatusF]=useState(seed?.status||'all');
  const[catF,setCatF]=useState('');
  const[byF,setByF]=useState('');
  const[from,setFrom]=useState('');
  const[to,setTo]=useState('');
  const[q,setQ]=useState('');
  const[sel,setSel]=useState([]);
  const[detail,setDetail]=useState(null);
  useEffect(()=>{if(seed?.status){setStatusF(seed.status);setSel([]);}},[seed?.token]);
  useEffect(()=>{if(from)xpEnsureFrom(from).catch(()=>{});},[from]);
  const loadOlder=async(all)=>{setOlderBusy(true);try{await(all?xpLoadAll():xpLoadOlder());}catch(e){toast.error('Could not load older expenses: '+e.message);}setOlderBusy(false);};

  const f=(k,v)=>setForm(p=>({...p,[k]:v}));
  const calc=expCalc(form.amount,form.gstRate);

  const approvedL=base.filter(e=>e.status==='approved');
  const pendingL=base.filter(e=>e.status==='pending');
  const rejectedL=base.filter(e=>e.status==='rejected');
  const monthKey=new Date().toISOString().slice(0,7);
  const monthTotal=sumTotal(approvedL.filter(e=>(e.date||'').startsWith(monthKey)));

  const list=base.filter(e=>{
    if(statusF!=='all'&&e.status!==statusF)return false;
    if(catF&&e.category!==catF)return false;
    if(byF&&e.createdById!==byF)return false;
    if(from&&(e.date||'')<from)return false;
    if(to&&(e.date||'')>to)return false;
    if(q){const s=q.toLowerCase();
      if(![e.title,e.vendor,e.expNo,e.billNo,e.category,e.createdBy,e.paymentRef].some(x=>(x||'').toLowerCase().includes(s)))return false;}
    return true;
  });
  const submitters=[...new Map(base.map(e=>[e.createdById,e.createdBy])).entries()];
  const selectable=list.filter(e=>e.status==='pending').map(e=>e.id);
  const selList=sel.filter(id=>selectable.includes(id));

  const openNew=()=>{setEditId(null);setForm(EMPTY_EXP());setShowForm(true);window.scrollTo({top:0,behavior:'smooth'});};
  const startEdit=e=>{
    if(!isSuper)return;
    setEditId(e.id);
    setForm({date:e.date,category:e.category,title:e.title,vendor:e.vendor||'',amount:e.amount,gstRate:e.gstRate||0,
      paymentMode:e.paymentMode||'Cash',paymentRef:e.paymentRef||'',paidFrom:e.paidFrom||EXPENSE_PAID_FROM[0],
      billNo:e.billNo||'',recurring:e.recurring||'One-time',notes:e.notes||'',bill:e.bill||'',billChanged:false,hadBill:!!(e.bill||e.hasBill),markApproved:true});
    if(!e.bill&&e.hasBill)xpGetBill(e.id).then(b=>setForm(p=>p.billChanged?p:{...p,bill:b}));
    setDetail(null);setShowForm(true);window.scrollTo({top:0,behavior:'smooth'});
  };
  const repeat=e=>{
    setEditId(null);
    setForm({...EMPTY_EXP(),category:e.category,title:e.title,vendor:e.vendor||'',amount:e.amount,gstRate:e.gstRate||0,
      paymentMode:e.paymentMode||'Cash',paidFrom:e.paidFrom||EXPENSE_PAID_FROM[0],recurring:e.recurring||'One-time',notes:e.notes||''});
    setDetail(null);setShowForm(true);window.scrollTo({top:0,behavior:'smooth'});
    toast.info('Details copied — check the date, amount and payment reference, then save.');
  };
  const pickBill=async ev=>{
    const file=ev.target.files&&ev.target.files[0];ev.target.value='';
    if(!file)return;
    try{const data=await readBillImage(file);setForm(p=>({...p,bill:data,billChanged:true,hadBill:true}));}catch(err){toast.error(err.message);}
  };
  const save=()=>{
    if(!form.date||!form.category||!form.title.trim()||!(parseFloat(form.amount)>0)){
      toast.error('Date, category, description and an amount greater than 0 are required.');return;}
    if(needsPaymentRef(form.paymentMode)&&!form.paymentRef.trim()){
      toast.error(`Enter the ${PAYMENT_REF_MODES[form.paymentMode].short} for this ${form.paymentMode} payment.`);return;}
    const c=expCalc(form.amount,form.gstRate);
    const fields={date:form.date,category:form.category,title:form.title.trim(),vendor:form.vendor.trim(),
      amount:c.amount,gstRate:Number(form.gstRate)||0,gstAmount:c.gstAmount,total:c.total,
      paymentMode:form.paymentMode,paymentRef:needsPaymentRef(form.paymentMode)?form.paymentRef.trim():'',
      paidFrom:form.paidFrom,billNo:form.billNo.trim(),recurring:form.recurring,notes:form.notes.trim()};
    const now=new Date().toISOString();
    if(editId){
      if(!isSuper){toast.error('Only a Super Admin can edit expenses.');return;}
      const old=xpMap(XP_KEY)[editId];if(!old){toast.error('That expense no longer exists.');return;}
      const upd={...old,...fields,editedBy:user.name,editedAt:now};
      if(form.billChanged){
        delete upd.bill;
        if(form.bill){upd.hasBill=true;xpPutBill(old.id,form.bill);}
        else{upd.hasBill=false;xpWrite({set:{['expense_bills/'+old.id]:null}});delete _billCache[old.id];}
      }
      xpPut(XP_KEY,upd,expDeltas(old,upd));
      toast.success('Expense updated');
    }else{
      const rec={id:'EXP-'+genId(),expNo:newExpNo(),...fields,status:'pending',
        createdBy:user.name,createdById:user.id,createdByRole:user.role,createdAt:now};
      if(isSuper&&form.markApproved)Object.assign(rec,{status:'approved',reviewedBy:user.name,reviewedById:user.id,reviewedAt:now,reviewNote:'Approved on entry'});
      if(form.bill){rec.hasBill=true;xpPutBill(rec.id,form.bill);}
      xpPut(XP_KEY,rec,expDeltas(null,rec));
      if(rec.status==='pending'){
        superAdminList().filter(a=>a.id!==user.id).forEach(a=>pushNotif(a.id,'submitted',rec,
          `${user.name} submitted expense ${rec.expNo} — ${rec.title} (${fmt(rec.total)}) for your approval.`));
        toast.success('Expense submitted — waiting for Super Admin approval');
      }else toast.success('Expense recorded and added to the books');
    }
    setShowForm(false);setEditId(null);setForm(EMPTY_EXP());
  };
  const approve=e=>{
    if(!window.confirm(`Approve ${e.expNo} — ${e.title} for ${fmt(e.total)}?\n\nIt will be added to the books and ${e.createdBy} will be notified.`))return;
    if(reviewExpense(user,e,'approved')){toast.success('Expense approved and added to the books');setDetail(null);}
  };
  const reject=e=>{
    const note=window.prompt(`Reject ${e.expNo} — ${e.title}?\n\nReason (shown to ${e.createdBy}):`,'');
    if(note===null)return;
    if(reviewExpense(user,e,'rejected',note.trim())){toast.info('Expense rejected');setDetail(null);}
  };
  const approveSelected=()=>{
    if(!selList.length)return;
    const items=selList.map(id=>xpMap(XP_KEY)[id]).filter(e=>e&&e.status==='pending');
    if(!window.confirm(`Approve ${items.length} expense${items.length>1?'s':''} totalling ${fmt(sumTotal(items))}?`))return;
    items.forEach(e=>reviewExpense(user,e,'approved'));
    setSel([]);toast.success(`${items.length} expense${items.length>1?'s':''} approved`);
  };
  const remove=e=>{
    if(!isSuper){toast.error('Only a Super Admin can delete expenses.');return;}
    if(!window.confirm(`Delete ${e.expNo} — ${e.title} (${fmt(e.total)}) permanently?${e.status==='approved'?'\n\nIt is approved, so deleting it will reduce the expenses in the books.':''}`))return;
    xpDel(XP_KEY,e.id,expDeltas(e,null));setDetail(null);setSel(s=>s.filter(x=>x!==e.id));toast.info('Expense deleted');
  };

  const actionBtns=(e,withRepeat)=>(
    <div className="xp-actions">
      <button className="btn btn-sm btn-outline" title="View details" onClick={()=>setDetail(e)}><Ic n="eye" s={12}/></button>
      {withRepeat&&<button className="btn btn-sm btn-outline" title="Repeat this expense" onClick={()=>repeat(e)}><Ic n="refresh" s={12}/></button>}
      {isSuper&&e.status==='pending'&&<>
        <button className="btn btn-sm btn-success" title="Approve" onClick={()=>approve(e)}><Ic n="check" s={12}/></button>
        <button className="btn btn-sm btn-outline" title="Reject" style={{color:'var(--warn)'}} onClick={()=>reject(e)}><Ic n="close" s={12}/></button>
      </>}
      {isSuper&&<button className="btn btn-sm btn-outline" title="Edit" onClick={()=>startEdit(e)}><Ic n="edit" s={12}/></button>}
      {isSuper&&<button className="btn btn-sm btn-outline" title="Delete" style={{color:'var(--red)'}} onClick={()=>remove(e)}><Ic n="trash" s={12}/></button>}
    </div>
  );
  const reviewTxt=e=>(e.status!=='pending'&&e.reviewedBy)?<div className="xp-sub2">by {e.reviewedBy} · {fmtD((e.reviewedAt||'').slice(0,10))}</div>:null;
  const pickBox=e=>isSuper&&e.status==='pending'
    ?<input type="checkbox" checked={sel.includes(e.id)} onChange={ev=>setSel(s=>ev.target.checked?[...s,e.id]:s.filter(x=>x!==e.id))}/>:null;

  const cards=isSuper?[
    {lbl:'Total Expenses',val:fmt(xt.approvedTotal),sub:`${xt.approvedN} approved`,c:'var(--danger-bg)',ic:'var(--red)'},
    {lbl:'This Month',val:fmt(xt.month(monthKey)),sub:'Approved, this month',c:'var(--primary-bg)',ic:'var(--primary2)'},
    {lbl:'Pending Approval',val:xt.pendingN,sub:fmt(xt.pendingTotal)+' waiting',c:'var(--warn-bg)',ic:'var(--warn)',go:'pending'},
    {lbl:'Rejected',val:rejectedL.length,sub:'Not in the books',c:'var(--card3)',ic:'var(--text2)',go:'rejected'},
  ]:[
    {lbl:'My Expenses',val:base.length,sub:'Recorded by me',c:'var(--primary-bg)',ic:'var(--primary2)',go:'all'},
    {lbl:'Pending',val:pendingL.length,sub:'Waiting for approval',c:'var(--warn-bg)',ic:'var(--warn)',go:'pending'},
    {lbl:'Approved',val:approvedL.length,sub:'Added to the books',c:'var(--success-bg)',ic:'var(--green)',go:'approved'},
    {lbl:'Rejected',val:rejectedL.length,sub:'See the reason inside',c:'var(--danger-bg)',ic:'var(--red)',go:'rejected'},
  ];

  return(
    <div className="page-enter">
      <div className="page-hdr">
        <div>
          <div className="page-title">Expenses</div>
          <div className="page-sub">{isSuper?'Record, approve and track every gym expense':'Record gym expenses and track their approval'}</div>
        </div>
        <button className="btn btn-primary" onClick={()=>showForm?(setShowForm(false),setEditId(null)):openNew()}>
          <Ic n="plus" s={14}/>{showForm?'Cancel':'Add Expense'}
        </button>
      </div>

      <div className="g4" style={{marginBottom:16}}>
        {cards.map(({lbl,val,sub,c,ic,go})=>(
          <div key={lbl} className="card stat-card" style={go?{cursor:'pointer'}:null} onClick={()=>go&&(setStatusF(go),setSel([]))}>
            <div><p className="lbl">{lbl}</p><p className="val">{val}</p><p className="sub">{sub}</p></div>
            <div className="stat-icon" style={{background:c,color:ic}}><Ic n={lbl==='Pending Approval'||lbl==='Pending'?'alert':lbl==='Approved'?'check':'wallet'} s={20}/></div>
          </div>
        ))}
      </div>

      {showForm&&<div className="card" style={{marginBottom:16}}>
        <div className="section-title" style={{marginBottom:14}}><Ic n="wallet" s={15}/>{editId?'Edit Expense':'New Expense'}</div>
        <div className="g3" style={{marginBottom:0}}>
          <div className="field"><label className="field-label">Expense Date *</label>
            <input className="field-input" type="date" max={today()} value={form.date} onChange={e=>f('date',e.target.value)}/></div>
          <div className="field"><label className="field-label">Category *</label>
            <select className="field-input" value={form.category} onChange={e=>f('category',e.target.value)}>
              <option value="">Select category…</option>
              {EXPENSE_CATEGORIES.map(c=><option key={c}>{c}</option>)}
            </select></div>
          <div className="field"><label className="field-label">Recurring?</label>
            <select className="field-input" value={form.recurring} onChange={e=>f('recurring',e.target.value)}>
              {EXPENSE_RECUR.map(c=><option key={c}>{c}</option>)}
            </select></div>
        </div>
        <div className="g2" style={{marginBottom:0}}>
          <div className="field"><label className="field-label">Description *</label>
            <input className="field-input" value={form.title} onChange={e=>f('title',e.target.value)} placeholder="e.g. October gym rent, treadmill belt replacement"/></div>
          <div className="field"><label className="field-label">Vendor / Paid To</label>
            <input className="field-input" value={form.vendor} onChange={e=>f('vendor',e.target.value)} placeholder="Shop, landlord, service provider…"/></div>
        </div>
        <div className="g3" style={{marginBottom:0}}>
          <div className="field"><label className="field-label">Amount before GST (₹) *</label>
            <input className="field-input" type="number" min="0" step="0.01" value={form.amount} onChange={e=>f('amount',e.target.value)} placeholder="0.00"/></div>
          <div className="field"><label className="field-label">GST on the bill</label>
            <select className="field-input" value={form.gstRate} onChange={e=>f('gstRate',e.target.value)}>
              {EXPENSE_GST_RATES.map(r=><option key={r} value={r}>{r===0?'No GST':r+'% GST'}</option>)}
            </select></div>
          <div className="field"><label className="field-label">Total Paid</label>
            <div className="field-input" style={{display:'flex',justifyContent:'space-between',fontWeight:700,background:'var(--card3)'}}>
              <span style={{color:'var(--text3)',fontWeight:500,fontSize:12}}>{calc.gstAmount>0?`incl. ${fmt(calc.gstAmount)} GST`:'no GST'}</span>
              <span style={{color:'var(--red)'}}>{fmt(calc.total)}</span>
            </div></div>
        </div>
        <div className="g3" style={{marginBottom:0}}>
          <div className="field"><label className="field-label">Payment Mode *</label>
            <select className="field-input" value={form.paymentMode} onChange={e=>setForm(p=>({...p,paymentMode:e.target.value,paymentRef:''}))}>
              {EXPENSE_PAYMODES.map(m=><option key={m}>{m}</option>)}
            </select></div>
          {needsPaymentRef(form.paymentMode)&&<div className="field"><label className="field-label">{PAYMENT_REF_MODES[form.paymentMode].label}</label>
            <input className="field-input" value={form.paymentRef} onChange={e=>f('paymentRef',e.target.value)} placeholder={PAYMENT_REF_MODES[form.paymentMode].ph}/></div>}
          <div className="field"><label className="field-label">Paid From</label>
            <select className="field-input" value={form.paidFrom} onChange={e=>f('paidFrom',e.target.value)}>
              {EXPENSE_PAID_FROM.map(m=><option key={m}>{m}</option>)}
            </select></div>
          <div className="field"><label className="field-label">Bill / Invoice No.</label>
            <input className="field-input" value={form.billNo} onChange={e=>f('billNo',e.target.value)} placeholder="Number printed on the vendor's bill"/></div>
        </div>
        <div className="g2" style={{marginBottom:0}}>
          <div className="field"><label className="field-label">Notes</label>
            <textarea className="field-input" rows={3} value={form.notes} onChange={e=>f('notes',e.target.value)} placeholder="Anything the approver should know"/></div>
          <div className="field"><label className="field-label">Bill / Receipt photo (optional)</label>
            {form.bill
              ?<div style={{display:'flex',gap:12,alignItems:'center'}}>
                  <img src={form.bill} alt="Bill" className="bill-thumb"/>
                  <button className="btn btn-sm btn-outline" style={{color:'var(--red)'}} onClick={()=>setForm(p=>({...p,bill:'',billChanged:true,hadBill:false}))}><Ic n="trash" s={12}/>Remove</button>
                </div>
              :(form.hadBill&&!form.billChanged)
              ?<div className="muted">Loading the attached bill…</div>
              :<label className="btn btn-outline" style={{cursor:'pointer',width:'fit-content'}}>
                  <Ic n="upload" s={13}/>Attach photo
                  <input type="file" accept="image/*" onChange={pickBill} style={{display:'none'}}/>
                </label>}
            <div style={{fontSize:11,color:'var(--text3)',marginTop:6}}>Photos are compressed automatically.</div>
          </div>
        </div>
        {isSuper&&!editId&&<label style={{display:'flex',gap:8,alignItems:'center',fontSize:13,color:'var(--text2)',marginBottom:14,cursor:'pointer'}}>
          <input type="checkbox" checked={form.markApproved} onChange={e=>f('markApproved',e.target.checked)}/>
          Approve immediately and add to the books (untick to keep it pending)
        </label>}
        {!isSuper&&<div style={{fontSize:12.5,color:'var(--text3)',marginBottom:14}}>
          This will be sent to a Super Admin. It is added to the books only after they approve it, and you will get a notification.</div>}
        <div style={{display:'flex',gap:8}}>
          <button className="btn btn-primary" onClick={save}><Ic n="check" s={13}/>{editId?'Update Expense':(isSuper&&form.markApproved?'Save Expense':'Submit for Approval')}</button>
          <button className="btn btn-outline" onClick={()=>{setShowForm(false);setEditId(null);}}>Cancel</button>
        </div>
      </div>}

      <div className="card" style={{marginBottom:16}}>
        <div className="pill-tabs" style={{flexWrap:'wrap',marginBottom:12}}>
          {[['all','All',base.length],['pending','Pending',pendingL.length],['approved','Approved',approvedL.length],['rejected','Rejected',rejectedL.length]].map(([k,l,n])=>(
            <button key={k} className={`pill-tab ${statusF===k?'active':''}`} onClick={()=>{setStatusF(k);setSel([]);}}>{l} ({n})</button>))}
        </div>
        <div className="xp-filters">
          <div className="field xp-search" style={{margin:0}}><label className="field-label">Search</label>
            <input className="field-input" value={q} onChange={e=>setQ(e.target.value)} placeholder="Description, vendor, bill no…"/></div>
          <div className="field" style={{margin:0}}><label className="field-label">Category</label>
            <select className="field-input" value={catF} onChange={e=>setCatF(e.target.value)}>
              <option value="">All</option>{EXPENSE_CATEGORIES.map(c=><option key={c}>{c}</option>)}</select></div>
          {isSuper&&<div className="field" style={{margin:0}}><label className="field-label">Submitted by</label>
            <select className="field-input" value={byF} onChange={e=>setByF(e.target.value)}>
              <option value="">Everyone</option>{submitters.map(([id,n])=><option key={id} value={id}>{n}</option>)}</select></div>}
          <div className="field" style={{margin:0}}><label className="field-label">From</label>
            <input className="field-input" type="date" value={from} onChange={e=>setFrom(e.target.value)}/></div>
          <div className="field" style={{margin:0}}><label className="field-label">To</label>
            <input className="field-input" type="date" value={to} onChange={e=>setTo(e.target.value)}/></div>
          {(q||catF||byF||from||to)&&<button className="btn btn-outline" onClick={()=>{setQ('');setCatF('');setByF('');setFrom('');setTo('');}}>Clear</button>}
        </div>
      </div>

      {!complete&&<div className="card win-note">
        <div style={{fontSize:12.5,color:'var(--text2)'}}>
          Showing expenses recorded since <strong>{fmtD(xpWindowDate())}</strong> (last {EXP_WINDOW_DAYS} days) so this page stays fast.
          {isSuper&&xt.pendingN>pendingL.length&&<span style={{color:'var(--warn)'}}> {xt.pendingN-pendingL.length} older pending expense{xt.pendingN-pendingL.length>1?'s are':' is'} not shown yet.</span>}
        </div>
        <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
          <button className="btn btn-sm btn-outline" disabled={olderBusy} onClick={()=>loadOlder(false)}>{olderBusy?'Loading…':`Load older ${EXP_WINDOW_DAYS} days`}</button>
          <button className="btn btn-sm btn-outline" disabled={olderBusy} onClick={()=>loadOlder(true)}>Load all</button>
        </div>
      </div>}

      {isSuper&&selList.length>0&&<div className="card" style={{marginBottom:16,display:'flex',gap:12,alignItems:'center',justifyContent:'space-between',flexWrap:'wrap'}}>
        <div style={{fontSize:13}}><strong>{selList.length}</strong> pending expense{selList.length>1?'s':''} selected · {fmt(sumTotal(selList.map(id=>xpMap(XP_KEY)[id]).filter(Boolean)))}</div>
        <button className="btn btn-success" onClick={approveSelected}><Ic n="check" s={13}/>Approve selected</button>
      </div>}

      <div className="card">
        {asCards
          ?<div className="xp-list">
            {isSuper&&selectable.length>0&&<label style={{display:'flex',gap:8,alignItems:'center',fontSize:12.5,color:'var(--text2)',cursor:'pointer'}}>
              <input type="checkbox" checked={selList.length===selectable.length} onChange={e=>setSel(e.target.checked?selectable:[])}/>
              Select all pending ({selectable.length})
            </label>}
            {list.length===0
              ?<div className="tbl-empty">{base.length===0?'No expenses recorded yet — tap “Add Expense”.':'No expenses match these filters'}</div>
              :list.map(e=>(
              <div key={e.id} className="xp-item">
                <div className="xp-item-top">
                  <div style={{minWidth:0,flex:1}}>
                    <div className="xp-title" onClick={()=>setDetail(e)}>{e.title}</div>
                    <div className="xp-sub">{e.expNo}{e.vendor?` · ${e.vendor}`:''}{(e.bill||e.hasBill)?' · 📎':''}</div>
                  </div>
                  <div className="xp-amt">{fmt(e.total)}{e.gstAmount>0&&<small>GST {fmt(e.gstAmount)}</small>}</div>
                </div>
                <div className="xp-meta">
                  <span>{fmtD(e.date)}</span><span>{e.category}</span><span>{e.paymentMode}</span>
                  {isSuper&&<span>{e.createdBy} · {timeAgo(e.createdAt)}</span>}
                </div>
                <div className="xp-foot">
                  <div style={{display:'flex',gap:10,alignItems:'center'}}>{pickBox(e)}<div><StatusBadge e={e}/>{reviewTxt(e)}</div></div>
                  {actionBtns(e,true)}
                </div>
              </div>))}
          </div>
          :<div className="tbl-wrap"><table className="xp-table">
          <thead><tr>
            {isSuper&&<th style={{width:34}}><input type="checkbox" checked={selectable.length>0&&selList.length===selectable.length}
              onChange={e=>setSel(e.target.checked?selectable:[])}/></th>}
            <th>Expense</th><th>Date</th><th style={{textAlign:'right'}}>Total</th><th>Payment</th>
            {isSuper&&<th>Submitted by</th>}<th>Status</th><th>Actions</th>
          </tr></thead>
          <tbody>
            {list.length===0
              ?<tr><td colSpan={isSuper?8:6} className="tbl-empty">{base.length===0?'No expenses recorded yet — click “Add Expense”.':'No expenses match these filters'}</td></tr>
              :list.map(e=>(
              <tr key={e.id}>
                {isSuper&&<td>{pickBox(e)}</td>}
                <td><div className="xp-cell"><div className="xp-title" onClick={()=>setDetail(e)}>{e.title}</div>
                  <div className="xp-sub">{e.expNo}{e.vendor?` · ${e.vendor}`:''}{(e.bill||e.hasBill)?' · 📎':''}</div>
                  <div className="xp-sub2">{e.category}{e.recurring&&e.recurring!=='One-time'?` · ${e.recurring}`:''}</div></div></td>
                <td style={{whiteSpace:'nowrap'}}>{fmtD(e.date)}</td>
                <td style={{textAlign:'right',fontWeight:700,whiteSpace:'nowrap'}}>{fmt(e.total)}{e.gstAmount>0&&<div className="xp-sub2" style={{fontWeight:500}}>GST {fmt(e.gstAmount)}</div>}</td>
                <td>{e.paymentMode}</td>
                {isSuper&&<td>{e.createdBy}<div className="xp-sub2">{timeAgo(e.createdAt)}</div></td>}
                <td><StatusBadge e={e}/>{reviewTxt(e)}</td>
                <td>{actionBtns(e,false)}</td>
              </tr>))}
          </tbody>
        </table></div>}
        {list.length>0&&<div style={{display:'flex',justifyContent:'space-between',padding:'12px 4px 0',fontSize:12.5,color:'var(--text3)',flexWrap:'wrap',gap:8}}>
          <span>{list.length} expense{list.length>1?'s':''} shown</span>
          <span>Total shown: <strong style={{color:'var(--text)'}}>{fmt(sumTotal(list))}</strong></span>
        </div>}
      </div>

      {detail&&(()=>{
        const e=xpMap(XP_KEY)[detail.id]||detail;
        const row=(l,v)=>v||v===0?<div className="xd-row"><span>{l}</span><strong>{v}</strong></div>:null;
        return(
        <div className="overlay" onClick={()=>setDetail(null)}>
          <div className="modal" style={{maxWidth:560}} onClick={ev=>ev.stopPropagation()}>
            <div className="modal-hdr" style={{gap:12}}><div style={{minWidth:0}}><div className="modal-title" style={{wordBreak:"break-word"}}>{e.title}</div>
              <div style={{fontSize:11.5,color:'var(--text3)',marginTop:2}}>{e.expNo}</div></div>
              <div style={{display:'flex',gap:10,alignItems:'center',flexShrink:0}}><StatusBadge e={e}/>
              <button className="close-btn" onClick={()=>setDetail(null)}>×</button></div></div>
            <div className="modal-body">
              {row('Date',fmtD(e.date))}{row('Category',e.category)}{row('Vendor / Paid to',e.vendor)}
              {row('Bill / Invoice no.',e.billNo)}{row('Amount before GST',fmt(e.amount))}
              {e.gstRate>0&&row(`GST (${e.gstRate}%)`,fmt(e.gstAmount))}
              <div className="xd-row" style={{fontSize:15}}><span>Total paid</span><strong style={{color:'var(--red)'}}>{fmt(e.total)}</strong></div>
              {row('Payment mode',e.paymentMode)}{row('Payment reference',e.paymentRef)}{row('Paid from',e.paidFrom)}
              {row('Recurring',e.recurring)}{row('Notes',e.notes)}
              {row('Submitted by',`${e.createdBy} · ${timeAgo(e.createdAt)}`)}
              {e.status!=='pending'&&row(e.status==='approved'?'Approved by':'Rejected by',`${e.reviewedBy||'—'} · ${fmtD((e.reviewedAt||'').slice(0,10))}`)}
              {e.status==='rejected'&&row('Reason',e.reviewNote||'No reason given')}
              {e.editedBy&&row('Last edited by',e.editedBy)}
              <BillView e={e}/>
            </div>
            <div className="modal-ftr">
              <button className="btn btn-outline" onClick={()=>repeat(e)}><Ic n="refresh" s={13}/>Repeat</button>
              {isSuper&&e.status==='pending'&&<>
                <button className="btn btn-outline" style={{color:'var(--warn)'}} onClick={()=>reject(e)}><Ic n="close" s={13}/>Reject</button>
                <button className="btn btn-success" onClick={()=>approve(e)}><Ic n="check" s={13}/>Approve</button></>}
              {isSuper&&<button className="btn btn-outline" style={{color:'var(--red)'}} onClick={()=>remove(e)}><Ic n="trash" s={13}/>Delete</button>}
            </div>
          </div>
        </div>);})()}
    </div>
  );
};

const Dashboard=({user})=>{
  useXp();
  const canSeeFinance=user.role==='superadmin';
  const members=S.get(SK.MEMBERS,[])||[];
  const invSum=InvDB.summary();           // all-time figures from running per-month totals (no need to load every invoice)
  const settings=S.get(SK.SETTINGS,{})||{};
  const revenue=invSum.total;
  const active=members.filter(m=>m.status==='active');
  const expired=members.filter(m=>m.status==='expired');
  const t=today();
  const in7=new Date();in7.setDate(in7.getDate()+7);
  const expiring=members.filter(m=>{
    if(!m.expiryDate||m.status==='expired')return false;
    const d=new Date(m.expiryDate);return d>=new Date()&&d<=in7;
  });
  const thisMonth=new Date().toISOString().slice(0,7);
  const monthRevenue=invSum.month(thisMonth).total;
  const newThisMonth=members.filter(m=>m.startDate&&m.startDate.startsWith(thisMonth)).length;

  // Expenses — only Super-Admin-approved expenses count in the books
  const xt=xpTotals();                      // all-time + per-month approved / pending totals
  const xpAllL=xpList(XP_KEY);              // the recent window (used for "my expenses" lists)
  const totalExp=xt.approvedTotal;
  const monthExp=xt.month(thisMonth);
  const pendingExpAmt=xt.pendingTotal;
  const myExp=xpAllL.filter(e=>e.createdById===user.id).sort(expSort);
  const catEntries=Object.entries(xt.cats(thisMonth)).map(([k,v])=>[catLabel(k),v]).filter(x=>x[1]>0).sort((a,b)=>b[1]-a[1]);
  const xpSig=xt.sig;
  const expChartRef=useRef(null), expChartInst=useRef(null);
  const catChartRef=useRef(null), catChartInst=useRef(null);

  const revChartRef=useRef(null), revChartInst=useRef(null);
  const planChartRef=useRef(null), planChartInst=useRef(null);
  const signupChartRef=useRef(null), signupChartInst=useRef(null);
  const paymentChartRef=useRef(null), paymentChartInst=useRef(null);

  const chartColors=['#6366F1','#0D9488','#D97706','#DC2626','#16A34A','#2563EB','#7C3AED','#DB2777'];

  // Revenue trend (superadmin only — this is the one chart showing ₹ amounts)
  useEffect(()=>{
    if(!canSeeFinance||!revChartRef.current)return;
    if(typeof Chart==='undefined'){console.warn('Chart.js not loaded — skipping revenue chart');return;}
    try{
      if(revChartInst.current)revChartInst.current.destroy();
      const months=[];const labels=[];
      for(let i=5;i>=0;i--){
        const d=new Date();d.setMonth(d.getMonth()-i);
        const m=d.toISOString().slice(0,7);
        months.push(m);labels.push(d.toLocaleString('en',{month:'short'}));
      }
      const data=months.map(m=>invSum.month(m).total);
      revChartInst.current=new Chart(revChartRef.current,{
        type:'line',
        data:{labels,datasets:[{data,borderColor:'#6366F1',backgroundColor:'rgba(99,102,241,0.1)',
          fill:true,tension:0.4,pointRadius:3,pointBackgroundColor:'#6366F1'}]},
        options:{responsive:true,maintainAspectRatio:false,
          plugins:{legend:{display:false}},
          scales:{x:{grid:{display:false},ticks:{color:'#6E7681',font:{size:11}}},
            y:{grid:{color:'rgba(110,118,129,0.1)'},ticks:{color:'#6E7681',font:{size:11}}}}}
      });
    }catch(e){ console.warn('Chart render skipped:',e.message); }
    return()=>revChartInst.current?.destroy();
  },[invSum.sig,canSeeFinance]);

  // Members by plan — operational, not financial, so visible to every role
  useEffect(()=>{
    if(!planChartRef.current)return;
    if(typeof Chart==='undefined')return;
    try{
      if(planChartInst.current)planChartInst.current.destroy();
      const counts={};
      active.forEach(m=>{const k=m.planName||'Unassigned';counts[k]=(counts[k]||0)+1;});
      const labels=Object.keys(counts);
      const data=Object.values(counts);
      planChartInst.current=new Chart(planChartRef.current,{
        type:'bar',
        data:{labels,datasets:[{data,backgroundColor:labels.map((_,i)=>chartColors[i%chartColors.length]),borderRadius:6,maxBarThickness:36}]},
        options:{responsive:true,maintainAspectRatio:false,
          plugins:{legend:{display:false}},
          scales:{x:{grid:{display:false},ticks:{color:'#6E7681',font:{size:11}}},
            y:{grid:{color:'rgba(110,118,129,0.1)'},ticks:{color:'#6E7681',font:{size:11},precision:0}}}}
      });
    }catch(e){ console.warn('Chart render skipped:',e.message); }
    return()=>planChartInst.current?.destroy();
  },[members]);

  // New signups per month — growth indicator, not a ₹ figure
  useEffect(()=>{
    if(!signupChartRef.current)return;
    if(typeof Chart==='undefined')return;
    try{
      if(signupChartInst.current)signupChartInst.current.destroy();
      const months=[];const labels=[];
      for(let i=5;i>=0;i--){
        const d=new Date();d.setMonth(d.getMonth()-i);
        const m=d.toISOString().slice(0,7);
        months.push(m);labels.push(d.toLocaleString('en',{month:'short'}));
      }
      const data=months.map(m=>members.filter(x=>x.startDate&&x.startDate.startsWith(m)).length);
      signupChartInst.current=new Chart(signupChartRef.current,{
        type:'bar',
        data:{labels,datasets:[{data,backgroundColor:'#0D9488',borderRadius:6,maxBarThickness:32}]},
        options:{responsive:true,maintainAspectRatio:false,
          plugins:{legend:{display:false}},
          scales:{x:{grid:{display:false},ticks:{color:'#6E7681',font:{size:11}}},
            y:{grid:{color:'rgba(110,118,129,0.1)'},ticks:{color:'#6E7681',font:{size:11},precision:0}}}}
      });
    }catch(e){ console.warn('Chart render skipped:',e.message); }
    return()=>signupChartInst.current?.destroy();
  },[members]);

  // Payment mode split — counts of invoices per mode, no ₹ amounts shown
  useEffect(()=>{
    if(!paymentChartRef.current)return;
    if(typeof Chart==='undefined')return;
    try{
      if(paymentChartInst.current)paymentChartInst.current.destroy();
      const counts={};
      Object.entries(invSum.modes).forEach(([k,c])=>{if(c>0)counts[k]=c;});
      const labels=Object.keys(counts);
      const data=Object.values(counts);
      paymentChartInst.current=new Chart(paymentChartRef.current,{
        type:'doughnut',
        data:{labels,datasets:[{data,backgroundColor:labels.map((_,i)=>chartColors[i%chartColors.length]),borderWidth:0}]},
        options:{responsive:true,maintainAspectRatio:false,cutout:'65%',
          plugins:{legend:{position:'bottom',labels:{color:'#8B949E',font:{size:11},boxWidth:10,padding:12}}}}
      });
    }catch(e){ console.warn('Chart render skipped:',e.message); }
    return()=>paymentChartInst.current?.destroy();
  },[invSum.sig]);

  // Revenue vs approved expenses (superadmin)
  useEffect(()=>{
    if(!canSeeFinance||!expChartRef.current||typeof Chart==='undefined')return;
    try{
      if(expChartInst.current)expChartInst.current.destroy();
      const months=[],labels=[];
      for(let i=5;i>=0;i--){const d=new Date();d.setMonth(d.getMonth()-i);months.push(d.toISOString().slice(0,7));labels.push(d.toLocaleString('en',{month:'short'}));}
      const rev=months.map(m=>invSum.month(m).total);
      const exp=months.map(m=>xt.month(m));
      expChartInst.current=new Chart(expChartRef.current,{
        type:'bar',
        data:{labels,datasets:[
          {label:'Revenue',data:rev,backgroundColor:'#16A34A',borderRadius:5,maxBarThickness:20},
          {label:'Expenses',data:exp,backgroundColor:'#DC2626',borderRadius:5,maxBarThickness:20}]},
        options:{responsive:true,maintainAspectRatio:false,
          plugins:{legend:{position:'bottom',labels:{color:'#8B949E',font:{size:11},boxWidth:10,padding:12}}},
          scales:{x:{grid:{display:false},ticks:{color:'#6E7681',font:{size:11}}},
            y:{grid:{color:'rgba(110,118,129,0.1)'},ticks:{color:'#6E7681',font:{size:11}}}}}
      });
    }catch(e){ console.warn('Chart render skipped:',e.message); }
    return()=>expChartInst.current?.destroy();
  },[invSum.sig,xpSig,canSeeFinance]);

  // This month's approved expenses by category (superadmin)
  useEffect(()=>{
    if(!canSeeFinance||!catChartRef.current||typeof Chart==='undefined')return;
    try{
      if(catChartInst.current)catChartInst.current.destroy();
      catChartInst.current=new Chart(catChartRef.current,{
        type:'doughnut',
        data:{labels:catEntries.map(x=>x[0]),datasets:[{data:catEntries.map(x=>round2(x[1])),
          backgroundColor:catEntries.map((_,i)=>chartColors[i%chartColors.length]),borderWidth:0}]},
        options:{responsive:true,maintainAspectRatio:false,cutout:'62%',
          plugins:{legend:{position:'bottom',labels:{color:'#8B949E',font:{size:11},boxWidth:10,padding:10}}}}
      });
    }catch(e){ console.warn('Chart render skipped:',e.message); }
    return()=>catChartInst.current?.destroy();
  },[xpSig,canSeeFinance]);

  return(
    <div className="page-enter">
      <div className="hero">
        <div>
          <h2>Welcome back, {user.name.split(' ')[0]} 💪</h2>
          <p>Here's how Arctic Gym Management is performing today.</p>
        </div>
        <div className="hero-stats">
          {canSeeFinance&&<div className="hero-stat"><div className="hv">{fmt(revenue)}</div><div className="hl">Total Revenue</div></div>}
          {canSeeFinance&&<div className="hero-stat"><div className="hv">{fmt(totalExp)}</div><div className="hl">Total Expenses</div></div>}
          {canSeeFinance&&<div className="hero-stat"><div className="hv">{xt.pendingN}</div><div className="hl">Expenses Pending</div></div>}
          <div className="hero-stat"><div className="hv">{active.length}</div><div className="hl">Active Members</div></div>
          <div className="hero-stat"><div className="hv">{expiring.length}</div><div className="hl">Expiring Soon</div></div>
          {!canSeeFinance&&<div className="hero-stat"><div className="hv">{invSum.count}</div><div className="hl">Total Invoices</div></div>}
        </div>
      </div>

      <div className="g4" style={{marginBottom:16}}>
        {[
          canSeeFinance
            ?{lbl:'Monthly Revenue',val:fmt(monthRevenue),sub:'This month',color:'var(--primary-bg)',ico:'rupee',icoc:'var(--primary2)'}
            :{lbl:'New This Month',val:newThisMonth,sub:'New members',color:'var(--primary-bg)',ico:'users',icoc:'var(--primary2)'},
          {lbl:'Active Members',val:active.length,sub:`${expired.length} expired`,color:'var(--success-bg)',ico:'users',icoc:'var(--green)'},
          {lbl:'Expiring in 7 Days',val:expiring.length,sub:'Needs renewal',color:'var(--warn-bg)',ico:'alert',icoc:'var(--warn)'},
          {lbl:'Total Invoices',val:invSum.count,sub:'All time',color:'var(--primary-bg)',ico:'receipt',icoc:'var(--primary2)'},
        ].map(({lbl,val,sub,color,ico,icoc})=>(
          <div key={lbl} className="card stat-card">
            <div><p className="lbl">{lbl}</p><p className="val">{val}</p><p className="sub">{sub}</p></div>
            <div className="stat-icon" style={{background:color,color:icoc}}><Ic n={ico} s={20}/></div>
          </div>
        ))}
      </div>

      {canSeeFinance&&<>
        {xt.pendingN>0&&<div className="card xp-banner">
          <div style={{display:'flex',gap:12,alignItems:'center'}}>
            <div className="stat-icon" style={{background:'var(--warn-bg)',color:'var(--warn)'}}><Ic n="alert" s={20}/></div>
            <div>
              <div style={{fontWeight:700}}>{xt.pendingN} expense{xt.pendingN>1?'s':''} waiting for your approval</div>
              <div style={{fontSize:12.5,color:'var(--text3)'}}>{fmt(pendingExpAmt)} — not added to the books until you approve</div>
            </div>
          </div>
        </div>}
        <div className="g4" style={{marginBottom:16}}>
          {[
            {lbl:'Total Expenses',val:fmt(totalExp),sub:`${xt.approvedN} approved · all time`,color:'var(--danger-bg)',ico:'wallet',icoc:'var(--red)',to:'approved'},
            {lbl:'This Month Expenses',val:fmt(monthExp),sub:new Date().toLocaleString('en',{month:'long',year:'numeric'}),color:'var(--primary-bg)',ico:'wallet',icoc:'var(--primary2)',to:'approved'},
            {lbl:'Pending Approval',val:xt.pendingN,sub:`${fmt(pendingExpAmt)} waiting`,color:'var(--warn-bg)',ico:'alert',icoc:'var(--warn)',to:'pending'},
            {lbl:'Net This Month',val:fmt(monthRevenue-monthExp),sub:'Revenue − expenses',color:monthRevenue-monthExp>=0?'var(--success-bg)':'var(--danger-bg)',ico:'rupee',icoc:monthRevenue-monthExp>=0?'var(--green)':'var(--red)'},
          ].map(({lbl,val,sub,color,ico,icoc,to})=>(
            <div key={lbl} className="card stat-card">
              <div><p className="lbl">{lbl}</p><p className="val">{val}</p><p className="sub">{sub}</p></div>
              <div className="stat-icon" style={{background:color,color:icoc}}><Ic n={ico} s={20}/></div>
            </div>
          ))}
        </div>
        <div className="g2" style={{marginBottom:16}}>
          <div className="card chart-card">
            <div className="section-title" style={{marginBottom:14}}><Ic n="chart" s={16}/>Revenue vs Expenses (6 months)</div>
            <div style={{height:220}}><canvas ref={expChartRef}/></div>
          </div>
          <div className="card chart-card">
            <div className="section-title" style={{marginBottom:14}}><Ic n="wallet" s={16}/>Expenses by Category (this month)</div>
            <div style={{height:220}}>{catEntries.length===0?<div className="tbl-empty">No approved expenses this month</div>:<canvas ref={catChartRef}/>}</div>
          </div>
        </div>
      </>}

      {!canSeeFinance&&<>
        <div className="g4" style={{marginBottom:16}}>
          {[
            {lbl:'My Expenses',val:myExp.length,sub:'Recorded by me',color:'var(--primary-bg)',icoc:'var(--primary2)',to:'all',ico:'wallet'},
            {lbl:'Pending Approval',val:myExp.filter(e=>e.status==='pending').length,sub:'Waiting for a Super Admin',color:'var(--warn-bg)',icoc:'var(--warn)',to:'pending',ico:'alert'},
            {lbl:'Approved',val:myExp.filter(e=>e.status==='approved').length,sub:'Added to the books',color:'var(--success-bg)',icoc:'var(--green)',to:'approved',ico:'check'},
            {lbl:'Rejected',val:myExp.filter(e=>e.status==='rejected').length,sub:'Check the reason',color:'var(--danger-bg)',icoc:'var(--red)',to:'rejected',ico:'close'},
          ].map(({lbl,val,sub,color,icoc,to,ico})=>(
            <div key={lbl} className="card stat-card">
              <div><p className="lbl">{lbl}</p><p className="val">{val}</p><p className="sub">{sub}</p></div>
              <div className="stat-icon" style={{background:color,color:icoc}}><Ic n={ico} s={20}/></div>
            </div>
          ))}
        </div>
        <div className="card" style={{marginBottom:16}}>
          <div className="section-title" style={{marginBottom:14,justifyContent:'space-between'}}>
            <span style={{display:'flex',gap:8,alignItems:'center'}}><Ic n="wallet" s={16}/>My Recent Expenses</span>
          </div>
          {myExp.length===0
            ?<div className="tbl-empty">You haven't recorded any expenses yet</div>
            :<div className="tbl-wrap"><table>
              <thead><tr><th>Expense</th><th>Date</th><th>Amount</th><th>Status</th></tr></thead>
              <tbody>{myExp.slice(0,5).map(e=><tr key={e.id}>
                <td>{e.title}<div style={{fontSize:11,color:'var(--text3)'}}>{e.category}</div></td>
                <td>{fmtD(e.date)}</td><td style={{fontWeight:700}}>{fmt(e.total)}</td>
                <td><StatusBadge e={e}/>{e.status!=='pending'&&e.reviewedBy&&<div style={{fontSize:10.5,color:'var(--text3)',marginTop:3}}>by {e.reviewedBy}</div>}</td>
              </tr>)}</tbody>
            </table></div>}
        </div>
      </>}

      <div className="g2" style={{marginBottom:16}}>
        <div className="card chart-card">
          <div className="section-title" style={{marginBottom:14}}><Ic n="chart" s={16}/>{canSeeFinance?'Revenue Trend (6 months)':'Members by Plan'}</div>
          <div style={{height:200}}>
            {canSeeFinance?<canvas ref={revChartRef}/>:<canvas ref={planChartRef}/>}
          </div>
        </div>
        <div className="card">
          <div className="section-title" style={{marginBottom:14}}><Ic n="alert" s={16}/>Expiring This Week</div>
          {expiring.length===0
            ?<div className="tbl-empty">No memberships expiring in 7 days 🎉</div>
            :<div className="tbl-wrap"><table>
                <thead><tr><th>Member</th><th>Plan</th><th>Expiry</th><th></th></tr></thead>
                <tbody>{expiring.map(m=><tr key={m.id}>
                  <td>{m.name}</td><td>{m.planName||'—'}</td>
                  <td style={{color:'var(--warn)',fontWeight:600}}>{fmtD(m.expiryDate)}</td>
                  <td>
                    <button className="btn btn-sm btn-outline" title={m.email?'Email renewal reminder':'No email saved'} disabled={!m.email}
                      onClick={()=>mailtoRenewalReminder(m,settings)}>
                      <Ic n="mail" s={12}/>
                    </button>
                  </td>
                </tr>)}</tbody>
              </table></div>
          }
        </div>
      </div>

      <div className="g2">
        <div className="card chart-card">
          <div className="section-title" style={{marginBottom:14}}><Ic n="chart" s={16}/>New Signups (6 months)</div>
          <div style={{height:200}}><canvas ref={signupChartRef}/></div>
        </div>
        <div className="card chart-card">
          <div className="section-title" style={{marginBottom:14}}><Ic n="receipt" s={16}/>Payment Mode Split</div>
          <div style={{height:200}}>
            {invSum.count===0?<div className="tbl-empty">No invoices yet</div>:<canvas ref={paymentChartRef}/>}
          </div>
        </div>
      </div>
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   👤  MEMBERS
   ══════════════════════════════════════════════════════════ */

/* ══════════════════════════════════════════════════════════
   🪪  MEMBER CARD — opens when a row in Members is clicked
   ══════════════════════════════════════════════════════════ */
const MemberCard=({m,onClose,onEdit,onFreeze,onUnfreeze,onDelete,isAdmin,isSuper,canSeeInvoices})=>{
  const users=S.get(SK.USERS,[])||[];
  const settings=S.get(SK.SETTINGS,{})||{};
  const[invs,setInvs]=useState(null);
  useEffect(()=>{
    let alive=true;
    if(!canSeeInvoices){setInvs([]);return;}
    (async()=>{
      const local=InvDB.all().filter(i=>i.memberId===m.id);
      let all=local;
      try{
        const db=getDb();
        if(db){
          const s=await db.ref(ROOT+'/invoice_by_member/'+fbSafe(m.id)).orderByKey().limitToLast(60).once('value');
          const have=new Set(local.map(i=>InvDB.keyOf(i)));
          const miss=Object.keys(s.val()||{}).filter(k=>!have.has(k));
          const got=await Promise.all(miss.map(k=>db.ref(ROOT+'/invoices/'+k).once('value').then(x=>x.val()).catch(()=>null)));
          all=[...local,...got.filter(Boolean)];
        }
      }catch(e){}
      if(alive)setInvs(all.sort((a,b)=>(b.date||'').localeCompare(a.date||'')));
    })();
    return()=>{alive=false;};
  },[m.id,canSeeInvoices]);

  const t0=new Date(today()).getTime(),DAY=86400000;
  const left=m.expiryDate?Math.round((new Date(m.expiryDate).getTime()-t0)/DAY):null;
  const span=m.startDate&&m.expiryDate?Math.max(1,Math.round((new Date(m.expiryDate)-new Date(m.startDate))/DAY)):null;
  const used=span&&m.startDate?Math.min(100,Math.max(0,Math.round(((t0-new Date(m.startDate).getTime())/DAY)/span*100))):null;
  const col=m.status==='frozen'?'var(--blue)':left!==null&&left<0?'var(--red)':left!==null&&left<=7?'var(--warn)':'var(--green)';
  const paid=(invs||[]).reduce((s,i)=>s+(i.total||0),0);
  const who=id=>{const u=users.find(x=>x.uid===id||x.id===id);return u?u.name:(id&&id!=='migration'?id:'')||'—';};
  const when=ts=>ts?new Date(ts).toLocaleString('en-IN',{day:'2-digit',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit'}):'—';
  const row=(l,v)=>v||v===0?<div className="xd-row"><span>{l}</span><strong style={{textAlign:'right',wordBreak:'break-word'}}>{v}</strong></div>:null;
  const digits=String(m.phone||'').replace(/\D/g,'');
  const wa=digits?`https://wa.me/${digits.length===10?'91'+digits:digits}?text=${encodeURIComponent('Hi '+(m.name||'')+', ')}`:'';
  const KNOWN=['id','name','email','phone','address','planId','planName','trainerId','trainerName','startDate','expiryDate','status','freezeUntil','note','deleted'];
  const extra=Object.entries(m).filter(([k,v])=>!KNOWN.includes(k)&&!k.startsWith('_')&&v!==''&&v!==null&&typeof v!=='object');
  const initials=(m.name||'?').split(/\s+/).map(w=>w[0]).slice(0,2).join('').toUpperCase();
  const box={background:'var(--card2)',border:'1px solid var(--border)',borderRadius:12,padding:'12px 14px'};
  return(
    <div className="overlay" onClick={onClose}>
      <div className="modal" style={{maxWidth:640}} onClick={e=>e.stopPropagation()}>
        <div className="modal-hdr" style={{gap:12}}>
          <div style={{display:'flex',gap:12,alignItems:'center',minWidth:0}}>
            <div className="avatar" style={{width:44,height:44,fontSize:16,flexShrink:0}}>{initials}</div>
            <div style={{minWidth:0}}><div className="modal-title" style={{wordBreak:'break-word'}}>{m.name}</div>
              <div style={{fontSize:11.5,color:'var(--text3)'}}>Member ID {m.id}</div></div>
          </div>
          <div style={{display:'flex',gap:10,alignItems:'center',flexShrink:0}}>
            <span className={`badge ${m.status==='frozen'?'badge-frozen':m.status==='expired'?'badge-expired':'badge-active'}`}>{m.status||'active'}</span>
            <button className="close-btn" onClick={onClose}>×</button>
          </div>
        </div>
        <div className="modal-body">
          <div style={{...box,marginBottom:14}}>
            <div style={{display:'flex',justifyContent:'space-between',fontSize:12.5,marginBottom:6}}>
              <span style={{color:'var(--text3)'}}>Membership</span>
              <b style={{color:col}}>{m.status==='frozen'?('Frozen until '+fmtD(m.freezeUntil)):left===null?'No expiry set':left<0?('Expired '+Math.abs(left)+' day'+(Math.abs(left)===1?'':'s')+' ago'):left===0?'Expires today':(left+' day'+(left===1?'':'s')+' left')}</b>
            </div>
            {used!==null&&<div style={{height:8,borderRadius:6,background:'var(--border)',overflow:'hidden'}}><div style={{width:used+'%',height:'100%',background:col,transition:'width .3s'}}/></div>}
            <div style={{display:'flex',justifyContent:'space-between',fontSize:11.5,color:'var(--text3)',marginTop:6}}><span>{fmtD(m.startDate)}</span><span>{fmtD(m.expiryDate)}</span></div>
          </div>

          <div style={{display:'flex',gap:8,flexWrap:'wrap',marginBottom:14}}>
            {m.phone&&<a className="btn btn-sm btn-outline" href={'tel:'+m.phone}>📞 Call</a>}
            {wa&&<a className="btn btn-sm btn-outline" href={wa} target="_blank" rel="noopener noreferrer" style={{color:'#25D366'}}>💬 WhatsApp</a>}
            {m.email&&<button className="btn btn-sm btn-outline" onClick={()=>mailtoRenewalReminder(m,settings)}><Ic n="mail" s={12}/>Renewal e-mail</button>}
            {m.phone&&<button className="btn btn-sm btn-outline" onClick={()=>{try{navigator.clipboard.writeText(m.phone);toast.success('Phone copied');}catch(e){}}}>Copy phone</button>}
          </div>

          <div className="section-title" style={{margin:'4px 0 6px'}}>Contact</div>
          {row('Phone',m.phone)}{row('Email',m.email)}{row('Address',m.address)}
          {!m.phone&&!m.email&&!m.address&&<div style={{fontSize:12.5,color:'var(--text3)'}}>No contact details saved.</div>}

          <div className="section-title" style={{margin:'16px 0 6px'}}>Membership</div>
          {row('Plan',m.planName||'—')}{row('Trainer',m.trainerName||'—')}
          {row('Start date',fmtD(m.startDate))}{row('Expiry date',fmtD(m.expiryDate))}
          {row('Status',m.status||'active')}{m.status==='frozen'&&row('Frozen until',fmtD(m.freezeUntil))}
          {row('Notes',m.note)}

          {extra.length>0&&<><div className="section-title" style={{margin:'16px 0 6px'}}>Other details</div>
            {extra.map(([k,v])=><React.Fragment key={k}>{row(k.replace(/([A-Z])/g,' $1').replace(/^./,c=>c.toUpperCase()),String(v))}</React.Fragment>)}</>}

          {canSeeInvoices&&<>
            <div className="section-title" style={{margin:'16px 0 6px',display:'flex',justifyContent:'space-between'}}>
              <span>Payments</span><span style={{fontWeight:600,fontSize:12.5,color:'var(--text3)'}}>{invs===null?'loading…':invs.length+' invoice'+(invs.length===1?'':'s')+' · '+fmt(paid)}</span></div>
            {invs!==null&&invs.length===0&&<div style={{fontSize:12.5,color:'var(--text3)'}}>No invoices found for this member.</div>}
            {invs&&invs.length>0&&<div className="tbl-wrap"><table>
              <thead><tr><th>Invoice</th><th>Date</th><th>Plan</th><th>Mode</th><th style={{textAlign:'right'}}>Total</th></tr></thead>
              <tbody>{invs.map(i=><tr key={i.id}><td>{i.number}</td><td>{fmtD(i.date)}</td><td>{i.planName}{i.ptPlanName?' + PT':''}</td><td>{i.paymentMode||'—'}</td><td style={{textAlign:'right'}}>{fmt(i.total)}</td></tr>)}</tbody>
            </table></div>}
          </>}

          <div className="section-title" style={{margin:'16px 0 6px'}}>Record</div>
          {row('Added',m._seq&&m._by!=='migration'?when(m._seq)+' · by '+who(m._by):m._seq?'Before the upgrade':'')}
          {row('Last changed',m._upd?when(m._upd)+' · by '+who(m._updBy):'')}
        </div>
        <div className="modal-ftr">
          {isAdmin&&<button className="btn btn-outline" onClick={onEdit}><Ic n="edit" s={13}/>Edit</button>}
          {isAdmin&&m.status==='frozen'&&<button className="btn btn-outline" style={{color:'var(--blue)'}} onClick={onUnfreeze}><Ic n="freeze" s={13}/>Unfreeze</button>}
          {isAdmin&&m.status!=='frozen'&&<button className="btn btn-outline" style={{color:'var(--blue)'}} onClick={onFreeze}><Ic n="freeze" s={13}/>Freeze</button>}
          {isSuper&&<button className="btn btn-outline" style={{color:'var(--red)'}} onClick={onDelete}><Ic n="trash" s={13}/>Delete</button>}
          <button className="btn btn-primary" onClick={onClose}>Close</button>
        </div>
      </div>
    </div>);
};

const Members=({user,searchSeed})=>{
  const isAdmin=user.role==='superadmin'||user.role==='admin'||user.role==='staff';
  const isSuper=user.role==='superadmin';
  const[members,setMembers]=useStoreState(SK.MEMBERS);
  const[q,setQ]=useState('');
  const[showForm,setShowForm]=useState(false);
  const[editId,setEditId]=useState(null);
  const[form,setForm]=useState({name:'',email:'',phone:'',address:'',planId:'',trainerId:'',startDate:today(),note:''});
  const[statusFilter,setStatusFilter]=useState('all');
  const[cardId,setCardId]=useState(null);       // member whose card is open
  const[shown,setShown]=useState(50);          // render the list in pages so it stays fast with thousands of members
  useEffect(()=>{setShown(50);},[q,statusFilter]);
  const plans=S.get(SK.PLANS,[])||[];
  const users=S.get(SK.USERS,[])||[];
  const trainers=users.filter(u=>u.role==='trainer');
  const settings=S.get(SK.SETTINGS,{})||{};

  // Picked up when the global topbar search sends someone here with a query already typed.
  useEffect(()=>{ if(searchSeed?.query!==undefined) setQ(searchSeed.query); },[searchSeed?.token]);

  const save=()=>{
    if(!form.name.trim()){toast.error('Name required');return;}
    const plan=plans.find(p=>p.id===form.planId);
    const expiry=plan?nextYear(form.startDate||today(),plan.durationMonths):null;
    const rec={...form,id:editId||genId(),planName:plan?.name||'',expiryDate:expiry,status:'active'};
    const trn=trainers.find(t=>t.id===form.trainerId);
    rec.trainerName=trn?.name||'';
    let all=S.get(SK.MEMBERS,[])||[];
    if(editId)all=all.map(m=>m.id===editId?rec:m);
    else all=[...all,rec];
    S.set(SK.MEMBERS,all);setMembers(all);
    setShowForm(false);setEditId(null);setForm({name:'',email:'',phone:'',address:'',planId:'',trainerId:'',startDate:today(),note:''});
    toast.success(editId?'Member updated':'Member added');
  };
  const del=id=>{
    if(!window.confirm('Delete this member?'))return;
    const all=(S.get(SK.MEMBERS,[])||[]).filter(m=>m.id!==id);
    S.set(SK.MEMBERS,all);setMembers(all);toast.info('Deleted');
  };
  const freeze=id=>{
    let all=S.get(SK.MEMBERS,[])||[];
    const m=all.find(x=>x.id===id);
    if(!m)return;
    const days=parseInt(prompt('Freeze for how many days?','30')||'0');
    if(!days)return;
    const fu=new Date();fu.setDate(fu.getDate()+days);
    all=all.map(x=>x.id===id?{...x,status:'frozen',freezeUntil:fu.toISOString().slice(0,10)}:x);
    S.set(SK.MEMBERS,all);setMembers(all);toast.success('Frozen for '+days+' days');
  };
  const unfreeze=id=>{
    const all=(S.get(SK.MEMBERS,[])||[]).map(x=>x.id===id?{...x,status:'active',freezeUntil:null}:x);
    S.set(SK.MEMBERS,all);setMembers(all);toast.success('Membership unfrozen');
  };
  const startEdit=m=>{
    setEditId(m.id);setForm({name:m.name,email:m.email||'',phone:m.phone||'',address:m.address||'',
      planId:m.planId||'',trainerId:m.trainerId||'',startDate:m.startDate||today(),note:m.note||''});
    setShowForm(true);
  };
  const filtered=members.filter(m=>{
    if(statusFilter!=='all'&&m.status!==statusFilter)return false;
    if(!q)return true;
    return m.name?.toLowerCase().includes(q.toLowerCase())||m.email?.includes(q)||m.phone?.includes(q)||m.planName?.toLowerCase().includes(q.toLowerCase());
  });
  const statusBadge=s=>{
    const cls=s==='frozen'?'badge-frozen':s==='expired'?'badge-expired':'badge-active';
    return<span className={`badge ${cls}`}>{s||'active'}</span>;
  };

  return(
    <div className="page-enter">
      <div className="page-hdr">
        <div><div className="page-title">Members</div><div className="page-sub">{members.length} total · {members.filter(m=>m.status==='active').length} active</div></div>
        {isAdmin&&<button className="btn btn-primary" onClick={()=>{setShowForm(!showForm);setEditId(null);setForm({name:'',email:'',phone:'',address:'',planId:'',trainerId:'',startDate:today(),note:''});}}>
          <Ic n="plus" s={14}/>{showForm?'Cancel':'Add Member'}
        </button>}
      </div>

      {showForm&&<div className="card" style={{marginBottom:16}}>
        <div className="section-title" style={{marginBottom:16}}>{editId?'Edit Member':'New Member'}</div>
        <div className="g2">
          <div className="field"><label className="field-label">Full Name *</label><input className="field-input" value={form.name} onChange={e=>setForm(p=>({...p,name:e.target.value}))} placeholder="Member name"/></div>
          <div className="field"><label className="field-label">Email</label><input className="field-input" type="email" value={form.email} onChange={e=>setForm(p=>({...p,email:e.target.value}))} placeholder="email@example.com"/></div>
          <div className="field"><label className="field-label">Phone</label><input className="field-input" value={form.phone} onChange={e=>setForm(p=>({...p,phone:e.target.value}))} placeholder="+91 9876543210"/></div>
          <div className="field" style={{gridColumn:'1/-1'}}><label className="field-label">Address</label><input className="field-input" value={form.address||''} onChange={e=>setForm(p=>({...p,address:e.target.value}))} placeholder="Optional — used for records/reminders"/></div>
          <div className="field"><label className="field-label">Membership Plan</label>
            <select className="field-input" value={form.planId} onChange={e=>setForm(p=>({...p,planId:e.target.value}))}>
              <option value="">— Select Plan —</option>
              {plans.filter(p=>p.active!==false).map(p=><option key={p.id} value={p.id}>{p.name} ({fmt(p.price)})</option>)}
            </select>
          </div>
          <div className="field"><label className="field-label">Assign Trainer</label>
            <select className="field-input" value={form.trainerId} onChange={e=>setForm(p=>({...p,trainerId:e.target.value}))}>
              <option value="">— None —</option>
              {trainers.map(t=><option key={t.id} value={t.id}>{t.name}</option>)}
            </select>
          </div>
          <div className="field"><label className="field-label">Start Date</label><input className="field-input" type="date" value={form.startDate} onChange={e=>setForm(p=>({...p,startDate:e.target.value}))}/></div>
          <div className="field" style={{gridColumn:'1/-1'}}><label className="field-label">Notes</label><input className="field-input" value={form.note} onChange={e=>setForm(p=>({...p,note:e.target.value}))} placeholder="Optional note"/></div>
        </div>
        <div style={{display:'flex',gap:8,marginTop:4}}>
          <button className="btn btn-primary" onClick={save}><Ic n="check" s={13}/>{editId?'Update':'Save Member'}</button>
          <button className="btn btn-outline" onClick={()=>{setShowForm(false);setEditId(null);}}>Cancel</button>
        </div>
      </div>}

      <div className="card">
        <div style={{display:'flex',gap:10,marginBottom:14,flexWrap:'wrap'}}>
          <div className="search-wrap" style={{flex:1,minWidth:200}}>
            <span className="search-icon"><Ic n="search" s={14}/></span>
            <input className="field-input" value={q} onChange={e=>setQ(e.target.value)} placeholder="Search name, email, phone, plan…" style={{paddingLeft:32}}/>
          </div>
          <div style={{display:'flex',gap:4}}>
            {['all','active','expired','frozen'].map(s=>(
              <button key={s} className={`btn btn-sm ${statusFilter===s?'btn-primary':'btn-outline'}`} onClick={()=>setStatusFilter(s)}>
                {s.charAt(0).toUpperCase()+s.slice(1)}
              </button>
            ))}
          </div>
        </div>
        <div className="tbl-wrap">
          <table>
            <thead><tr>
              <th>Member</th><th>Plan</th><th>Trainer</th><th>Start</th><th>Expiry</th><th>Status</th>
              {isAdmin&&<th>Actions</th>}
            </tr></thead>
            <tbody>
              {filtered.length===0?<tr><td colSpan={isAdmin?7:6} className="tbl-empty">No members found</td></tr>
               :filtered.slice(0,shown).map(m=>(
                <tr key={m.id} onClick={()=>setCardId(m.id)} style={{cursor:'pointer'}} title="Click to open member card">
                  <td><div style={{fontWeight:600}}>{m.name}</div><div style={{fontSize:11,color:'var(--text3)'}}>{m.email||m.phone||''}</div></td>
                  <td>{m.planName||'—'}</td>
                  <td>{m.trainerName||'—'}</td>
                  <td>{fmtD(m.startDate)}</td>
                  <td style={{color:m.expiryDate&&m.expiryDate<today()?'var(--red)':'var(--text)'}}>{fmtD(m.expiryDate)}</td>
                  <td>{statusBadge(m.status)}</td>
                  {isAdmin&&<td onClick={e=>e.stopPropagation()}>
                    <div style={{display:'flex',gap:4}}>
                      <button className="btn btn-sm btn-outline" onClick={()=>startEdit(m)} title="Edit"><Ic n="edit" s={12}/></button>
                      {(m.status==='active'||m.status==='frozen')&&<button className="btn btn-sm btn-outline" title={m.email?'Email renewal reminder':'No email saved'} disabled={!m.email} onClick={()=>mailtoRenewalReminder(m,settings)}><Ic n="mail" s={12}/></button>}
                      <button className="btn btn-sm btn-outline" onClick={()=>freeze(m.id)} title="Freeze" style={{color:'var(--blue)'}}><Ic n="freeze" s={12}/></button>
                      {isSuper&&<button className="btn btn-sm btn-outline" onClick={()=>del(m.id)} style={{color:'var(--red)'}}><Ic n="trash" s={12}/></button>}
                    </div>
                  </td>}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {filtered.length>0&&<div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:10,flexWrap:'wrap',padding:'12px 4px 0',fontSize:12.5,color:'var(--text3)'}}>
          <span>Showing {Math.min(shown,filtered.length)} of {filtered.length} member{filtered.length>1?'s':''}</span>
          {filtered.length>shown&&<div style={{display:'flex',gap:8}}>
            <button className="btn btn-sm btn-outline" onClick={()=>setShown(s=>s+50)}>Show 50 more</button>
            <button className="btn btn-sm btn-outline" onClick={()=>setShown(filtered.length)}>Show all</button>
          </div>}
        </div>}
      </div>
      {cardId&&(()=>{const cm=members.find(x=>x.id===cardId);if(!cm)return null;return<MemberCard m={cm} isAdmin={isAdmin} isSuper={isSuper} canSeeInvoices={isAdmin}
        onClose={()=>setCardId(null)}
        onEdit={()=>{startEdit(cm);setCardId(null);window.scrollTo({top:0,behavior:'smooth'});}}
        onFreeze={()=>freeze(cm.id)} onUnfreeze={()=>unfreeze(cm.id)}
        onDelete={()=>{if(window.confirm('Delete this member? You can restore them from Data Safety → Recycle Bin.')){const all=(S.get(SK.MEMBERS,[])||[]).filter(x=>x.id!==cm.id);S.set(SK.MEMBERS,all);setMembers(all);setCardId(null);toast.info('Moved to Recycle Bin');}}}/>;})()}
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   🧾  INVOICES — Generate & History
   ══════════════════════════════════════════════════════════ */
/* Discount presets the superadmin's master switch unlocks on invoices. */
const DISCOUNT_OPTIONS=[5,10,15,20];
/* Single source of truth for invoice maths. Discount comes off the subtotal FIRST,
   then GST is charged on the discounted (taxable) amount — the correct order for GST. */
const calcInvoiceTotals=(subtotal,discountPct,gstOn,gstRate=18)=>{
  const pct=DISCOUNT_OPTIONS.includes(Number(discountPct))?Number(discountPct):0;
  const discountAmount=+(subtotal*pct/100).toFixed(2);
  const taxable=+(subtotal-discountAmount).toFixed(2);
  const gstAmount=gstOn?+(taxable*(gstRate/100)).toFixed(2):0;
  return{pct,discountAmount,taxable,gstAmount,total:+(taxable+gstAmount).toFixed(2)};
};

/* Dropdown you can type into: filters as you type, arrow keys + Enter, Esc to close. */
const SearchSelect=({options,value,onChange,placeholder='Search…',emptyText='No matches found',maxShown=50})=>{
  const[open,setOpen]=useState(false);
  const[term,setTerm]=useState('');
  const[hi,setHi]=useState(0);
  const wrapRef=useRef(null);
  const itemRefs=useRef({});
  const selected=options.find(o=>o.value===value)||null;
  const t=term.trim().toLowerCase();
  const digits=t.replace(/\D/g,'');
  const matches=t?options.filter(o=>o.search.includes(t)||(digits.length>=3&&o.digits.includes(digits))):options;
  const shown=matches.slice(0,maxShown);

  useEffect(()=>{
    if(!open)return;
    const onDown=e=>{if(wrapRef.current&&!wrapRef.current.contains(e.target)){setOpen(false);setTerm('');}};
    document.addEventListener('mousedown',onDown);
    document.addEventListener('touchstart',onDown);
    return()=>{document.removeEventListener('mousedown',onDown);document.removeEventListener('touchstart',onDown);};
  },[open]);
  useEffect(()=>{setHi(0);},[term]);
  useEffect(()=>{
    const el=itemRefs.current[hi];
    if(open&&el&&el.scrollIntoView)el.scrollIntoView({block:'nearest'});
  },[hi,open]);

  const choose=o=>{onChange(o.value);setOpen(false);setTerm('');};
  const onKey=e=>{
    if(e.key==='ArrowDown'){e.preventDefault();if(!open)setOpen(true);else setHi(h=>Math.min(h+1,Math.max(shown.length-1,0)));}
    else if(e.key==='ArrowUp'){e.preventDefault();setHi(h=>Math.max(h-1,0));}
    else if(e.key==='Enter'){if(open){e.preventDefault();if(shown[hi])choose(shown[hi]);}}
    else if(e.key==='Escape'||e.key==='Tab'){setOpen(false);setTerm('');}
  };

  return(
    <div className="search-wrap" ref={wrapRef} style={{maxWidth:'none'}}>
      <span className="search-icon"><Ic n="search" s={14}/></span>
      <input className="field-input" style={{paddingLeft:32,paddingRight:selected?32:12}}
        value={open?term:(selected?selected.label:'')}
        placeholder={open&&selected?selected.label:placeholder}
        onFocus={()=>setOpen(true)} onClick={()=>setOpen(true)}
        onChange={e=>{setTerm(e.target.value);setOpen(true);}}
        onKeyDown={onKey} autoComplete="off"/>
      {selected&&!open&&<button type="button" className="ss-clear" title="Clear" onClick={()=>onChange('')}><Ic n="close" s={12}/></button>}
      {open&&<div className="search-dropdown">
        {shown.length===0&&<div className="search-dropdown-empty">{emptyText}</div>}
        {shown.map((o,idx)=>(
          <div key={o.value} ref={el=>{itemRefs.current[idx]=el;}}
            className={`search-dropdown-item ${idx===hi?'ss-hi':''} ${o.value===value?'ss-sel':''}`}
            onMouseEnter={()=>setHi(idx)}
            onMouseDown={e=>{e.preventDefault();choose(o);}}>
            <div style={{minWidth:0}}>
              <div className="sdi-title">{o.label}</div>
              {o.sub&&<div className="sdi-sub">{o.sub}</div>}
            </div>
            {o.badge&&<span className={`ss-badge ${o.tone||'green'}`}>{o.badge}</span>}
          </div>
        ))}
        {matches.length>shown.length&&<div className="ss-foot">Showing {shown.length} of {matches.length} — type more to narrow down</div>}
      </div>}
    </div>
  );
};

const Invoices=({user,searchSeed})=>{
  const isAdmin=user.role==='superadmin'||user.role==='admin'||user.role==='staff';
  const isSuper=user.role==='superadmin';
  const[tab,setTab]=useState('generate');
  useXp();
  const invoices=InvDB.all();      // recent window + anything looked up on demand
  const[olderBusy,setOlderBusy]=useState(false);
  const[lookupMsg,setLookupMsg]=useState('');
  const[members,setMembers]=useStoreState(SK.MEMBERS);
  const[form,setForm]=useState({memberId:'',isNew:false,newName:'',newEmail:'',newPhone:'',newAddress:'',
    planId:'',ptPlanId:'',startDate:today(),paymentMode:'Cash',paymentRef:'',gstEnabled:false,discountPercent:0});
  const[preview,setPreview]=useState(null);
  const[q,setQ]=useState('');
  const monthStart=()=>{const d=new Date();return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-01`;};
  const[gstrFrom,setGstrFrom]=useState(monthStart());
  const[gstrTo,setGstrTo]=useState(today());
  const plans=S.get(SK.PLANS,[])||[];
  const ptPlans=S.get(SK.PTPLANS,[])||[];
  const settings=S.get(SK.SETTINGS,{})||{};
  // Gym-wide GST master switch — set by the superadmin in Gym Settings.
  // When this is off, GST can never be applied to an invoice by anyone,
  // regardless of what the per-invoice toggle below is set to.
  const gstMasterOn=settings.gstEnabled===true;
  // Gym-wide Discount master switch — same idea as GST: only a superadmin can turn it
  // on (Gym Settings). While it's off the discount dropdown is hidden and no discount
  // can be applied to an invoice, even if a value were somehow set on the form.
  const discountMasterOn=settings.discountEnabled===true;

  // Live price breakdown shown under the form so staff see the exact total before generating.
  const selPlan=plans.find(p=>p.id===form.planId);
  const selPt=form.ptPlanId?ptPlans.find(p=>p.id===form.ptPlanId):null;
  const liveSubtotal=(selPlan?.price||0)+(selPt?.price||0);
  const live=calcInvoiceTotals(liveSubtotal,discountMasterOn?form.discountPercent:0,gstMasterOn&&form.gstEnabled);

  // Options for the searchable member picker: name, phone and email are all searchable,
  // and each row shows the member's plan + whether their membership is active/expiring/expired.
  const memberOptions=members.slice().sort((a,b)=>(a.name||'').localeCompare(b.name||'')).map(m=>{
    let badge='',tone='green';
    if(m.expiryDate){
      const days=Math.ceil((new Date(m.expiryDate)-new Date(today()))/86400000);
      if(days<0){badge='Expired';tone='red';}
      else if(days<=7){badge=days===0?'Expires today':`${days}d left`;tone='warn';}
      else{badge='Active';tone='green';}
    }
    return{value:m.id,label:m.name||'(no name)',
      sub:[m.phone,m.planName].filter(Boolean).join(' · '),badge,tone,
      search:`${m.name||''} ${m.phone||''} ${m.email||''}`.toLowerCase(),
      digits:String(m.phone||'').replace(/\D/g,'')};
  });
  // Picking a member for renewal pre-fills their current plan (only if none chosen yet and it's still on offer).
  const pickMember=id=>{
    const m=members.find(x=>x.id===id);
    setForm(p=>({...p,memberId:id,
      planId:(!p.planId&&m?.planId&&plans.some(pl=>pl.id===m.planId&&pl.active!==false))?m.planId:p.planId}));
  };

  // Picked up when the global topbar search sends someone here with a query already typed.
  useEffect(()=>{
    if(searchSeed?.query!==undefined){
      setQ(searchSeed.query);
      setTab('history');
    }
  },[searchSeed?.token]);

  const generateInvoice=async()=>{
    const plan=plans.find(p=>p.id===form.planId);
    if(!plan){toast.error('Select a plan');return;}
    // UPI / Card / Bank Transfer / Cheque must carry a reference number.
    const refNeeded=needsPaymentRef(form.paymentMode);
    const payRef=(form.paymentRef||'').trim();
    if(refNeeded&&payRef.length<3){toast.error(`Enter the ${PAYMENT_REF_MODES[form.paymentMode].short} for this ${form.paymentMode} payment.`);return;}
    if(refNeeded){
      const dup=await InvDB.findByRef(form.paymentMode,payRef);   // checks ALL history, not just the loaded window
      if(dup&&!window.confirm(`Reference "${payRef}" was already used on invoice ${dup.number} (${dup.memberName}).\n\nUse it again anyway?`))return;
    }
    let invNo;
    try{invNo=await nextInvNo();}catch(e){toast.error(e.message||'Could not get an invoice number');return;}
    let memberRec;
    if(form.isNew){
      if(!form.newName.trim()){toast.error('Member name required');return;}
      const expiry=nextYear(form.startDate,plan.durationMonths);
      memberRec={id:genId(),name:form.newName,email:form.newEmail,phone:form.newPhone,address:form.newAddress||'',
        planId:plan.id,planName:plan.name,startDate:form.startDate,expiryDate:expiry,status:'active'};
      const allM=[...S.get(SK.MEMBERS,[])||[],memberRec];
      S.set(SK.MEMBERS,allM);setMembers(allM);
    } else {
      memberRec=(S.get(SK.MEMBERS,[])||[]).find(m=>m.id===form.memberId);
      if(!memberRec){toast.error('Select a member');return;}
      // Renew
      const expiry=nextYear(form.startDate,plan.durationMonths);
      const allM=(S.get(SK.MEMBERS,[])||[]).map(m=>m.id===memberRec.id?{...m,planId:plan.id,planName:plan.name,startDate:form.startDate,expiryDate:expiry,status:'active'}:m);
      S.set(SK.MEMBERS,allM);setMembers(allM);
      memberRec={...memberRec,planId:plan.id,planName:plan.name};
    }
    const pt=form.ptPlanId?ptPlans.find(p=>p.id===form.ptPlanId):null;
    const lineItems=[{name:plan.name,hsn:plan.hsn||'999723',amount:plan.price||0}];
    if(pt)lineItems.push({name:`PT — ${pt.name}`,hsn:pt.hsn||'999723',amount:pt.price||0});
    const subtotal=lineItems.reduce((s,i)=>s+i.amount,0);
    const gstRate=18;
    // GST can only ever apply if the superadmin's gym-wide master switch (Gym
    // Settings → "Enable GST on invoices") is on — this is enforced here as
    // a hard backstop regardless of what the per-invoice toggle shows, so a
    // staff member can never sneak GST onto an invoice with the switch off.
    const gstApplied=gstMasterOn&&form.gstEnabled;
    // Discount is hard-gated by the superadmin's master switch (and limited to the preset
    // percentages) here too, so it can't be applied with the switch off. Applies to both
    // existing and new members since they share this one generate path.
    const t=calcInvoiceTotals(subtotal,discountMasterOn?form.discountPercent:0,gstApplied,gstRate);
    const gstAmt=t.gstAmount;
    const total=t.total;
    const inv={id:genId(),number:invNo,date:form.startDate,
      memberId:memberRec.id,memberName:memberRec.name,memberPhone:memberRec.phone||'',
      memberEmail:memberRec.email||'',
      planId:plan.id,planName:plan.name,ptPlanId:pt?.id||null,ptPlanName:pt?.name||null,
      lineItems,subtotal,discountPercent:t.pct,discountAmount:t.discountAmount,gstEnabled:gstApplied,gstRate,gstAmount:gstAmt,total,
      paymentMode:form.paymentMode,paymentRef:refNeeded?payRef:'',raisedBy:user.name,raisedById:user.id,startDate:form.startDate,
      expiryDate:nextYear(form.startDate,plan.durationMonths)};
    InvDB.add(inv);
    setPreview(inv);
    toast.success('Invoice '+inv.number+' generated!');
    setForm(p=>({...p,discountPercent:0,paymentRef:''})); // never carry a discount over to the next invoice by accident
    // Fire-and-forget: push this member's details to the Google Sheet (if
    // configured) so the Apps Script reminder automation always has the
    // latest contact info and expiry date to work from.
    syncToGoogleSheet({
      type:'invoice',
      isNewMember:!!form.isNew,
      // Gym profile (used for the emailed invoice)
      gymName:settings.name||'',gymAddress:settings.address||'',gymGstin:settings.gstin||'',
      gymPhone:settings.phone||'',gymEmail:settings.email||'',gymTerms:settings.terms||'',
      // Invoice
      invoiceNumber:inv.number,invoiceDate:inv.date,
      memberId:inv.memberId,memberName:inv.memberName,memberEmail:inv.memberEmail||'',
      memberPhone:inv.memberPhone||'',memberAddress:memberRec.address||'',
      planName:inv.planName,ptPlanName:inv.ptPlanName||'',lineItems:inv.lineItems,
      startDate:inv.startDate,expiryDate:inv.expiryDate,
      subtotal:inv.subtotal,discountPercent:inv.discountPercent||0,discountAmount:inv.discountAmount||0,
      taxableValue:round2((inv.subtotal||0)-(inv.discountAmount||0)),
      gstEnabled:inv.gstEnabled,gstRate:inv.gstEnabled?inv.gstRate:0,gstAmount:inv.gstAmount||0,
      cgst:inv.gstEnabled?round2((inv.gstAmount||0)/2):0,sgst:inv.gstEnabled?round2((inv.gstAmount||0)-round2((inv.gstAmount||0)/2)):0,
      total:inv.total,paymentMode:inv.paymentMode,paymentRef:inv.paymentRef||'',raisedBy:inv.raisedBy
    },settings);
  };

  // Superadmin sees every invoice; everyone else only sees invoices they
  // personally raised — staff shouldn't be able to browse the whole gym's
  // billing history, just their own work. raisedById is matched first
  // (reliable), falling back to a name match for older invoices raised
  // before that field existed.
  const visibleInvoices=isSuper?invoices:invoices.filter(i=>i.raisedById===user.id||i.raisedBy===user.name);
  const filteredInv=visibleInvoices.filter(i=>!q||i.number?.toLowerCase().includes(q.trim().toLowerCase())||i.memberName?.toLowerCase().includes(q.trim().toLowerCase())||String(i.paymentRef||'').toLowerCase().includes(q.trim().toLowerCase()));
  const complete=InvDB.isComplete();
  const invTotals=InvDB.summary();

  // Search on demand: older invoices aren't loaded, so look them up (number / payment ref / member) when the person pauses typing.
  useEffect(()=>{
    const t=q.trim();
    setLookupMsg('');
    if(t.length<3||InvDB.isComplete())return;
    let alive=true;
    const h=setTimeout(async()=>{
      try{const n=await InvDB.search(t,S.get(SK.MEMBERS,[])||[]);if(alive&&n>0)setLookupMsg(`Found ${n} older invoice${n>1?'s':''} matching “${t}”.`);}catch(e){}
    },400);
    return()=>{alive=false;clearTimeout(h);};
  },[q]);
  const loadOlderInv=async all=>{setOlderBusy(true);try{await(all?InvDB.loadAll():InvDB.loadOlder());}catch(e){toast.error('Could not load older invoices: '+e.message);}setOlderBusy(false);};

  // Only the two default owner accounts (Adithya & Gym Admin) can permanently
  // delete an invoice. Every other superadmin — including ones created later
  // — never sees this option. Deleting here removes the record from storage,
  // so revenue, invoice counts and every other figure derived from invoices
  // (dashboard, reports, etc.) automatically drop to match on their next render.
  const canDeleteInvoices=isProtectedSuperAdmin(user);
  const delInvoice=id=>{
    if(!window.confirm('Delete this invoice permanently? This cannot be undone and will reduce total revenue accordingly.'))return;
    const gone=InvDB.all().find(i=>i.id===id);
    if(gone)InvDB.remove(gone);
    if(gone)syncToGoogleSheet({type:'invoice_deleted',invoiceNumber:gone.number},settings);
    toast.info('Invoice deleted');
  };

  return(
    <div className="page-enter">
      <div className="page-hdr">
        <div><div className="page-title">Invoices</div><div className="page-sub">{isSuper&&invTotals.count>0?invTotals.count:visibleInvoices.length} total{!complete&&<span> · showing {visibleInvoices.length} from the last {INV_WINDOW_DAYS} days{InvDB.windowDate()?' (since '+fmtD(InvDB.windowDate())+')':''}</span>}</div></div>
      </div>
      <div className="pill-tabs">
        {isAdmin&&<button className={`pill-tab ${tab==='generate'?'active':''}`} onClick={()=>{setTab('generate');setPreview(null);}}>Generate Invoice</button>}
        <button className={`pill-tab ${tab==='history'?'active':''}`} onClick={()=>setTab('history')}>Invoice History</button>
      </div>

      {tab==='generate'&&isAdmin&&<div className="g2">
        <div className="card">
          <div className="section-title" style={{marginBottom:16}}><Ic n="invoice" s={15}/>New Invoice</div>
          {/* Member toggle */}
          <div style={{display:'flex',gap:8,marginBottom:14}}>
            <button className={`btn btn-sm ${!form.isNew?'btn-primary':'btn-outline'}`} onClick={()=>setForm(p=>({...p,isNew:false}))}>Existing Member</button>
            <button className={`btn btn-sm ${form.isNew?'btn-primary':'btn-outline'}`} onClick={()=>setForm(p=>({...p,isNew:true}))}>New Member</button>
          </div>
          {form.isNew?<>
            <div className="field"><label className="field-label">Name *</label><input className="field-input" value={form.newName} onChange={e=>setForm(p=>({...p,newName:e.target.value}))} placeholder="Member name"/></div>
            <div className="field"><label className="field-label">Email</label><input className="field-input" value={form.newEmail} onChange={e=>setForm(p=>({...p,newEmail:e.target.value}))}/></div>
            <div className="field"><label className="field-label">Phone</label><input className="field-input" value={form.newPhone} onChange={e=>setForm(p=>({...p,newPhone:e.target.value}))}/></div>
            <div className="field"><label className="field-label">Address</label><input className="field-input" value={form.newAddress} onChange={e=>setForm(p=>({...p,newAddress:e.target.value}))} placeholder="Optional — shown on the emailed invoice"/></div>
          </>:<div className="field"><label className="field-label">Select Member *</label>
            <SearchSelect options={memberOptions} value={form.memberId} onChange={pickMember}
              placeholder={`Search by name or phone… (${members.length} members)`}
              emptyText="No member matches that search"/>
          </div>}
          <div className="field"><label className="field-label">Membership Plan *</label>
            <select className="field-input" value={form.planId} onChange={e=>setForm(p=>({...p,planId:e.target.value}))}>
              <option value="">— Choose plan —</option>
              {plans.filter(p=>p.active!==false).map(p=><option key={p.id} value={p.id}>{p.name} — {fmt(p.price)}</option>)}
            </select>
          </div>
          <div className="field"><label className="field-label">Personal Training (optional)</label>
            <select className="field-input" value={form.ptPlanId} onChange={e=>setForm(p=>({...p,ptPlanId:e.target.value}))}>
              <option value="">— None —</option>
              {ptPlans.filter(p=>p.active!==false).map(p=><option key={p.id} value={p.id}>{p.name} — {fmt(p.price)}</option>)}
            </select>
          </div>
          <div className="g2 form-g2">
            <div className="field"><label className="field-label">Start Date</label><input className="field-input" type="date" value={form.startDate} onChange={e=>setForm(p=>({...p,startDate:e.target.value}))}/></div>
            <div className="field"><label className="field-label">Payment Mode</label>
              <select className="field-input" value={form.paymentMode} onChange={e=>setForm(p=>({...p,paymentMode:e.target.value,paymentRef:''}))}>
                {['Cash','UPI','Card','Bank Transfer','Cheque'].map(m=><option key={m}>{m}</option>)}
              </select>
            </div>
          </div>
          {needsPaymentRef(form.paymentMode)&&<div className="field">
            <label className="field-label">{PAYMENT_REF_MODES[form.paymentMode].label}</label>
            <input className="field-input" value={form.paymentRef} onChange={e=>setForm(p=>({...p,paymentRef:e.target.value}))} placeholder={PAYMENT_REF_MODES[form.paymentMode].ph} autoComplete="off"/>
          </div>}
          {discountMasterOn&&<div className="field">
            <label className="field-label">Discount</label>
            <select className="field-input" value={form.discountPercent} onChange={e=>setForm(p=>({...p,discountPercent:Number(e.target.value)}))}>
              <option value={0}>No discount</option>
              {DISCOUNT_OPTIONS.map(d=><option key={d} value={d}>{d}% off</option>)}
            </select>
          </div>}
          <div className={`toggle-wrap ${gstMasterOn?'':'toggle-wrap-disabled'}`} style={{marginBottom:6}} onClick={()=>{
            if(!gstMasterOn){toast.info('GST is turned off gym-wide. A superadmin can enable it in Gym Settings.');return;}
            setForm(p=>({...p,gstEnabled:!p.gstEnabled}));
          }}>
            <div className={`toggle-sw ${gstMasterOn&&form.gstEnabled?'on':''}`}><div className="toggle-knob"/></div>
            <span style={{fontSize:13,color:'var(--text2)'}}>Include GST (18%)</span>
          </div>
          {!gstMasterOn&&<div style={{fontSize:11,color:'var(--text3)',marginBottom:14}}>GST is disabled gym-wide — only a superadmin can turn it on, in Gym Settings.</div>}
          {gstMasterOn&&<div style={{marginBottom:14}}/>}
          {selPlan&&<div className="inv-sum">
            <div className="inv-sum-row"><span>Subtotal</span><span>{fmt(liveSubtotal)}</span></div>
            {live.discountAmount>0&&<div className="inv-sum-row" style={{color:'var(--success)'}}><span>Discount ({live.pct}%)</span><span>− {fmt(live.discountAmount)}</span></div>}
            {live.gstAmount>0&&<div className="inv-sum-row"><span>GST (18%)</span><span>{fmt(live.gstAmount)}</span></div>}
            <div className="inv-sum-total"><span>Total payable</span><span>{fmt(live.total)}</span></div>
          </div>}
          <button className="btn btn-primary" onClick={generateInvoice}><Ic n="check" s={13}/>Generate Invoice</button>
        </div>

        {preview&&<div id="inv-preview">
          <div className="inv-print" style={{border:'1px solid var(--border)'}}>
            <div style={{display:'flex',justifyContent:'space-between',flexWrap:'wrap',gap:12,borderBottom:'2px solid #E7EAF3',paddingBottom:16,marginBottom:16}}>
              <div style={{display:'flex',gap:12}}>
                <div style={{width:44,height:44,borderRadius:10,background:settings.logo?'#fff':'transparent',flexShrink:0,
                  border:settings.logo?'1px solid #E7EAF3':'none',overflow:'hidden',
                  display:'flex',alignItems:'center',justifyContent:'center'}}>
                  {settings.logo
                    ?<img src={settings.logo} alt="Gym logo" style={{width:'100%',height:'100%',objectFit:'contain'}}/>
                    :<ArcticLogoMark size={44} tight/>}
                </div>
                <div>
                  <div style={{fontFamily:'Sora,sans-serif',fontWeight:800,fontSize:20,marginBottom:4}}>{settings.name||'Arctic Gym Management'}</div>
                  <div style={{fontSize:12,color:'#575F79',lineHeight:1.6}}>{settings.address||''}<br/>{settings.gstin?`GSTIN: ${settings.gstin}`:''}</div>
                </div>
              </div>
              <div style={{textAlign:'right',marginLeft:'auto'}}>
                <div style={{fontFamily:'Sora,sans-serif',fontWeight:800,fontSize:16,color:'#4338CA'}}>{preview.gstEnabled?'TAX INVOICE':'INVOICE'}</div>
                <div style={{fontSize:13,fontWeight:600,whiteSpace:'nowrap'}}>{preview.number}</div>
                <div style={{fontSize:12,color:'#575F79'}}>{fmtD(preview.date)}</div>
              </div>
            </div>
            <div style={{marginBottom:14,fontSize:13}}>
              <strong>Bill To:</strong><br/>
              {preview.memberName}<br/>
              {preview.memberPhone&&<>{preview.memberPhone}<br/></>}
              {preview.memberEmail&&<>{preview.memberEmail}<br/></>}
            </div>
            <table style={{marginBottom:16}}>
              <thead><tr style={{background:'#F4F6FB'}}>
                <th style={{padding:'8px 10px',textAlign:'left',fontSize:12}}>Description</th>
                {preview.gstEnabled&&<th style={{padding:'8px 10px',fontSize:12}}>HSN</th>}
                <th style={{padding:'8px 10px',textAlign:'right',fontSize:12}}>Amount</th>
              </tr></thead>
              <tbody>
                {preview.lineItems.map((li,i)=><tr key={i} style={{borderBottom:'1px solid #E7EAF3'}}>
                  <td style={{padding:'8px 10px',fontSize:13,color:'#12172E'}}>{li.name}</td>
                  {preview.gstEnabled&&<td style={{padding:'8px 10px',fontSize:12,color:'#575F79'}}>{li.hsn}</td>}
                  <td style={{padding:'8px 10px',textAlign:'right',fontSize:13,color:'#12172E'}}>{fmt(li.amount)}</td>
                </tr>)}
              </tbody>
            </table>
            <div style={{display:'flex',justifyContent:'flex-end',marginBottom:14}}>
              <div style={{width:'100%',maxWidth:220,fontSize:13}}>
                <div style={{display:'flex',justifyContent:'space-between',padding:'3px 0',color:'#575F79'}}><span>Subtotal</span><span>{fmt(preview.subtotal)}</span></div>
                {preview.discountAmount>0&&<div style={{display:'flex',justifyContent:'space-between',padding:'3px 0',color:'#575F79'}}><span>Discount ({preview.discountPercent}%)</span><span>− {fmt(preview.discountAmount)}</span></div>}
                {preview.gstEnabled&&<>
                  <div style={{display:'flex',justifyContent:'space-between',padding:'3px 0',color:'#575F79'}}><span>CGST (9%)</span><span>{fmt(preview.gstAmount/2)}</span></div>
                  <div style={{display:'flex',justifyContent:'space-between',padding:'3px 0',color:'#575F79'}}><span>SGST (9%)</span><span>{fmt(preview.gstAmount/2)}</span></div>
                </>}
                <div style={{display:'flex',justifyContent:'space-between',padding:'6px 0 3px',borderTop:'2px solid #E7EAF3',fontWeight:700,fontFamily:'Sora,sans-serif',fontSize:15,color:'#12172E'}}><span>Total</span><span>{fmt(preview.total)}</span></div>
              </div>
            </div>
            <div style={{fontSize:12,color:'#575F79',display:'flex',justifyContent:'space-between',marginBottom:12}}>
              <span>Payment: <strong style={{color:'#12172E'}}>{preview.paymentMode}</strong>{preview.paymentRef&&<span> · Ref: {preview.paymentRef}</span>}</span>
              <span>Raised by: {preview.raisedBy}</span>
            </div>
            <div style={{fontSize:11,color:'#8A90A6',borderTop:'1px solid #E7EAF3',paddingTop:10}}>
              Membership valid: {fmtD(preview.startDate)} → {fmtD(preview.expiryDate)}
            </div>
          </div>
          <div style={{display:'flex',gap:8,marginTop:10}}>
            <button className="btn btn-primary fw" onClick={()=>{
              try{
                downloadInvoicePDF(preview,settings);
              }catch(e){
                console.error('PDF export failed:',e);
                toast.error('Could not generate PDF: '+e.message);
              }
            }}><Ic n="download" s={13}/>Download PDF</button>
            <button className="btn btn-success fw" onClick={()=>{
              try{sendInvoiceWhatsApp(preview,settings);}
              catch(e){console.error('WhatsApp send failed:',e);toast.error('Could not open WhatsApp: '+e.message);}
            }}><Ic n="whatsapp" s={14}/>WhatsApp</button>
          </div>
        </div>}
      </div>}

      {tab==='history'&&<div className="card">
        <div style={{display:'flex',flexWrap:'wrap',gap:10,alignItems:'flex-end',marginBottom:14}}>
          <div className="field" style={{margin:0,flex:'1 1 220px'}}>
            <label className="field-label" style={{visibility:'hidden'}}>Search</label>
            <div className="search-wrap" style={{maxWidth:'none'}}>
              <span className="search-icon"><Ic n="search" s={14}/></span>
              <input className="field-input" value={q} onChange={e=>setQ(e.target.value)} placeholder="Search invoice number, member…" style={{paddingLeft:32}}/>
            </div>
          </div>
          <div className="field" style={{margin:0}}>
            <label className="field-label">From</label>
            <input className="field-input" type="date" value={gstrFrom} onChange={e=>setGstrFrom(e.target.value)}/>
          </div>
          <div className="field" style={{margin:0}}>
            <label className="field-label">To</label>
            <input className="field-input" type="date" value={gstrTo} onChange={e=>setGstrTo(e.target.value)}/>
          </div>
          {isSuper&&<button className="btn btn-outline-primary" onClick={async()=>{
            try{await InvDB.ensureFrom(gstrFrom);exportInvoicesToExcel(InvDB.all(),settings,gstrFrom,gstrTo);}
            catch(e){console.error('Excel export failed:',e);toast.error('Could not export Excel: '+e.message);}
          }}><Ic n="download" s={13}/>Export for GSTR-1</button>}
        </div>
        {(lookupMsg||!complete)&&<div className="win-note" style={{marginBottom:12}}>
          <div style={{fontSize:12.5,color:'var(--text2)'}}>
            {lookupMsg||<>Type at least 3 characters of an invoice number, payment reference or member name to search older invoices, or load them in bulk.</>}
          </div>
          {!complete&&<div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
            <button className="btn btn-sm btn-outline" disabled={olderBusy} onClick={()=>loadOlderInv(false)}>{olderBusy?'Loading…':`Load older ${INV_WINDOW_DAYS} days`}</button>
            <button className="btn btn-sm btn-outline" disabled={olderBusy} onClick={()=>loadOlderInv(true)}>Load all</button>
          </div>}
        </div>}
        <div className="tbl-wrap">
          <table>
            <thead><tr><th>Invoice No</th><th>Member</th><th>Plan</th><th>Date</th><th>Amount</th><th>Payment</th><th>Raised By</th><th></th></tr></thead>
            <tbody>
              {filteredInv.length===0?<tr><td colSpan={8} className="tbl-empty">No invoices found</td></tr>
               :filteredInv.slice().reverse().map(i=>(
                <tr key={i.id}>
                  <td style={{fontFamily:'monospace',fontWeight:700,color:'var(--primary2)'}}>{i.number}</td>
                  <td><div style={{fontWeight:600}}>{i.memberName}</div><div style={{fontSize:11,color:'var(--text3)'}}>{i.memberPhone}</div></td>
                  <td>{i.planName}</td>
                  <td>{fmtD(i.date)}</td>
                  <td style={{fontWeight:700,color:'var(--green)'}}>{fmt(i.total)}{i.discountPercent>0&&<div style={{fontSize:10.5,fontWeight:500,color:'var(--warn)'}}>{i.discountPercent}% discount</div>}</td>
                  <td><span className="badge badge-active">{i.paymentMode}</span>{i.paymentRef&&<div style={{fontSize:10.5,color:'var(--text3)',marginTop:3,fontFamily:'monospace'}}>{i.paymentRef}</div>}</td>
                  <td style={{fontSize:12,color:'var(--text2)'}}>{i.raisedBy}</td>
                  <td>
                    <div style={{display:'flex',gap:6}}>
                      <button className="btn btn-sm btn-outline" title="Download PDF" onClick={()=>{
                        try{downloadInvoicePDF(i,settings);}
                        catch(e){console.error('PDF export failed:',e);toast.error('Could not generate PDF: '+e.message);}
                      }}><Ic n="download" s={12}/></button>
                      <button className="btn btn-sm btn-outline" title="Send via WhatsApp" style={{color:'var(--green)'}} onClick={()=>{
                        try{sendInvoiceWhatsApp(i,settings);}
                        catch(e){console.error('WhatsApp send failed:',e);toast.error('Could not open WhatsApp: '+e.message);}
                      }}><Ic n="whatsapp" s={12}/></button>
                      {canDeleteInvoices&&<button className="btn btn-sm btn-outline" title="Delete invoice" style={{color:'var(--red)'}} onClick={()=>delInvoice(i.id)}><Ic n="trash" s={12}/></button>}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>}
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   📋  PLANS (Membership + PT)
   ══════════════════════════════════════════════════════════ */
const Plans=({user})=>{
  const isSuper=user.role==='superadmin';
  const[tab,setTab]=useState('membership');
  const[plans,setPlans]=useStoreState(SK.PLANS);
  const[ptPlans,setPtPlans]=useStoreState(SK.PTPLANS);
  const[form,setForm]=useState({name:'',price:'',durationMonths:'1',sessions:'',hsn:'999723',active:true});
  const[editId,setEditId]=useState(null);
  const[showForm,setShowForm]=useState(false);

  const savePlan=()=>{
    if(!form.name.trim()||!form.price){toast.error('Name and price required');return;}
    const rec={...form,id:editId||genId(),price:parseFloat(form.price)||0,
      durationMonths:parseInt(form.durationMonths)||1,sessions:parseInt(form.sessions)||0};
    if(tab==='membership'){
      let all=editId?plans.map(p=>p.id===editId?rec:p):[...plans,rec];
      S.set(SK.PLANS,all);setPlans(all);
    } else {
      let all=editId?ptPlans.map(p=>p.id===editId?rec:p):[...ptPlans,rec];
      S.set(SK.PTPLANS,all);setPtPlans(all);
    }
    setShowForm(false);setEditId(null);setForm({name:'',price:'',durationMonths:'1',sessions:'',hsn:'999723',active:true});
    toast.success(editId?'Plan updated':'Plan added');
  };
  const delPlan=id=>{
    if(!window.confirm('Delete plan?'))return;
    if(tab==='membership'){const a=plans.filter(p=>p.id!==id);S.set(SK.PLANS,a);setPlans(a);}
    else{const a=ptPlans.filter(p=>p.id!==id);S.set(SK.PTPLANS,a);setPtPlans(a);}
    toast.info('Deleted');
  };
  const startEdit=p=>{
    setEditId(p.id);
    setForm({name:p.name,price:p.price,durationMonths:p.durationMonths||1,sessions:p.sessions||'',hsn:p.hsn||'999723',active:p.active!==false});
    setShowForm(true);
  };
  const rows=tab==='membership'?plans:ptPlans;

  return(
    <div className="page-enter">
      <div className="page-hdr">
        <div><div className="page-title">Plans</div><div className="page-sub">Membership &amp; Personal Training</div></div>
        {isSuper&&<button className="btn btn-primary" onClick={()=>{setShowForm(!showForm);setEditId(null);setForm({name:'',price:'',durationMonths:'1',sessions:'',hsn:'999723',active:true});}}>
          <Ic n="plus" s={14}/>{showForm?'Cancel':'Add Plan'}
        </button>}
      </div>
      <div className="pill-tabs">
        <button className={`pill-tab ${tab==='membership'?'active':''}`} onClick={()=>{setTab('membership');setShowForm(false);}}>Membership Plans</button>
        <button className={`pill-tab ${tab==='pt'?'active':''}`} onClick={()=>{setTab('pt');setShowForm(false);}}>Personal Training</button>
      </div>

      {showForm&&isSuper&&<div className="card" style={{marginBottom:16}}>
        <div className="section-title" style={{marginBottom:14}}>{editId?'Edit':'New'} {tab==='membership'?'Membership':'PT'} Plan</div>
        <div className="g2">
          <div className="field"><label className="field-label">Plan Name *</label><input className="field-input" value={form.name} onChange={e=>setForm(p=>({...p,name:e.target.value}))} placeholder="e.g. Monthly, Quarterly"/></div>
          <div className="field"><label className="field-label">Price (₹) *</label><input className="field-input" type="number" value={form.price} onChange={e=>setForm(p=>({...p,price:e.target.value}))}/></div>
          {tab==='membership'
            ?<div className="field"><label className="field-label">Duration (months)</label><input className="field-input" type="number" min="1" value={form.durationMonths} onChange={e=>setForm(p=>({...p,durationMonths:e.target.value}))}/></div>
            :<div className="field"><label className="field-label">Sessions</label><input className="field-input" type="number" value={form.sessions} onChange={e=>setForm(p=>({...p,sessions:e.target.value}))}/></div>
          }
          <div className="field"><label className="field-label">HSN Code</label><input className="field-input" value={form.hsn} onChange={e=>setForm(p=>({...p,hsn:e.target.value}))}/></div>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button className="btn btn-primary" onClick={savePlan}><Ic n="check" s={13}/>{editId?'Update':'Save'}</button>
          <button className="btn btn-outline" onClick={()=>{setShowForm(false);setEditId(null);}}>Cancel</button>
        </div>
      </div>}

      <div className="card">
        <div className="tbl-wrap">
          <table>
            <thead><tr>
              <th>Plan Name</th><th>Price</th>
              {tab==='membership'?<th>Duration</th>:<th>Sessions</th>}
              <th>HSN</th><th>Status</th>
              {isSuper&&<th>Actions</th>}
            </tr></thead>
            <tbody>
              {rows.length===0?<tr><td colSpan={isSuper?6:5} className="tbl-empty">No plans yet</td></tr>
               :rows.map(p=>(
                <tr key={p.id}>
                  <td style={{fontWeight:600}}>{p.name}</td>
                  <td style={{fontWeight:700,color:'var(--green)'}}>{fmt(p.price)}</td>
                  {tab==='membership'?<td>{p.durationMonths} month{p.durationMonths>1?'s':''}</td>:<td>{p.sessions} sessions</td>}
                  <td style={{fontFamily:'monospace',color:'var(--text2)'}}>{p.hsn}</td>
                  <td><span className={`badge ${p.active!==false?'badge-active':'badge-expired'}`}>{p.active!==false?'Active':'Inactive'}</span></td>
                  {isSuper&&<td><div style={{display:'flex',gap:4}}>
                    <button className="btn btn-sm btn-outline" onClick={()=>startEdit(p)}><Ic n="edit" s={12}/></button>
                    <button className="btn btn-sm btn-outline" onClick={()=>delPlan(p.id)} style={{color:'var(--red)'}}><Ic n="trash" s={12}/></button>
                  </div></td>}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   📈  SALES FUNNEL (Kanban)
   ══════════════════════════════════════════════════════════ */
const STAGES=[
  {key:'lead',label:'Leads',color:'var(--blue)'},
  {key:'deal',label:'Deals',color:'var(--gold)'},
  {key:'renewal',label:'Renewals',color:'var(--green)'},
];
const SalesFunnel=({user})=>{
  const[cards,setCards]=useStoreState(SK.PIPELINE);
  const[showForm,setShowForm]=useState(false);
  const[form,setForm]=useState({name:'',value:'',dueDate:today(),note:''});
  const[dragId,setDragId]=useState(null);

  const addLead=()=>{
    if(!form.name.trim()){toast.error('Name required');return;}
    const rec={...form,id:genId(),stage:'lead',value:parseFloat(form.value)||0,createdAt:today()};
    const all=[...cards,rec];S.set(SK.PIPELINE,all);setCards(all);
    setShowForm(false);setForm({name:'',value:'',dueDate:today(),note:''});
    toast.success('Lead added');
  };
  const drop=stageKey=>{
    if(!dragId)return;
    const all=cards.map(c=>c.id===dragId?{...c,stage:stageKey}:c);
    S.set(SK.PIPELINE,all);setCards(all);setDragId(null);
  };
  const del=id=>{
    const all=cards.filter(c=>c.id!==id);S.set(SK.PIPELINE,all);setCards(all);toast.info('Removed');
  };

  return(
    <div className="page-enter">
      <div className="page-hdr">
        <div><div className="page-title">Sales Funnel</div><div className="page-sub">Drag cards across stages</div></div>
        <button className="btn btn-primary" onClick={()=>setShowForm(!showForm)}><Ic n="plus" s={14}/>{showForm?'Cancel':'Add Lead'}</button>
      </div>
      {showForm&&<div className="card" style={{marginBottom:16}}>
        <div className="g2" style={{marginBottom:10}}>
          <div className="field"><label className="field-label">Name / Lead</label><input className="field-input" value={form.name} onChange={e=>setForm(p=>({...p,name:e.target.value}))} placeholder="e.g. Rahul — walk-in"/></div>
          <div className="field"><label className="field-label">Expected Value (₹)</label><input className="field-input" type="number" value={form.value} onChange={e=>setForm(p=>({...p,value:e.target.value}))}/></div>
          <div className="field"><label className="field-label">Follow-up Date</label><input className="field-input" type="date" value={form.dueDate} onChange={e=>setForm(p=>({...p,dueDate:e.target.value}))}/></div>
          <div className="field"><label className="field-label">Note</label><input className="field-input" value={form.note} onChange={e=>setForm(p=>({...p,note:e.target.value}))} placeholder="Optional"/></div>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button className="btn btn-primary" onClick={addLead}><Ic n="check" s={13}/>Add to Leads</button>
          <button className="btn btn-outline" onClick={()=>setShowForm(false)}>Cancel</button>
        </div>
      </div>}
      <div className="kanban">
        {STAGES.map(st=>{
          const stCards=cards.filter(c=>c.stage===st.key);
          return(
            <div key={st.key} className="kanban-col" onDragOver={e=>e.preventDefault()} onDrop={()=>drop(st.key)}>
              <div className="kanban-col-hdr">
                <div className="kanban-dot" style={{background:st.color}}/>
                <span style={{fontSize:13,fontWeight:700,color:'var(--text)'}}>{st.label}</span>
                <span style={{marginLeft:'auto',fontSize:11,color:'var(--text3)',background:'var(--card3)',padding:'1px 8px',borderRadius:20}}>{stCards.length}</span>
              </div>
              {stCards.length===0?<div className="kanban-empty">Nothing here yet</div>
               :stCards.map(c=>(
                <div key={c.id} className="kanban-card" draggable onDragStart={()=>setDragId(c.id)}>
                  <div className="kname">{c.name}</div>
                  <div className="kmeta">{fmt(c.value)} · Due {fmtD(c.dueDate)}</div>
                  {c.note&&<div style={{fontSize:11,color:'var(--text3)',marginTop:4}}>{c.note}</div>}
                  <button className="btn btn-sm" style={{marginTop:6,color:'var(--red)',background:'none',border:'none',padding:0,fontSize:11}} onClick={()=>del(c.id)}>Remove</button>
                </div>
              ))}
            </div>
          );
        })}
      </div>
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   📊  REPORTS (Super Admin only) — period filter + Excel exports
   ══════════════════════════════════════════════════════════ */
const REPORT_PRESETS=[
  ['thisMonth','This month'],['lastMonth','Last month'],['thisQuarter','This quarter'],
  ['thisFY','This FY'],['lastFY','Last FY'],['all','All time'],['custom','Custom'],
];
const MEMBER_BASIS=[
  ['invoiced','Billed in the period (joined or renewed)'],
  ['start','Membership started in the period'],
  ['expiry','Membership expires in the period'],
  ['all','All members (ignore the period)'],
];
const Reports=({user})=>{
  useXp();
  const isSuper=user?.role==='superadmin';
  const first=periodPreset('thisMonth');
  const[preset,setPreset]=useState('thisMonth');
  const[from,setFrom]=useState(first[0]);
  const[to,setTo]=useState(first[1]);
  const[basis,setBasis]=useState('invoiced');
  const[expMode,setExpMode]=useState('approved');
  const[loadingRange,setLoadingRange]=useState(false);
  // Older invoices / expenses are loaded on demand for whichever period is selected.
  useEffect(()=>{
    if(!isSuper)return;
    let alive=true;setLoadingRange(true);
    Promise.all([InvDB.ensureFrom(from),xpEnsureFrom(from)]).catch(e=>console.warn('Range load:',e.message)).then(()=>{if(alive)setLoadingRange(false);});
    return()=>{alive=false;};
  },[from,isSuper]);

  // Hard guard — even if someone reaches this page some other way, only a super admin sees data.
  if(!isSuper)return(
    <div className="page-enter"><div className="card" style={{textAlign:'center',padding:40}}>
      <div style={{fontWeight:700,fontSize:15,marginBottom:6}}>Reports are restricted</div>
      <div style={{fontSize:13,color:'var(--text3)'}}>Only Super Admins can view and export reports.</div>
    </div></div>
  );

  const settings=S.get(SK.SETTINGS,{})||{};
  const allInv=InvDB.all();
  const allMem=S.get(SK.MEMBERS,[])||[];
  const periodInv=allInv.filter(i=>inPeriod(i.date,from,to));
  const sum=fn=>round2(periodInv.reduce((a,i)=>a+(fn(i)||0),0));
  const taxable=sum(i=>invTax(i).taxable),gst=sum(i=>invTax(i).gst),total=sum(i=>i.total);
  const byMode={};
  periodInv.forEach(i=>{const m=i.paymentMode||'Other';byMode[m]=byMode[m]||{n:0,amt:0};byMode[m].n++;byMode[m].amt+=(i.total||0);});
  const memberCount=selectReportMembers(allMem,allInv,from,to,basis).length;
  const allExp=xpList(XP_KEY);
  const expInP=allExp.filter(e=>inPeriod(e.date,from,to));
  const expApproved=expInP.filter(e=>e.status==='approved');
  const expPending=expInP.filter(e=>e.status==='pending');
  const expApprovedTotal=sumTotal(expApproved);
  const expModeCount=(expMode==='all'?expInP:expInP.filter(e=>e.status===expMode)).length;
  const expByCat={};expApproved.forEach(e=>{const k=e.category||'Other';expByCat[k]=expByCat[k]||{n:0,amt:0};expByCat[k].n++;expByCat[k].amt+=(e.total||0);});

  const pick=key=>{
    setPreset(key);
    const r=periodPreset(key);
    if(r){setFrom(r[0]);setTo(r[1]);}
  };
  const rangeOk=()=>{
    if(from&&to&&from>to){toast.error('"From" date must be on or before "To" date.');return false;}
    return true;
  };
  const run=async fn=>{
    if(!rangeOk())return;
    try{await Promise.all([InvDB.ensureFrom(from),xpEnsureFrom(from)]);fn();}   // make sure the whole period is loaded first
    catch(e){console.error('Report export failed:',e);toast.error('Could not export: '+e.message);}
  };
  const periodText=(from||to)?`${from?fmtD(from):'Beginning'} → ${to?fmtD(to):'Today'}`:'All time';

  return(
    <div className="page-enter">
      <div className="page-hdr">
        <div><div className="page-title">Reports</div><div className="page-sub">Export GSTR-1, member and expense data to Excel · Super Admin only</div></div>
      </div>

      <div className="card" style={{marginBottom:16}}>
        <div className="section-title" style={{marginBottom:12}}><Ic n="calendar" s={15}/>Period{loadingRange&&<span className="muted" style={{marginLeft:8,fontWeight:500}}>loading older records…</span>}</div>
        <div className="pill-tabs" style={{flexWrap:'wrap',marginBottom:12}}>
          {REPORT_PRESETS.map(([k,l])=><button key={k} className={`pill-tab ${preset===k?'active':''}`} onClick={()=>pick(k)}>{l}</button>)}
        </div>
        <div style={{display:'flex',gap:12,flexWrap:'wrap',alignItems:'flex-end'}}>
          <div className="field" style={{margin:0}}>
            <label className="field-label">From</label>
            <input className="field-input" type="date" value={from} onChange={e=>{setFrom(e.target.value);setPreset('custom');}}/>
          </div>
          <div className="field" style={{margin:0}}>
            <label className="field-label">To</label>
            <input className="field-input" type="date" value={to} onChange={e=>{setTo(e.target.value);setPreset('custom');}}/>
          </div>
          <div style={{fontSize:12,color:'var(--text3)',paddingBottom:10}}>Showing: <strong style={{color:'var(--text2)'}}>{periodText}</strong></div>
        </div>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(150px,1fr))',gap:12,marginBottom:16}}>
        <div className="card stat-card"><div><div className="lbl">Invoices</div><div className="val">{periodInv.length}</div><div className="sub">in this period</div></div></div>
        <div className="card stat-card"><div><div className="lbl">Taxable value</div><div className="val" style={{fontSize:20}}>{fmt(taxable)}</div><div className="sub">after discounts</div></div></div>
        <div className="card stat-card"><div><div className="lbl">GST collected</div><div className="val" style={{fontSize:20}}>{fmt(gst)}</div><div className="sub">CGST + SGST</div></div></div>
        <div className="card stat-card"><div><div className="lbl">Total collected</div><div className="val" style={{fontSize:20}}>{fmt(total)}</div><div className="sub">invoice value</div></div></div>
      </div>
      <div className="rp-stats3" style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))',gap:12,marginBottom:16}}>
        <div className="card stat-card"><div><div className="lbl">Approved expenses</div><div className="val" style={{fontSize:20}}>{fmt(expApprovedTotal)}</div><div className="sub">{expApproved.length} in the books</div></div></div>
        <div className="card stat-card"><div><div className="lbl">Pending approval</div><div className="val" style={{fontSize:20}}>{expPending.length}</div><div className="sub">{fmt(sumTotal(expPending))} not in books</div></div></div>
        <div className="card stat-card"><div><div className="lbl">Net result</div><div className="val" style={{fontSize:20,color:total-expApprovedTotal>=0?'var(--green)':'var(--red)'}}>{fmt(total-expApprovedTotal)}</div><div className="sub">collected − approved expenses</div></div></div>
      </div>

      <div className="g2" style={{marginBottom:16}}>
        <div className="card">
          <div className="section-title" style={{marginBottom:6}}><Ic n="receipt" s={15}/>GSTR-1 Export</div>
          <div style={{fontSize:12.5,color:'var(--text3)',lineHeight:1.65,marginBottom:14}}>
            Excel workbook for the selected period with five sheets: <strong style={{color:'var(--text2)'}}>Summary</strong>,
            {' '}<strong style={{color:'var(--text2)'}}>Invoices</strong> (with payment mode &amp; reference),
            {' '}<strong style={{color:'var(--text2)'}}>B2CS</strong>, <strong style={{color:'var(--text2)'}}>HSN Summary</strong> and
            {' '}<strong style={{color:'var(--text2)'}}>Documents Issued</strong>. Use it as a reference when filing GSTR-1.
          </div>
          <button className="btn btn-primary" disabled={periodInv.length===0} onClick={()=>run(()=>exportGstr1(InvDB.all(),settings,from,to))}>
            <Ic n="download" s={13}/>Export GSTR-1 ({periodInv.length} invoice{periodInv.length===1?'':'s'})
          </button>
          {!settings.gstin&&<div style={{fontSize:11,color:'var(--warn)',marginTop:10}}>GSTIN isn't set — add it in Gym Settings so Place of Supply fills in correctly.</div>}
        </div>

        <div className="card">
          <div className="section-title" style={{marginBottom:6}}><Ic n="users" s={15}/>Members Details Sheet</div>
          <div style={{fontSize:12.5,color:'var(--text3)',lineHeight:1.65,marginBottom:12}}>
            Everything we hold on each member — contact info, plan, trainer, dates, status, payment history and totals — plus a
            {' '}<strong style={{color:'var(--text2)'}}>Member Invoices</strong> sheet with the payment trail.
          </div>
          <div className="field" style={{marginBottom:12}}>
            <label className="field-label">Include members who…</label>
            <select className="field-input" value={basis} onChange={e=>setBasis(e.target.value)}>
              {MEMBER_BASIS.map(([k,l])=><option key={k} value={k}>{l}</option>)}
            </select>
          </div>
          <button className="btn btn-primary" disabled={memberCount===0} onClick={()=>run(()=>exportMembersExcel(allMem,InvDB.all(),settings,from,to,basis))}>
            <Ic n="download" s={13}/>Export Members ({memberCount})
          </button>
        </div>
      </div>

      <div className="g2" style={{marginBottom:16}}>
        <div className="card">
          <div className="section-title" style={{marginBottom:6}}><Ic n="wallet" s={15}/>Expenses Report</div>
          <div style={{fontSize:12.5,color:'var(--text3)',lineHeight:1.65,marginBottom:12}}>
            Excel workbook with <strong style={{color:'var(--text2)'}}>Summary</strong> (incl. revenue vs expenses),
            {' '}<strong style={{color:'var(--text2)'}}>Expense Register</strong> (every detail, approver and status),
            {' '}<strong style={{color:'var(--text2)'}}>By Category</strong>, <strong style={{color:'var(--text2)'}}>By Month</strong>,
            {' '}<strong style={{color:'var(--text2)'}}>By Payment Mode</strong> and <strong style={{color:'var(--text2)'}}>By Staff</strong>.
          </div>
          <div className="field" style={{marginBottom:12}}>
            <label className="field-label">Include</label>
            <select className="field-input" value={expMode} onChange={e=>setExpMode(e.target.value)}>
              <option value="approved">Approved only — what is in the books</option>
              <option value="all">All expenses, with status</option>
              <option value="pending">Pending approval only</option>
              <option value="rejected">Rejected only</option>
            </select>
          </div>
          <button className="btn btn-primary" disabled={expInP.length===0} onClick={()=>run(()=>exportExpensesExcel(xpList(XP_KEY),InvDB.all(),settings,from,to,expMode))}>
            <Ic n="download" s={13}/>Export Expenses ({expModeCount})
          </button>
        </div>
        <div className="card">
          <div className="section-title" style={{marginBottom:12}}><Ic n="wallet" s={15}/>Approved expenses by category</div>
          <div className="tbl-wrap"><table>
            <thead><tr><th>Category</th><th>Bills</th><th style={{textAlign:'right'}}>Amount</th></tr></thead>
            <tbody>
              {Object.keys(expByCat).length===0
                ?<tr><td colSpan={3} className="tbl-empty">No approved expenses in this period</td></tr>
                :Object.entries(expByCat).sort((a,b)=>b[1].amt-a[1].amt).map(([c,v])=>(
                  <tr key={c}><td>{c}</td><td>{v.n}</td><td style={{textAlign:'right',fontWeight:700}}>{fmt(v.amt)}</td></tr>))}
            </tbody>
          </table></div>
        </div>
      </div>

      <div className="card">
        <div className="section-title" style={{marginBottom:12}}><Ic n="rupee" s={15}/>Collections by payment mode</div>
        <div className="tbl-wrap"><table>
          <thead><tr><th>Payment mode</th><th>Invoices</th><th style={{textAlign:'right'}}>Amount</th></tr></thead>
          <tbody>
            {Object.keys(byMode).length===0
              ?<tr><td colSpan={3} className="tbl-empty">No invoices in this period</td></tr>
              :Object.entries(byMode).sort((a,b)=>b[1].amt-a[1].amt).map(([m,v])=>(
                <tr key={m}><td>{m}</td><td>{v.n}</td><td style={{textAlign:'right',fontWeight:700}}>{fmt(v.amt)}</td></tr>
              ))}
          </tbody>
        </table></div>
      </div>
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   👥  USERS (Super Admin only)
   ══════════════════════════════════════════════════════════ */
const UsersAdmin=({user})=>{
  const[users,setUsers]=useStoreState(SK.USERS);
  const[showForm,setShowForm]=useState(false);
  const[editId,setEditId]=useState(null);
  const[form,setForm]=useState({name:'',email:'',password:'',role:'staff',active:true});
  const[showPwd,setShowPwd]=useState({});

  const[busy,setBusy]=useState(false);
  const save=async()=>{
    if(busy)return;
    if(!form.name.trim()||!form.email.trim()){toast.error('Name and email required');return;}
    if(!editId&&(form.password||'').length<6){toast.error('Password must be at least 6 characters');return;}
    const em=form.email.trim().toLowerCase();
    if(users.find(u=>u.email.toLowerCase()===em&&u.id!==editId)){toast.error('Email already exists');return;}
    setBusy(true);
    try{
      if(editId){
        const old=users.find(u=>u.id===editId);
        if(isProtectedSuperAdmin(old)){toast.error('Owner accounts cannot be edited');return;}
        S.set(SK.USERS,users.map(u=>u.id===editId?{...u,name:form.name.trim(),role:form.role,active:form.active}:u));  // e-mail is the login id: it is not changed here
        toast.success('User updated');
      }else{
        const uid=await Auth.createLogin(em,form.password);   // real Firebase login (password is never stored by us)
        S.set(SK.USERS,[...users,{id:uid,uid,name:form.name.trim(),email:em,role:form.role,active:true,createdAt:new Date().toISOString()}]);
        toast.success('User created — they can now log in');
      }
      setShowForm(false);setEditId(null);setForm({name:'',email:'',password:'',role:'staff',active:true});
    }catch(e){toast.error(Auth.friendly(e));}
    finally{setBusy(false);}
  };
  const toggle=id=>{
    const t=users.find(u=>u.id===id);if(!t||isProtectedSuperAdmin(t))return;
    S.set(SK.USERS,users.map(u=>u.id===id?{...u,active:!(u.active!==false)}:u));
  };
  const del=id=>{
    const t=users.find(u=>u.id===id);if(!t||isProtectedSuperAdmin(t))return;
    if(!window.confirm('Remove this user? They lose access immediately. You can restore them from Data Safety → Recycle Bin.'))return;
    S.set(SK.USERS,users.filter(u=>u.id!==id));toast.info('User moved to Recycle Bin');
  };
  const resetPw=async u=>{try{await Auth.sendReset(u.email);toast.success('Password-reset e-mail sent to '+u.email);}catch(e){toast.error(Auth.friendly(e));}};
  const migrateLegacy=async()=>{
    if(!window.confirm('Create real logins for the users stored in the old system? Passwords are re-used once, then never stored.'))return;
    setBusy(true);
    try{const r=await Auth.migrateLegacyUsers();toast.success('Created '+r.created.length+', skipped '+r.skipped.length+(r.failed.length?', FAILED '+r.failed.length:''));if(r.failed.length)console.warn(r.failed);}
    catch(e){toast.error(e.message);}finally{setBusy(false);}
  };
  const startEdit=u=>{
    setEditId(u.id);setForm({name:u.name,email:u.email,password:'',role:u.role,active:u.active!==false});
    setShowForm(true);
  };
  const ROLES=[{v:'superadmin',l:'Super Admin'},{v:'staff',l:'Staff'},{v:'trainer',l:'Trainer'}];

  return(
    <div className="page-enter">
      <div className="page-hdr">
        <div><div className="page-title">User Management</div><div className="page-sub">{users.length} users · Add unlimited staff &amp; trainers</div></div>
        <button className="btn btn-primary" onClick={()=>{setShowForm(!showForm);setEditId(null);setForm({name:'',email:'',password:'',role:'staff',active:true});}}>
          <Ic n="plus" s={14}/>{showForm?'Cancel':'Add User'}
        </button>
        <button className="btn btn-outline" onClick={migrateLegacy} disabled={busy} title="One-time: convert old users to Firebase logins">Migrate old users</button>
      </div>

      {showForm&&<div className="card" style={{marginBottom:16}}>
        <div className="section-title" style={{marginBottom:16}}>{editId?'Edit User':'Create New User'}</div>
        <div className="g2">
          <div className="field"><label className="field-label">Full Name *</label><input className="field-input" value={form.name} onChange={e=>setForm(p=>({...p,name:e.target.value}))} placeholder="Full name"/></div>
          <div className="field"><label className="field-label">Email * (used to login)</label><input className="field-input" type="email" disabled={!!editId} value={form.email} onChange={e=>setForm(p=>({...p,email:e.target.value}))} placeholder="user@gym.com"/></div>
          {!editId&&<div className="field"><label className="field-label">{editId?'New Password (leave blank to keep)':'Password *'}</label>
            <div style={{position:'relative'}}>
              <input className="field-input" type={showPwd[editId||'new']?'text':'password'} value={form.password} onChange={e=>setForm(p=>({...p,password:e.target.value}))} placeholder={editId?'Leave blank to keep current':'Set password'}/>
              <button type="button" onClick={()=>setShowPwd(p=>({...p,[editId||'new']:!p[editId||'new']}))} style={{position:'absolute',right:10,top:'50%',transform:'translateY(-50%)',background:'none',border:'none',color:'var(--text3)',cursor:'pointer'}}>
                <Ic n="eye" s={14}/>
              </button>
            </div>
          </div>}
          <div className="field"><label className="field-label">Role</label>
            <select className="field-input" value={form.role} onChange={e=>setForm(p=>({...p,role:e.target.value}))}>
              {ROLES.map(r=><option key={r.v} value={r.v}>{r.l}</option>)}
            </select>
          </div>
        </div>
        <div style={{display:'flex',gap:8,marginTop:4}}>
          <button className="btn btn-primary" onClick={save} disabled={busy}><Ic n="check" s={13}/>{editId?'Update':'Create User'}</button>
          <button className="btn btn-outline" onClick={()=>{setShowForm(false);setEditId(null);}}>Cancel</button>
        </div>
        <div style={{marginTop:12,padding:'10px 12px',background:'var(--success-bg)',borderRadius:8,fontSize:12,color:'var(--green)'}}>
          ✅ Users sign in with Firebase Authentication. Passwords are never stored in the database; use “Reset password” to e-mail a reset link.
        </div>
      </div>}

      <div className="card">
        <div className="tbl-wrap">
          <table>
            <thead><tr><th>User</th><th>Role</th><th>Status</th><th>Created</th><th>Actions</th></tr></thead>
            <tbody>
              {users.length===0?<tr><td colSpan={5} className="tbl-empty">No users yet</td></tr>
               :users.map(u=>(
                <tr key={u.id}>
                  <td>
                    <div style={{display:'flex',alignItems:'center',gap:10}}>
                      <div className="avatar" style={{width:30,height:30,fontSize:12}}>{u.name[0]}</div>
                      <div><div style={{fontWeight:600}}>{u.name}</div><div style={{fontSize:11,color:'var(--text3)'}}>{u.email}</div></div>
                    </div>
                  </td>
                  <td><span className={`badge badge-${u.role}`}>{u.role}</span></td>
                  <td><span className={`badge ${u.active!==false?'badge-active':'badge-expired'}`}>{u.active!==false?'Active':'Inactive'}</span></td>
                  <td style={{fontSize:12,color:'var(--text2)'}}>{u.createdAt?fmtD(u.createdAt.slice(0,10)):'—'}</td>
                  <td>
                    {isProtectedSuperAdmin(u)?
                      <span style={{fontSize:11,color:'var(--text3)',fontStyle:'italic'}}>Protected</span>
                    :
                      <div style={{display:'flex',gap:4}}>
                        <button className="btn btn-sm btn-outline" onClick={()=>startEdit(u)}><Ic n="edit" s={12}/></button>
                        <button className="btn btn-sm btn-outline" onClick={()=>resetPw(u)} title="E-mail a password reset link">Reset password</button>
                        <button className="btn btn-sm btn-outline" onClick={()=>toggle(u.id)} title={u.active?'Deactivate':'Activate'} style={{color:u.active?'var(--warn)':'var(--green)'}}>
                          {u.active!==false?'Disable':'Enable'}
                        </button>
                        {u.role!=='superadmin'&&<button className="btn btn-sm btn-outline" onClick={()=>del(u.id)} style={{color:'var(--red)'}}><Ic n="trash" s={12}/></button>}
                      </div>
                    }
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   ⚙️  GYM SETTINGS
   ══════════════════════════════════════════════════════════ */
/* ── Data & performance (Super Admin) ── */
const DataHealthCard=()=>{
  useXp();
  const[busy,setBusy]=useState('');
  const sum=InvDB.summary(),xt=xpTotals();
  const loadedInv=InvDB.all().length,loadedExp=xpList(XP_KEY).length;
  const act=async(label,fn)=>{
    setBusy(label);
    try{const n=await fn();toast.success(label+' — done'+(n!=null?' ('+n+' records)':''));}
    catch(e){toast.error(label+' failed: '+e.message);}
    setBusy('');
  };
  return(
    <div className="card" style={{marginTop:16}}>
      <div className="section-title" style={{marginBottom:6}}><Ic n="chart" s={15}/>Data &amp; performance</div>
      <div style={{fontSize:12.5,color:'var(--text3)',lineHeight:1.65,marginBottom:12}}>
        To keep the software fast as your records grow, only the last {INV_WINDOW_DAYS} days of invoices and expenses are loaded at startup.
        Older records are fetched when you search, pick a date range, or click “Load older”. Dashboard totals always cover all time.
      </div>
      <div className="tbl-wrap"><table>
        <thead><tr><th>Records</th><th style={{textAlign:'right'}}>All time</th><th style={{textAlign:'right'}}>Loaded now</th><th>Loaded since</th></tr></thead>
        <tbody>
          <tr><td>Invoices</td><td style={{textAlign:'right'}}>{sum.count}</td><td style={{textAlign:'right'}}>{loadedInv}</td><td>{InvDB.isComplete()?'Everything':fmtD(InvDB.windowDate())}</td></tr>
          <tr><td>Expenses (approved + pending)</td><td style={{textAlign:'right'}}>{xt.approvedN+xt.pendingN}</td><td style={{textAlign:'right'}}>{loadedExp}</td><td>{xpComplete()?'Everything':fmtD(xpWindowDate())}</td></tr>
        </tbody>
      </table></div>
      <div style={{display:'flex',gap:8,flexWrap:'wrap',marginTop:12}}>
        <button className="btn btn-outline" disabled={!!busy} onClick={()=>act('Load full history',async()=>{await InvDB.loadAll();await xpLoadAll();})}>{busy==='Load full history'?'Loading…':'Load full history now'}</button>
        <button className="btn btn-outline" disabled={!!busy} onClick={()=>{if(window.confirm('Recalculate the dashboard totals from every invoice and expense? This loads all records once and may take a moment.'))act('Rebuild dashboard totals',async()=>{const a=await InvDB.rebuildStats();const b=await xpRebuildStats();return a+b;});}}>{busy==='Rebuild dashboard totals'?'Working…':'Rebuild dashboard totals'}</button>
      </div>
      <div style={{fontSize:11,color:'var(--text3)',marginTop:8}}>“Rebuild” is only needed if a dashboard total ever looks out of step with your records.</div>
    </div>
  );
};

const GymSettings=({user,onSaved})=>{
  const[form,setForm]=useState(S.get(SK.SETTINGS,{})||{});
  const[uploading,setUploading]=useState(false);
  const[testingSheet,setTestingSheet]=useState(false);
  const fileRef=useRef(null);
  const save=()=>{S.set(SK.SETTINGS,form);toast.success('Settings saved');onSaved&&onSaved();};

  const testSheetConnection=()=>{
    const url=(form.sheetWebhookUrl||'').trim();
    if(!url){toast.error('Paste your Google Apps Script Web App URL first.');return;}
    if(!/^https:\/\/script\.google\.com\/macros\/s\/.+\/exec$/.test(url)){
      toast.error("That doesn't look like a deployed Web App URL — it should start with https://script.google.com/macros/s/ and end in /exec (not /dev).");
      return;
    }
    setTestingSheet(true);
    syncToGoogleSheet({
      type:'test',invoiceNumber:'TEST',invoiceDate:today(),
      memberName:'TEST ROW — Arctic Gym Management connection check',memberEmail:'test@example.com',
      memberPhone:'0000000000',memberAddress:'This row confirms the connection works — delete it once seen.',
      planName:'Test',startDate:today(),expiryDate:today(),total:0,gstEnabled:false
    },{sheetWebhookUrl:url,sheetWebhookSecret:form.sheetWebhookSecret});
    toast.info("Test row sent — check your Google Sheet now. If nothing shows up within a few seconds, see the troubleshooting notes below.");
    setTimeout(()=>setTestingSheet(false),1500);
  };

  const handleLogoFile=(e)=>{
    const file=e.target.files[0];
    e.target.value=''; // allow re-selecting the same file later
    if(!file)return;
    if(!file.type.startsWith('image/')){toast.error('Please choose an image file (PNG, JPG, etc.)');return;}
    if(file.size>3*1024*1024){toast.error('Image is too large — please choose one under 3MB');return;}
    setUploading(true);
    const reader=new FileReader();
    reader.onload=(ev)=>{
      const img=new Image();
      img.onload=()=>{
        // Normalize to PNG and cap dimensions so it stores compactly in
        // localStorage / Firebase and prints crisply on invoices.
        const maxDim=480;
        let w=img.naturalWidth,h=img.naturalHeight;
        if(w>maxDim||h>maxDim){const scale=maxDim/Math.max(w,h);w=Math.round(w*scale);h=Math.round(h*scale);}
        const canvas=document.createElement('canvas');
        canvas.width=w;canvas.height=h;
        canvas.getContext('2d').drawImage(img,0,0,w,h);
        const dataUrl=canvas.toDataURL('image/png');
        setForm(p=>({...p,logo:dataUrl,logoW:w,logoH:h}));
        setUploading(false);
        toast.success('Logo ready — click Save Settings to apply');
      };
      img.onerror=()=>{setUploading(false);toast.error('Could not read that image');};
      img.src=ev.target.result;
    };
    reader.onerror=()=>{setUploading(false);toast.error('Could not read that file');};
    reader.readAsDataURL(file);
  };
  const removeLogo=()=>setForm(p=>({...p,logo:null,logoW:null,logoH:null}));

  return(
    <div className="page-enter">
      <div className="page-hdr">
        <div><div className="page-title">Gym Settings</div><div className="page-sub">Business info printed on invoices</div></div>
        <button className="btn btn-primary" onClick={save}><Ic n="check" s={13}/>Save Settings</button>
      </div>
      <div className="card">
        <div className="field" style={{marginBottom:20}}>
          <label className="field-label">Gym Logo</label>
          <div style={{display:'flex',alignItems:'center',gap:16,flexWrap:'wrap'}}>
            <div style={{width:68,height:68,borderRadius:16,overflow:'hidden',flexShrink:0,
              border:'1px solid var(--border)',display:'flex',alignItems:'center',justifyContent:'center',
              background:form.logo?'#fff':'var(--card2)'}}>
              {form.logo
                ?<img src={form.logo} alt="Gym logo" style={{width:'100%',height:'100%',objectFit:'contain'}}/>
                :<GymLogo size={68} radius={16}/>}
            </div>
            <div>
              <div style={{display:'flex',gap:8}}>
                <button type="button" className="btn btn-sm btn-outline" disabled={uploading} onClick={()=>fileRef.current?.click()}>
                  <Ic n="upload" s={12}/>{uploading?'Uploading…':form.logo?'Replace Logo':'Upload Logo'}
                </button>
                {form.logo&&<button type="button" className="btn btn-sm btn-outline" style={{color:'var(--red)'}} onClick={removeLogo}>
                  <Ic n="trash" s={12}/>Remove
                </button>}
              </div>
              <input ref={fileRef} type="file" accept="image/*" style={{display:'none'}} onChange={handleLogoFile}/>
              <div style={{fontSize:11,color:'var(--text3)',marginTop:7,lineHeight:1.5}}>
                Square image recommended · PNG or JPG · Max 3MB<br/>Shown in the sidebar, login screen and on every invoice.
              </div>
            </div>
          </div>
        </div>
        <div className="g2">
          <div className="field"><label className="field-label">Gym Name</label><input className="field-input" value={form.name||''} onChange={e=>setForm(p=>({...p,name:e.target.value}))} placeholder="Arctic Gym Management"/></div>
          <div className="field"><label className="field-label">Phone</label><input className="field-input" value={form.phone||''} onChange={e=>setForm(p=>({...p,phone:e.target.value}))}/></div>
          <div className="field" style={{gridColumn:'1/-1'}}><label className="field-label">Address</label><textarea className="field-input" rows={2} value={form.address||''} onChange={e=>setForm(p=>({...p,address:e.target.value}))}/></div>
          <div className="field"><label className="field-label">GSTIN</label><input className="field-input" value={form.gstin||''} onChange={e=>setForm(p=>({...p,gstin:e.target.value}))} placeholder="29AAAAA0000A1Z5"/></div>
          <div className="field"><label className="field-label">Email</label><input className="field-input" type="email" value={form.email||''} onChange={e=>setForm(p=>({...p,email:e.target.value}))}/></div>
          <div className="field"><label className="field-label">UPI ID</label><input className="field-input" value={form.upiId||''} onChange={e=>setForm(p=>({...p,upiId:e.target.value}))} placeholder="gym@upi"/></div>
          <div className="field">
            <label className="field-label">WhatsApp Number</label>
            <input className="field-input" value={form.whatsapp||''} onChange={e=>setForm(p=>({...p,whatsapp:e.target.value}))} placeholder="+91 98765 43210"/>
            <div style={{fontSize:11,color:'var(--text3)',marginTop:5}}>Your gym's own WhatsApp contact — shown to members. Invoices are sent to each member's own saved phone number.</div>
          </div>
          <div className="field" style={{gridColumn:'1/-1'}}>
            <label className="field-label">Google Sheet Sync URL (Excel sync, invoice emails &amp; renewal reminders)</label>
            <div style={{display:'flex',gap:8}}>
              <input className="field-input" style={{flex:1}} value={form.sheetWebhookUrl||''} onChange={e=>setForm(p=>({...p,sheetWebhookUrl:e.target.value}))} placeholder="https://script.google.com/macros/s/.../exec"/>
              <button type="button" className="btn btn-outline" disabled={testingSheet} onClick={testSheetConnection} style={{flexShrink:0}}>
                {testingSheet?'Sending…':'Send Test Row'}
              </button>
            </div>
            <div style={{fontSize:11,color:'var(--text3)',marginTop:5,lineHeight:1.6}}>
              Optional. Paste your deployed Google Apps Script Web App URL here — every invoice you generate will
              automatically send that member's name, contact info and expiry date to your Google Sheet, so a script
              there can email renewal reminders automatically. See the setup guide provided with this app.
            </div>
            <div style={{fontSize:11,color:'var(--text3)',marginTop:10,padding:'10px 12px',background:'var(--card2)',borderRadius:8,lineHeight:1.7}}>
              <strong style={{color:'var(--text2)'}}>Nothing showing up in your Sheet?</strong> Click "Send Test Row" above first — if
              a test row never appears, it's almost always one of these two things in your Apps Script deployment:
              <br/>1. Under <strong>Deploy → Manage deployments</strong>, "Who has access" must be set to <strong>Anyone</strong> —
              not "Anyone with a Google account" and not "Only myself". With any other setting, requests from Arctic Gym Management are
              silently rejected before your script even runs.
              <br/>2. If you've edited the script <em>after</em> deploying it, you must create a <strong>new deployment</strong>
              (or edit the existing one and select a new version) — just saving the script does not update the live URL.
              <br/>3. A strict work/gym WiFi or firewall can block script.google.com outright — if the test row still doesn't
              appear after checking 1 and 2, try again on a different network (e.g. mobile data) to rule this out.
            </div>
          </div>
          <div className="field" style={{gridColumn:'1/-1'}}>
            <label className="field-label">Sheet Secret (optional but recommended)</label>
            <input className="field-input" type="password" autoComplete="new-password" value={form.sheetWebhookSecret||''} onChange={e=>setForm(p=>({...p,sheetWebhookSecret:e.target.value}))} placeholder="Same value as WEBHOOK_SECRET in the Apps Script"/>
            <div style={{fontSize:11,color:'var(--text3)',marginTop:5,lineHeight:1.6}}>
              Because the script now emails invoices automatically, set a secret here and the same one in the script so nobody else can make it send mail.
            </div>
          </div>
          <div className="field" style={{gridColumn:'1/-1'}}><label className="field-label">Bank Details</label><textarea className="field-input" rows={2} value={form.bankDetails||''} onChange={e=>setForm(p=>({...p,bankDetails:e.target.value}))} placeholder="Account No, IFSC, Bank"/></div>
          <div className="field" style={{gridColumn:'1/-1'}}><label className="field-label">Terms &amp; Conditions (printed on invoice)</label><textarea className="field-input" rows={3} value={form.terms||''} onChange={e=>setForm(p=>({...p,terms:e.target.value}))}/></div>
        </div>
        <div className="toggle-wrap" style={{marginTop:4}} onClick={()=>setForm(p=>({...p,gstEnabled:!p.gstEnabled}))}>
          <div className={`toggle-sw ${form.gstEnabled?'on':''}`}><div className="toggle-knob"/></div>
          <span style={{fontSize:13,color:'var(--text2)'}}>Enable GST on invoices</span>
        </div>
        <div style={{fontSize:11,color:'var(--text3)',marginTop:8,maxWidth:520,lineHeight:1.6}}>
          This is a gym-wide master switch. When it's off, nobody — including staff — can add GST to
          an invoice, and invoices print as a plain "INVOICE" instead of a "TAX INVOICE". Turn it on
          here to let staff choose whether to include GST on each invoice they raise.
        </div>
        <div className="toggle-wrap" style={{marginTop:22}} onClick={()=>{
          if(user?.role!=='superadmin'){toast.error('Only a superadmin can change this setting.');return;}
          setForm(p=>({...p,discountEnabled:!p.discountEnabled}));
        }}>
          <div className={`toggle-sw ${form.discountEnabled?'on':''}`}><div className="toggle-knob"/></div>
          <span style={{fontSize:13,color:'var(--text2)'}}>Enable discounts on invoices</span>
        </div>
        <div style={{fontSize:11,color:'var(--text3)',marginTop:8,maxWidth:520,lineHeight:1.6}}>
          This is a gym-wide master switch. When it's on, a Discount dropdown (5%, 10%, 15% or 20%) appears
          on the Generate Invoice screen for both new and existing members. When it's off, the dropdown is hidden and
          no discount can be applied. The discount is taken off the subtotal first, and GST (if on) is then charged
          on the discounted amount. Remember to click <strong>Save Settings</strong> after changing this.
        </div>
      </div>
      {user?.role==='superadmin'&&<DataHealthCard/>}
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   🏋️  TRAINER VIEW
   ══════════════════════════════════════════════════════════ */
const TrainerView=({user})=>{
  const all=S.get(SK.MEMBERS,[])||[];
  const mine=all.filter(m=>m.trainerId===user.id);
  const active=mine.filter(m=>m.status==='active');
  return(
    <div className="page-enter">
      <div className="hero" style={{marginBottom:20}}>
        <div>
          <h2>Hey, {user.name.split(' ')[0]}! 🏋️</h2>
          <p>Your assigned members and their progress.</p>
        </div>
        <div className="hero-stats">
          <div className="hero-stat"><div className="hv">{mine.length}</div><div className="hl">Total Members</div></div>
          <div className="hero-stat"><div className="hv">{active.length}</div><div className="hl">Active</div></div>
        </div>
      </div>
      <div className="card">
        <div className="section-title" style={{marginBottom:14}}><Ic n="dumbbell" s={15}/>My Members</div>
        {mine.length===0?<div className="tbl-empty">No members assigned yet — contact your admin</div>
         :<div className="tbl-wrap"><table>
            <thead><tr><th>Member</th><th>Plan</th><th>Start</th><th>Expiry</th><th>Status</th></tr></thead>
            <tbody>{mine.map(m=><tr key={m.id}>
              <td><div style={{fontWeight:600}}>{m.name}</div><div style={{fontSize:11,color:'var(--text3)'}}>{m.phone}</div></td>
              <td>{m.planName||'—'}</td>
              <td>{fmtD(m.startDate)}</td>
              <td style={{color:m.expiryDate&&m.expiryDate<today()?'var(--red)':'inherit'}}>{fmtD(m.expiryDate)}</td>
              <td><span className={`badge badge-${m.status}`}>{m.status}</span></td>
            </tr>)}</tbody>
          </table></div>
        }
      </div>
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   🛡️  DATA SAFETY (owner only) — recycle bin · daily snapshots · export · audit log
   ══════════════════════════════════════════════════════════ */
const DataSafety=({user})=>{
  const[,tick]=useState(0);
  useEffect(()=>{const off=[SK.MEMBERS,SK.USERS,SK.PLANS,SK.PTPLANS,SK.PIPELINE].map(k=>S.subscribe(k,()=>tick(x=>x+1)));return()=>off.forEach(f=>f());},[]);
  const[busy,setBusy]=useState('');
  const[snaps,setSnaps]=useState([]);
  const[audit,setAudit]=useState([]);
  const[bills,setBills]=useState(false);
  const load=async()=>{try{setSnaps(await Backup.list());setAudit(await Audit.recent(120));}catch(e){toast.error('Could not load: '+e.message);}};
  useEffect(()=>{load();},[]);
  const act=async(label,fn)=>{setBusy(label);try{const r=await fn();toast.success(label+' — done');await load();return r;}catch(e){toast.error(label+' failed: '+e.message);}finally{setBusy('');}};
  const bin=Bin.list();
  const nice=t=>t?new Date(t).toLocaleString('en-IN'):'—';
  const KIND={profiles:'User',members:'Member',plans:'Plan',ptplans:'PT plan',pipeline:'Lead'};
  const counts=[['Members',(S.get(SK.MEMBERS,[])||[]).length],['Users',(S.get(SK.USERS,[])||[]).length],['Plans',(S.get(SK.PLANS,[])||[]).length+(S.get(SK.PTPLANS,[])||[]).length],['Leads',(S.get(SK.PIPELINE,[])||[]).length]];
  return(
    <div className="page-enter">
      <div className="page-hdr"><div><div className="page-title">Data Safety</div><div className="page-sub">Nothing is ever deleted for good by accident: removals go to a bin, snapshots are taken daily, every change is logged.</div></div></div>

      <div className="card" style={{marginBottom:16}}>
        <div className="section-title" style={{marginBottom:10}}>Status</div>
        <div style={{display:'flex',gap:18,flexWrap:'wrap',fontSize:13}}>
          <span>Database: <b style={{color:Store.ready?'var(--green)':'var(--red)'}}>{Store.ready?'Live & writable':'Read-only'}</b></span>
          <span>Connection: <b>{Store.online?'Online':'Offline'}</b></span>
          {counts.map(([n,c])=><span key={n}>{n}: <b>{c}</b></span>)}
          <span>Recycle bin: <b>{bin.length}</b></span>
        </div>
        {!Store.ready&&<div style={{marginTop:8,fontSize:12,color:'var(--red)'}}>{Store.reason}</div>}
      </div>

      <div className="card" style={{marginBottom:16}}>
        <div className="section-title" style={{marginBottom:10}}>Recycle Bin</div>
        <div className="tbl-wrap"><table>
          <thead><tr><th>Type</th><th>Name</th><th>Removed</th><th>Actions</th></tr></thead>
          <tbody>{bin.length===0?<tr><td colSpan={4} className="tbl-empty">Bin is empty</td></tr>:bin.map(it=>(
            <tr key={it.col+it.rec.id}>
              <td>{KIND[it.col]||it.col}</td>
              <td><b>{it.rec.name||it.rec.title||it.rec.id}</b><div style={{fontSize:11,color:'var(--text3)'}}>{it.rec.email||it.rec.phone||''}</div></td>
              <td style={{fontSize:12}}>{nice(it.rec._delAt)}</td>
              <td><div style={{display:'flex',gap:4}}>
                <button className="btn btn-sm btn-outline" disabled={!!busy} onClick={()=>act('Restore',()=>Bin.restore(it))}>Restore</button>
                <button className="btn btn-sm btn-outline" style={{color:'var(--red)'}} disabled={!!busy} onClick={()=>{if(window.confirm('Delete "'+(it.rec.name||it.rec.id)+'" FOREVER? This cannot be undone.'))act('Delete forever',()=>Bin.purge(it));}}>Delete forever</button>
              </div></td>
            </tr>))}</tbody>
        </table></div>
      </div>

      <div className="card" style={{marginBottom:16}}>
        <div className="section-title" style={{marginBottom:6}}>Backups</div>
        <div style={{fontSize:12,color:'var(--text3)',marginBottom:10}}>A snapshot is saved automatically each day you sign in (last {SNAPSHOT_KEEP_DAYS} days kept). “Recover missing” brings back records that are gone or in the bin — it never overwrites newer edits.</div>
        <div style={{display:'flex',gap:10,alignItems:'center',flexWrap:'wrap',marginBottom:12}}>
          <button className="btn btn-primary" disabled={!!busy} onClick={()=>act('Export',()=>Backup.download(bills))}>Download full backup (.json)</button>
          <label style={{fontSize:12,display:'flex',gap:6,alignItems:'center'}}><input type="checkbox" checked={bills} onChange={e=>setBills(e.target.checked)}/>include expense bill photos (large)</label>
          <button className="btn btn-outline" disabled={!!busy} onClick={()=>act('Snapshot now',async()=>{const d=new Date().toISOString().slice(0,10).replace(/-/g,'');await getDb().ref(ROOT+'/backup_index/'+d).remove();await Backup.dailySnapshot();})}>Take snapshot now</button>
        </div>
        <div className="tbl-wrap"><table>
          <thead><tr><th>Snapshot</th><th>Taken</th><th>Records</th><th>Action</th></tr></thead>
          <tbody>{snaps.length===0?<tr><td colSpan={4} className="tbl-empty">No snapshots yet</td></tr>:snaps.map(([d,m])=>(
            <tr key={d}><td>{d.slice(0,4)+'-'+d.slice(4,6)+'-'+d.slice(6)}</td><td style={{fontSize:12}}>{nice(m.t)}</td><td>{m.records}</td>
              <td><button className="btn btn-sm btn-outline" disabled={!!busy} onClick={()=>{if(window.confirm('Recover records missing since this snapshot?'))act('Recover',async()=>{const c=await Backup.recoverMissing(d);toast.info('Recovered: '+(Object.keys(c).length?JSON.stringify(c):'nothing was missing'));});}}>Recover missing</button></td></tr>))}</tbody>
        </table></div>
      </div>

      <div className="card">
        <div className="section-title" style={{marginBottom:10}}>Activity log (last {audit.length})</div>
        <div className="tbl-wrap"><table>
          <thead><tr><th>When</th><th>Who</th><th>Action</th><th>Item</th></tr></thead>
          <tbody>{audit.length===0?<tr><td colSpan={4} className="tbl-empty">No activity yet</td></tr>:audit.map(a=>(
            <tr key={a.k}><td style={{fontSize:12,whiteSpace:'nowrap'}}>{nice(a.t)}</td><td>{a.byName||a.by}</td><td><code style={{fontSize:11}}>{a.action}</code></td><td style={{fontSize:12}}>{a.label}{a.fields?<span style={{color:'var(--text3)'}}> · {a.fields}</span>:null}</td></tr>))}</tbody>
        </table></div>
      </div>
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   🏠  MAIN APP
   ══════════════════════════════════════════════════════════ */
const App=()=>{
  const[appReady,setAppReady]=useState(false);
  const[user,setUser]=useState(null);
  const[page,setPage]=useState('dashboard');
  const[theme,setTheme]=useState(S.get(SK.THEME,'dark'));
  const[sidebarCollapsed,setSidebarCollapsed]=useState(false);
  const[mobOpen,setMobOpen]=useState(false);
  const[settingsTick,setSettingsTick]=useState(0); // bump to force re-read of gym settings after save
  const[searchSeed,setSearchSeed]=useState({page:null,query:'',token:0});
  const[expSeed,setExpSeed]=useState({status:'all',token:0});
  const[showPw,setShowPw]=useState(false);
  const[resetParams,setResetParams]=useState(()=>{
    try{const p=new URLSearchParams(window.location.search);return p.get('mode')==='resetPassword'&&p.get('oobCode')?{oobCode:p.get('oobCode')}:null;}catch(e){return null;}
  });
  useXp();

  useStoreState('__status',null);   // repaint the banner when connection / ready state changes
  useEffect(()=>{
    Auth.init();
    let alive=true;
    const off=Auth.onChange(async(profile,err)=>{
      if(!alive)return;
      if(!profile){
        Sync.stop();setUser(null);setAppReady(true);
        return;
      }
      setAppReady(false);
      try{await Sync.start();}
      catch(e){console.error('Startup sync:',e);toast.error('Could not load live data: '+e.message);}
      try{await seedDefaultPlans();runAutoExpire();Backup.dailySnapshot().catch(e=>console.warn('Snapshot:',e.message));}
      catch(e){console.warn('Post-login tasks:',e.message);}
      if(!alive)return;
      setUser(profile);setPage('dashboard');setAppReady(true);
    });
    return()=>{alive=false;off&&off();};
  },[]);

  useEffect(()=>{ // live sync of expenses + notifications once someone is logged in
    if(!user)return;
    xpStartLive();
    return()=>xpStopLive();
  },[user&&user.id]);

  useEffect(()=>{
    document.documentElement.setAttribute('data-theme',theme);
    S.set(SK.THEME,theme);
  },[theme]);

  if(resetParams)return<><ResetPasswordPage oobCode={resetParams.oobCode} onDone={()=>{try{window.history.replaceState({},'',window.location.pathname);}catch(e){}setResetParams(null);}}/></>;

  if(!appReady)return(
    <div className="loading-wrap">
      <img src={ARCTIC_LOGO_URI} alt="Arctic Books" style={{width:'min(280px,70vw)',height:'auto'}}/>
      <div className="spinner"/>
      <div style={{fontSize:12,color:'var(--text3)'}}>Loading Arctic Gym Management…</div>
    </div>
  );

  const gymSettings=S.get(SK.SETTINGS,{})||{}; // re-read each render; settingsTick forces a render after save

  if(!user)return<><Login onLogin={()=>{}} settings={gymSettings}/><Toast/></>;

  const isSuper=user.role==='superadmin';
  const isAdmin=user.role==='superadmin'||user.role==='staff';
  const isTrainer=user.role==='trainer';

  // NAV CONFIG per role
  const superNav=[
    {key:'dashboard',label:'Dashboard',icon:'dashboard',section:'Main'},
    {key:'members',label:'Members',icon:'users',section:'Gym'},
    {key:'invoices',label:'Invoices',icon:'receipt',section:'Gym'},
    {key:'expenses',label:'Expenses',icon:'wallet',section:'Gym'},
    {key:'plans',label:'Plans',icon:'dumbbell',section:'Gym'},
    {key:'sales',label:'Sales Funnel',icon:'kanban',section:'Gym'},
    {key:'reports',label:'Reports',icon:'reports',section:'Gym'},
    {key:'users',label:'Users',icon:'usercog',section:'Admin'},
    {key:'safety',label:'Data Safety',icon:'check',section:'Admin'},
    {key:'settings',label:'Gym Settings',icon:'settings',section:'Admin'},
  ];
  const staffNav=[
    {key:'dashboard',label:'Dashboard',icon:'dashboard',section:'Main'},
    {key:'members',label:'Members',icon:'users',section:'Gym'},
    {key:'invoices',label:'Invoices',icon:'receipt',section:'Gym'},
    {key:'expenses',label:'Expenses',icon:'wallet',section:'Gym'},
    {key:'sales',label:'Sales Funnel',icon:'kanban',section:'Gym'},
  ];
  const trainerNav=[
    {key:'dashboard',label:'My Members',icon:'dumbbell',section:'Main'},
  ];
  const navItems=isSuper?superNav:isTrainer?trainerNav:staffNav;

  const PAGES={
    dashboard:()=>isTrainer?<TrainerView user={user}/>:<Dashboard user={user}/>,
    expenses:()=>isTrainer?<TrainerView user={user}/>:<Expenses user={user} seed={expSeed}/>,
    members:()=><Members user={user} searchSeed={searchSeed.page==='members'?searchSeed:null}/>,
    invoices:()=><Invoices user={user} searchSeed={searchSeed.page==='invoices'?searchSeed:null}/>,
    plans:()=><Plans user={user}/>,
    sales:()=><SalesFunnel user={user}/>,
    reports:()=>isSuper?<Reports user={user}/>:<Dashboard user={user}/>,
    users:()=><UsersAdmin user={user}/>,
    safety:()=>isSuper?<DataSafety user={user}/>:<Dashboard user={user}/>,
    settings:()=><GymSettings user={user} onSaved={()=>setSettingsTick(t=>t+1)}/>,
  };

  const nav=(key)=>{setPage(key);setMobOpen(false);};
  const goTo=(key,status)=>{if(status)setExpSeed({status,token:Date.now()});nav(key);};
  const pendingExpN=isSuper?xpList(XP_KEY).filter(e=>e.status==='pending').length:0;
  const logout=async()=>{xpStopLive();await Auth.signOut();clearLocalData();window.location.reload();};   // reload = nothing of this user stays in memory

  // Group nav items by section
  const sections=[...new Set(navItems.map(n=>n.section))];

  return(
    <div style={{display:'flex',minHeight:'100vh'}}>
      <Toast/>
      {mobOpen&&<div className="mobile-overlay" onClick={()=>setMobOpen(false)}/>}

      {/* ── SIDEBAR ── */}
      <nav className={`sidebar${sidebarCollapsed?' collapsed':''}${mobOpen?' mob-open':''}`}>
        <div className="sidebar-logo" onClick={()=>setSidebarCollapsed(c=>!c)}>
          <GymLogo size={32} radius={9} src={gymSettings.logo}/>
          <div>
            {gymSettings.name
              ? <div className="sidebar-brand">{gymSettings.name}</div>
              : <div className="sidebar-brand">Arctic Gym <span>Management</span></div>}
            {gymSettings.name&&<div className="sidebar-sub">Gym Management</div>}
          </div>
        </div>

        <div className="sidebar-nav">
          {sections.map((section,si)=>(
            <React.Fragment key={section}>
              {si>0&&<div className="nav-sep"/>}
              <div className="sidebar-section-label">{section}</div>
              {navItems.filter(n=>n.section===section).map(n=>(
                <button key={n.key} className={`nav-item${page===n.key?' active':''}`} onClick={()=>nav(n.key)}>
                  <span className="nav-icon"><Ic n={n.icon} s={17}/></span>
                  <span className="nav-label">{n.label}</span>
                  {n.key==='expenses'&&pendingExpN>0&&<span className="nav-badge red">{pendingExpN}</span>}
                </button>
              ))}
            </React.Fragment>
          ))}
        </div>

        <div className="sidebar-arctic"><ArcticBooksBadge compact={sidebarCollapsed}/></div>

        <div className="sidebar-bottom">
          <div className="sidebar-user">
            <div className="avatar" style={{width:30,height:30,fontSize:12,flexShrink:0}}>{user.name[0]}</div>
            <div className="nav-label" style={{minWidth:0}}>
              <div className="sidebar-user-name">{user.name}</div>
              <div className="sidebar-user-role">{user.role}</div>
            </div>
          </div>
          <button className="nav-item" onClick={()=>setShowPw(true)}>
            <span className="nav-icon"><Ic n="key" s={17}/></span>
            <span className="nav-label">Change password</span>
          </button>
          {showPw&&<ChangePasswordModal onClose={()=>setShowPw(false)}/>}
          <button className="nav-item danger" onClick={logout}>
            <span className="nav-icon"><Ic n="logout" s={17}/></span>
            <span className="nav-label">Logout</span>
          </button>
        </div>
      </nav>

      {/* ── MAIN ── */}
      <div className={`main-wrapper${sidebarCollapsed?' collapsed':''}`}>
        <div className="topbar">
          <button className="mob-ham" onClick={()=>setMobOpen(o=>!o)}>
            <div/><div/><div/>
          </button>
          <div className="breadcrumb">
            <span>{gymSettings.name||'Arctic Gym Management'}</span>
            <span style={{color:'var(--border2)'}}>›</span>
            <span className="cur">{navItems.find(n=>n.key===page)?.label||'Dashboard'}</span>
          </div>
          <GlobalSearch onNavigate={(pg,qv)=>{setPage(pg);setSearchSeed({page:pg,query:qv,token:Date.now()});}}/>
          <div className="topbar-spacer"/>
          {!isTrainer&&<NotificationBell user={user} onOpen={()=>goTo('expenses')}/>}
          <div className="topbar-icon-btn" onClick={()=>setTheme(t=>t==='dark'?'light':'dark')} title="Toggle theme">
            {theme==='dark'?<Ic n="sun" s={15}/>:<Ic n="moon" s={15}/>}
          </div>
          <div className="topbar-user">
            <div className="topbar-avatar">{user.name[0]}</div>
            <div>
              <div className="topbar-user-name">{gymSettings.name||'Arctic Gym Management'}</div>
              <div className="topbar-user-role">{user.name} · {user.role}</div>
            </div>
          </div>
        </div>

        <div className="app-body page-enter" key={page}>
          {!Store.ready&&<div style={{background:'var(--danger-bg)',border:'1px solid var(--red)',color:'var(--red)',borderRadius:10,padding:'10px 14px',marginBottom:14,fontSize:12.5,fontWeight:600}}>
            ⚠ READ-ONLY — {Store.reason||'Not connected. Changes cannot be saved.'}
          </div>}
          {(PAGES[page]||PAGES.dashboard)()}
        </div>
      </div>
    </div>
  );
};

/* ══════════════════════════════════════════════════════════
   🛡️  ERROR BOUNDARY — never show a blank screen again.
   Catches any unexpected crash and shows a recoverable message
   instead of leaving the page blank.
   ══════════════════════════════════════════════════════════ */
class ErrorBoundary extends React.Component{
  constructor(props){super(props);this.state={hasError:false,msg:''};}
  static getDerivedStateFromError(err){return{hasError:true,msg:err?.message||'Unknown error'};}
  componentDidCatch(err,info){console.error('Arctic Gym Management crashed:',err,info);}
  render(){
    if(this.state.hasError){
      return(
        <div style={{minHeight:'100vh',display:'flex',flexDirection:'column',alignItems:'center',
          justifyContent:'center',background:'#080B0F',color:'#F0F6FC',padding:24,gap:14,textAlign:'center'}}>
          <GymLogo size={48} radius={14}/>
          <div style={{fontSize:16,fontWeight:700,fontFamily:'Sora,sans-serif'}}>Something went wrong</div>
          <div style={{fontSize:13,color:'#8B949E',maxWidth:420}}>
            Arctic Gym Management hit an unexpected error and stopped instead of showing a blank page.
            Your data is safe in this browser's local storage. Try reloading — if it keeps happening,
            check that your internet connection allows this page to load its scripts.
          </div>
          <div style={{fontSize:11,color:'#6E7681',fontFamily:'monospace',maxWidth:420,wordBreak:'break-word'}}>{this.state.msg}</div>
          <button className="btn btn-primary" onClick={()=>window.location.reload()}>Reload App</button>
        </div>
      );
    }
    return this.props.children;
  }
}

ReactDOM.createRoot(document.getElementById('root')).render(<ErrorBoundary><App/></ErrorBoundary>);