const sidebar=document.querySelector('.sidebar'),menuToggle=document.querySelector('.menu-toggle'),mobileBackdrop=document.querySelector('.mobile-backdrop'),sidebarCollapse=document.querySelector('.sidebar-collapse'),mobileNav=window.matchMedia('(max-width:920px)');
let returnFocus=null;

// Consolidated daily/weekly cash movement view.
const cashViewTabs=Array.from(document.querySelectorAll('[data-cash-view]'));
const cashViewPanels=Array.from(document.querySelectorAll('[data-cash-panel]'));
function showCashMovementView(view,focus=false){
  cashViewTabs.forEach(tab=>{
    const active=tab.dataset.cashView===view;
    tab.setAttribute('aria-selected',active?'true':'false');
    tab.tabIndex=active?0:-1;
    if(active&&focus)tab.focus();
  });
  cashViewPanels.forEach(panel=>{panel.hidden=panel.dataset.cashPanel!==view});
}
cashViewTabs.forEach((tab,index)=>{
  tab.addEventListener('click',()=>showCashMovementView(tab.dataset.cashView));
  tab.addEventListener('keydown',event=>{
    if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return;
    event.preventDefault();
    let next=index;
    if(event.key==='ArrowRight')next=(index+1)%cashViewTabs.length;
    if(event.key==='ArrowLeft')next=(index-1+cashViewTabs.length)%cashViewTabs.length;
    if(event.key==='Home')next=0;
    if(event.key==='End')next=cashViewTabs.length-1;
    showCashMovementView(cashViewTabs[next].dataset.cashView,true);
  });
});
function syncSidebarAccessibility(){
  const isMobile=mobileNav.matches,isOpen=sidebar?.classList.contains('open')||false;
  if(isMobile){document.body.classList.remove('sidebar-collapsed');if(sidebar)sidebar.inert=!isOpen;if(mobileBackdrop)mobileBackdrop.hidden=!isOpen;menuToggle?.setAttribute('aria-expanded',isOpen?'true':'false');menuToggle?.setAttribute('aria-label',isOpen?'Close navigation':'Open navigation')}
  else{if(sidebar)sidebar.inert=false;if(mobileBackdrop)mobileBackdrop.hidden=true;menuToggle?.setAttribute('aria-expanded','false');const collapsed=document.body.classList.contains('sidebar-collapsed');sidebarCollapse?.setAttribute('aria-expanded',collapsed?'false':'true');sidebarCollapse?.setAttribute('aria-label',collapsed?'Expand navigation':'Collapse navigation')}
}

// Finance control centre interactions.
document.querySelectorAll('.match-form').forEach(form=>{
  const type=form.querySelector('[data-match-type]'),target=form.querySelector('[data-match-id]');
  if(!type||!target)return;
  const sync=()=>{const selected=type.value;Array.from(target.querySelectorAll('option')).forEach(option=>{option.hidden=selected==='ignored'||option.dataset.type!==selected});target.disabled=selected==='ignored';const first=target.querySelector(`option[data-type="${selected}"]`);if(first)target.value=first.value};
  type.addEventListener('change',sync);sync();
});

document.querySelectorAll('[data-stock-receipt]').forEach(form=>{
  const host=form.querySelector('[data-stock-lines]'),template=form.querySelector('[data-stock-line-template]'),grand=form.querySelector('[data-stock-grand-total]');
  if(!host||!template)return;
  const recalc=()=>{let total=0;host.querySelectorAll('.stock-receipt-line').forEach((line,index)=>{const product=line.querySelector('[data-stock-product]'),qty=line.querySelector('[data-stock-qty]'),cost=line.querySelector('[data-stock-cost]'),value=Math.max(0,Number(qty.value)||0)*Math.max(0,Number(cost.value)||0);product.name=`items[${index}][product_id]`;qty.name=`items[${index}][quantity]`;cost.name=`items[${index}][unit_cost]`;line.querySelector('[data-stock-total]').textContent=`USD ${value.toFixed(2)}`;total+=value});if(grand)grand.textContent=`USD ${total.toFixed(2)}`};
  const add=()=>{const line=template.content.firstElementChild.cloneNode(true);host.appendChild(line);const product=line.querySelector('[data-stock-product]'),cost=line.querySelector('[data-stock-cost]');product.addEventListener('change',()=>{if(!cost.value)cost.value=product.selectedOptions[0]?.dataset.cost||'0';recalc()});line.querySelectorAll('input').forEach(input=>input.addEventListener('input',recalc));line.querySelector('[data-remove-stock-line]').addEventListener('click',()=>{line.remove();if(!host.children.length)add();recalc()});recalc()};
  form.querySelector('[data-add-stock-line]')?.addEventListener('click',add);add();
});
function setMobileNav(open){if(!sidebar||!mobileNav.matches)return;if(open){returnFocus=document.activeElement;sidebar.classList.add('open');document.body.classList.add('nav-open');syncSidebarAccessibility();sidebar.querySelector('a')?.focus()}else{sidebar.classList.remove('open');document.body.classList.remove('nav-open');syncSidebarAccessibility();if(returnFocus instanceof HTMLElement)returnFocus.focus();returnFocus=null}}
if(!mobileNav.matches&&localStorage.getItem('sodazw-sidebar-collapsed')==='1')document.body.classList.add('sidebar-collapsed');
menuToggle?.addEventListener('click',()=>setMobileNav(!sidebar?.classList.contains('open')));
sidebarCollapse?.addEventListener('click',()=>{if(mobileNav.matches)return;document.body.classList.toggle('sidebar-collapsed');localStorage.setItem('sodazw-sidebar-collapsed',document.body.classList.contains('sidebar-collapsed')?'1':'0');syncSidebarAccessibility()});
mobileBackdrop?.addEventListener('click',()=>setMobileNav(false));
document.querySelectorAll('.sidebar nav a').forEach(link=>link.addEventListener('click',()=>{if(mobileNav.matches)setMobileNav(false)}));
document.addEventListener('keydown',event=>{if(event.key==='Escape'){setMobileNav(false);document.querySelectorAll('.create-menu[open]').forEach(menu=>menu.removeAttribute('open'))}});
mobileNav.addEventListener?.('change',()=>{sidebar?.classList.remove('open');document.body.classList.remove('nav-open');if(!mobileNav.matches&&localStorage.getItem('sodazw-sidebar-collapsed')==='1')document.body.classList.add('sidebar-collapsed');syncSidebarAccessibility()});
syncSidebarAccessibility();
document.addEventListener('click',event=>{document.querySelectorAll('.create-menu[open]').forEach(menu=>{if(!menu.contains(event.target))menu.removeAttribute('open')})});
const presetCustomer=new URLSearchParams(location.search).get('customer_id');
const customerSelect=document.querySelector('.document-form select[name="customer_id"]');
if(presetCustomer&&customerSelect)customerSelect.value=presetCustomer;
const documentForm=document.querySelector('.document-form');
if(documentForm){
  const notesGrid=documentForm.querySelector('textarea[name="notes"]')?.closest('.form-grid');
  if(notesGrid){
    const operations=document.createElement('div');operations.className='form-grid order-details';
    operations.innerHTML='<h2>Order & fulfilment</h2><label>Customer PO / reference<input name="customer_reference" placeholder="Optional purchase order or reference"></label><label>Order source<select name="order_source"><option>WhatsApp</option><option>Website</option><option>Walk-in</option><option>Phone</option><option>Social media</option><option>Other</option></select></label><label>Customer receives order by<select name="fulfilment_method" data-fulfilment><option>Pickup</option><option>Delivery</option></select></label><label class="full" data-delivery-address style="display:none">Delivery or pickup details<input name="delivery_address" placeholder="Pickup at 100 Livingstone Avenue or enter delivery address"></label>';
    notesGrid.parentNode.insertBefore(operations,notesGrid);
    const fulfilment=operations.querySelector('[data-fulfilment]'),address=operations.querySelector('[data-delivery-address]');const toggleAddress=()=>address.style.display=fulfilment.value==='Delivery'?'grid':'none';fulfilment.addEventListener('change',toggleAddress);toggleAddress();
    const documentId=new URLSearchParams(location.search).get('id');if(documentId)fetch('document-meta.php?id='+encodeURIComponent(documentId),{credentials:'same-origin'}).then(r=>r.ok?r.json():null).then(meta=>{if(!meta)return;operations.querySelector('[name="customer_reference"]').value=meta.customer_reference||'';operations.querySelector('[name="order_source"]').value=meta.order_source||'WhatsApp';fulfilment.value=meta.fulfilment_method||'Pickup';operations.querySelector('[name="delivery_address"]').value=meta.delivery_address||'';toggleAddress()}).catch(()=>{});
  }
}
const docActions=document.querySelector('.doc-actions'),docType=document.querySelector('.document-title h2')?.textContent.trim().toLowerCase();
if(docActions&&new URLSearchParams(location.search).get('share')==='1'){docActions.classList.add('sharing-ready');requestAnimationFrame(()=>docActions.scrollIntoView({behavior:'smooth',block:'center'}))}
const documentStatusSelect=docActions?.querySelector('select[name="status"]');
if(documentStatusSelect&&docType==='invoice'){
  const currentStatus=document.querySelector('.document-title .status')?.textContent.trim().toLowerCase();
  Array.from(documentStatusSelect.options).forEach(option=>{if(['accepted','rejected'].includes(option.value)||(option.value==='draft'&&currentStatus!=='draft'))option.remove()});
}
if(docActions&&docType==='quotation'){
  const currentStatus=document.querySelector('.document-title .status')?.textContent.trim().toLowerCase(),convertForm=docActions.querySelector('form input[name="action"][value="convert_quote"]')?.closest('form');
  if(convertForm&&currentStatus!=='accepted'){convertForm.hidden=true;documentStatusSelect?.setAttribute('title','Mark the quotation accepted after customer confirmation before converting it')}
}
if(docActions&&docType==='invoice'){
  const csrf=docActions.querySelector('input[name="csrf"]');const invoiceId=new URLSearchParams(location.search).get('id');
  if(invoiceId)fetch('document-meta.php?id='+encodeURIComponent(invoiceId),{credentials:'same-origin'}).then(r=>r.ok?r.json():null).then(meta=>{if(!meta)return;const viewed=document.createElement('span');viewed.className='invoice-view-status '+(Number(meta.share_view_count)>0?'viewed':'not-viewed');viewed.textContent=Number(meta.share_view_count)>0?'Customer viewed '+meta.share_view_count+' time'+(Number(meta.share_view_count)===1?'':'s'):'Not viewed by customer';if(meta.share_last_viewed_at)viewed.title='Last viewed '+meta.share_last_viewed_at;docActions.prepend(viewed);const documentMeta=document.querySelector('.document-card .document-meta');if(documentMeta){const extra=document.createElement('div');extra.className='invoice-operation-summary';[['PO / reference',meta.customer_reference||'Not supplied'],['Order source',meta.order_source||'WhatsApp'],['Fulfilment',meta.fulfilment_method||'Pickup'],['Delivery / pickup details',meta.delivery_address||((meta.fulfilment_method||'Pickup')==='Pickup'?'100 Livingstone Avenue':'Not supplied')]].forEach(([label,value])=>{const item=document.createElement('div'),strong=document.createElement('strong'),span=document.createElement('span');strong.textContent=label;span.textContent=value;item.append(strong,span);extra.appendChild(item)});documentMeta.insertAdjacentElement('afterend',extra)}}).catch(()=>{});
  if(csrf&&invoiceId){const form=document.createElement('form');form.method='post';form.innerHTML='<input type="hidden" name="action" value="fulfil_invoice"><input type="hidden" name="id" value="'+invoiceId+'"><input type="hidden" name="csrf" value="'+csrf.value+'"><button class="button primary" type="submit">Fulfil order & deduct stock</button>';form.addEventListener('submit',e=>{if(!confirm('Confirm this order has been supplied? Tracked stock will be deducted once.'))e.preventDefault()});docActions.appendChild(form);}
}
document.addEventListener('click',e=>{
  const add=e.target.closest('[data-add-item]'); if(add){
    const body=document.querySelector('#items-body'), row=body.querySelector('tr').cloneNode(true);
    row.querySelectorAll('input,select').forEach(el=>{if(el.tagName==='SELECT')el.selectedIndex=0;else if(el.name.includes('quantity'))el.value='1';else if(el.name.includes('tax_rate'))el.value=add.dataset.tax||'0';else el.value='';}); body.appendChild(row); renumber(); calculate();
  }
  const remove=e.target.closest('[data-remove-item]'); if(remove){const rows=document.querySelectorAll('#items-body tr'); if(rows.length>1)remove.closest('tr').remove(); else remove.closest('tr').querySelectorAll('input').forEach(i=>i.value='');renumber();calculate();}
});
function renumber(){document.querySelectorAll('#items-body tr').forEach((row,i)=>row.querySelectorAll('[name]').forEach(el=>el.name=el.name.replace(/items\[\d+\]/,`items[${i}]`)));}
function calculate(){let subtotal=0,tax=0;document.querySelectorAll('#items-body tr').forEach(row=>{const q=parseFloat(row.querySelector('[data-qty]')?.value)||0,p=parseFloat(row.querySelector('[data-price]')?.value)||0,r=parseFloat(row.querySelector('[data-tax]')?.value)||0,line=q*p;subtotal+=line;tax+=line*r/100;row.querySelector('[data-line]').textContent=line.toFixed(2)});const dtype=document.querySelector('[name=discount_type]')?.value,d=parseFloat(document.querySelector('[name=discount_value]')?.value)||0,delivery=parseFloat(document.querySelector('[name=delivery_fee]')?.value)||0,discount=dtype==='percent'?subtotal*d/100:Math.min(subtotal,d),total=Math.max(0,subtotal-discount+tax+delivery);document.querySelector('[data-subtotal]')&&(document.querySelector('[data-subtotal]').textContent=subtotal.toFixed(2));document.querySelector('[data-tax-total]')&&(document.querySelector('[data-tax-total]').textContent=tax.toFixed(2));document.querySelector('[data-total]')&&(document.querySelector('[data-total]').textContent=total.toFixed(2));}
document.addEventListener('input',e=>{if(e.target.closest('.document-form'))calculate()}); document.addEventListener('change',e=>{if(e.target.closest('.document-form'))calculate()}); calculate();
document.addEventListener('change',e=>{if(e.target.matches('[data-product]')){const option=e.target.selectedOptions[0],row=e.target.closest('tr');if(option?.value){row.querySelector('[name*="description"]').value=option.dataset.name||'';row.querySelector('[data-price]').value=option.dataset.price||'0';row.querySelector('[data-tax]').value=option.dataset.tax||'0';calculate();}}});
document.querySelectorAll('[data-confirm]').forEach(el=>el.addEventListener('click',e=>{if(!confirm(el.dataset.confirm))e.preventDefault()}));
const websiteInvoiceForm=Array.from(document.querySelectorAll('form')).find(form=>form.querySelector('input[name="action"][value="convert_web_order"]'));
if(websiteInvoiceForm){
  const reviewCards=document.querySelectorAll('.order-review-grid>div');const isDelivery=Array.from(reviewCards).some(card=>card.querySelector('h3')?.textContent.trim()==='Fulfilment'&&card.querySelector('strong')?.textContent.trim()==='Delivery');
  if(isDelivery){const fee=document.createElement('label');fee.className='website-delivery-fee';fee.innerHTML='Confirmed delivery fee (USD)<input type="number" name="delivery_fee" min="0.01" step="0.01" placeholder="Required for delivery" required><small>Quote this according to the customer location. It will be added to the draft invoice.</small>';websiteInvoiceForm.insertBefore(fee,websiteInvoiceForm.querySelector('button'));}
  else{const input=document.createElement('input');input.type='hidden';input.name='delivery_fee';input.value='0';websiteInvoiceForm.appendChild(input);}
}
function updatePaymentPreview(){const form=document.querySelector('.payment-form');if(!form)return;const account=form.querySelector('[data-payment-account]'),currency=account?.selectedOptions[0]?.dataset.currency||'',invoice=form.querySelector('[data-invoice-currency]')?.value||'USD',received=parseFloat(form.querySelector('[data-received]')?.value)||0,rateInput=form.querySelector('[data-exchange-rate]');if(currency&&currency===invoice)rateInput.value='1';const rate=parseFloat(rateInput?.value)||1;form.querySelector('[data-applied]').textContent=(received/rate).toFixed(2)}
document.addEventListener('input',e=>{if(e.target.closest('.payment-form'))updatePaymentPreview()});document.addEventListener('change',e=>{if(e.target.closest('.payment-form'))updatePaymentPreview()});updatePaymentPreview();

const refillInvoiceLink=document.querySelector('.page-refills .crm-action-row a[href*="page=document-edit"][href*="type=invoice"]');
if(refillInvoiceLink){
  const refillId=new URLSearchParams(location.search).get('id');
  const csrf=document.querySelector('.page-refills form input[name="csrf"]')?.value;
  if(refillId&&csrf){
    const form=document.createElement('form');form.method='post';form.className='inline-operation-form';
    form.innerHTML='<input type="hidden" name="csrf" value="'+csrf+'"><input type="hidden" name="action" value="create_refill_invoice"><input type="hidden" name="refill_id" value="'+refillId+'"><button class="button secondary" type="submit">Create linked invoice</button>';
    form.addEventListener('submit',event=>{if(!confirm('Create a draft invoice using this job\'s cylinder price and delivery fee?'))event.preventDefault()});
    refillInvoiceLink.replaceWith(form);
  }
}

document.querySelectorAll('a[href="index.php?page=document-edit&type=invoice"]').forEach(link=>{
  if(!link.closest('.page-refills .crm-action-row'))link.href='quick-invoice.php';
});
document.querySelectorAll('a[href="index.php?page=document-edit&type=quotation"]').forEach(link=>link.href='quick-invoice.php?type=quotation');

const quickInvoice=document.querySelector('[data-quick-invoice]');
if(quickInvoice){
  const existingCustomerPanel=quickInvoice.querySelector('[data-existing-customer]'),existingCustomerSelect=quickInvoice.querySelector('[name="customer_id"]');
  if(existingCustomerPanel&&existingCustomerSelect){
    const presetCustomerId=new URLSearchParams(location.search).get('customer_id');if(presetCustomerId)existingCustomerSelect.value=presetCustomerId;
    const customerSearch=document.createElement('label');customerSearch.className='quick-customer-search';customerSearch.innerHTML='Find customer<input type="search" placeholder="Search name or company" autocomplete="off">';existingCustomerPanel.prepend(customerSearch);
    customerSearch.querySelector('input').addEventListener('input',event=>{const query=event.target.value.trim().toLowerCase();Array.from(existingCustomerSelect.options).forEach((option,index)=>{if(index===0)return;option.hidden=query!==''&&!option.textContent.toLowerCase().includes(query)});if(existingCustomerSelect.selectedOptions[0]?.hidden)existingCustomerSelect.value=''});
  }
  const primaryCreateButton=quickInvoice.querySelector('.quick-summary button[type="submit"]');
  if(primaryCreateButton){primaryCreateButton.name='next_action';primaryCreateButton.value='review';primaryCreateButton.textContent='Create draft & review';const shareButton=document.createElement('button');shareButton.type='submit';shareButton.name='next_action';shareButton.value='share';shareButton.className='button secondary quick-share-next';shareButton.textContent='Create draft & open sharing';primaryCreateButton.insertAdjacentElement('afterend',shareButton)}
  const syncCustomerMode=()=>{const isNew=quickInvoice.querySelector('[name="customer_mode"]:checked')?.value==='new',existing=quickInvoice.querySelector('[data-existing-customer]'),newFields=quickInvoice.querySelector('[data-new-customer]'),existingSelect=quickInvoice.querySelector('[name="customer_id"]'),newName=quickInvoice.querySelector('[name="new_customer_name"]');existing.style.display=isNew?'none':'block';newFields.style.display=isNew?'grid':'none';existingSelect.required=!isNew;newName.required=isNew};
  const calculateQuickInvoice=()=>{
    let subtotal=0,tax=0;
    quickInvoice.querySelectorAll('.quick-product input[type="number"]').forEach(input=>{const quantity=parseFloat(input.value)||0,price=parseFloat(input.dataset.price)||0,rate=parseFloat(input.dataset.tax)||0;subtotal+=quantity*price;tax+=quantity*price*rate/100});
    const customQuantity=parseFloat(quickInvoice.querySelector('[data-custom-qty]')?.value)||0,customPrice=parseFloat(quickInvoice.querySelector('[data-custom-price]')?.value)||0;subtotal+=customQuantity*customPrice;
    const isDelivery=quickInvoice.querySelector('[name="fulfilment_method"]:checked')?.value==='Delivery',delivery=isDelivery?(parseFloat(quickInvoice.querySelector('[data-delivery-fee]')?.value)||0):0;
    quickInvoice.querySelector('[data-delivery-fields]').style.display=isDelivery?'grid':'none';
    quickInvoice.querySelector('[data-quick-subtotal]').textContent=subtotal.toFixed(2);quickInvoice.querySelector('[data-quick-tax]').textContent=tax.toFixed(2);quickInvoice.querySelector('[data-quick-delivery]').textContent=delivery.toFixed(2);quickInvoice.querySelector('[data-quick-total]').textContent=(subtotal+tax+delivery).toFixed(2);
    const isNew=quickInvoice.querySelector('[name="customer_mode"]:checked')?.value==='new',customerName=isNew?quickInvoice.querySelector('[name="new_customer_name"]')?.value.trim():quickInvoice.querySelector('[name="customer_id"]')?.selectedOptions[0]?.textContent.trim(),summaryCustomer=quickInvoice.querySelector('[data-summary-customer]');if(summaryCustomer)summaryCustomer.textContent=customerName&&customerName!=='Select customer'?customerName:'New document';
    const selectedInputs=Array.from(quickInvoice.querySelectorAll('.quick-product input[type="number"]')).filter(input=>(parseFloat(input.value)||0)>0),customSelected=customQuantity>0&&customPrice>=0,lineCount=selectedInputs.length+(customSelected?1:0),totalUnits=selectedInputs.reduce((sum,input)=>sum+(parseFloat(input.value)||0),0)+(customSelected?customQuantity:0),lineSummary=quickInvoice.querySelector('[data-summary-lines]');if(lineSummary)lineSummary.textContent=lineCount?lineCount+' line item'+(lineCount===1?'':'s')+' · '+totalUnits+' unit'+(totalUnits===1?'':'s'):'No items selected';
  };
  const sourceCatalog=quickInvoice.querySelector('.quick-products');
  if(sourceCatalog){
    sourceCatalog.classList.add('expert-source-catalog');quickInvoice.querySelector('.quick-search')?.classList.add('expert-source-search');
    const sourceRows=Array.from(sourceCatalog.querySelectorAll('.quick-product')),studio=document.createElement('div');studio.className='item-studio';
    const pickerBar=document.createElement('div');pickerBar.className='item-picker-bar';
    const productSearch=document.createElement('input');productSearch.type='search';productSearch.placeholder='Search products';productSearch.setAttribute('aria-label','Search Soda ZW products');
    const picker=document.createElement('select');picker.setAttribute('aria-label','Choose a product');
    const populatePicker=query=>{const current=picker.value;picker.replaceChildren();const placeholder=document.createElement('option');placeholder.value='';placeholder.textContent='Choose a product';picker.appendChild(placeholder);sourceRows.forEach((row,index)=>{const name=row.querySelector('strong').textContent,price=row.querySelector('em').textContent;if(query&&!(name+' '+price).toLowerCase().includes(query))return;const option=document.createElement('option');option.value=String(index);option.textContent=name+' — '+price;picker.appendChild(option)});if(Array.from(picker.options).some(option=>option.value===current))picker.value=current};
    populatePicker('');productSearch.addEventListener('input',()=>populatePicker(productSearch.value.trim().toLowerCase()));
    const addButton=document.createElement('button');addButton.type='button';addButton.className='button secondary';addButton.textContent='+ Add item';pickerBar.append(productSearch,picker,addButton);
    const popular=document.createElement('div');popular.className='popular-products';sourceRows.slice(0,6).forEach((row,index)=>{const chip=document.createElement('button');chip.type='button';chip.textContent=row.querySelector('strong').textContent;chip.addEventListener('click',()=>{const input=row.querySelector('input');input.value=Math.max(1,parseFloat(input.value)||0);renderSelected();calculateQuickInvoice()});popular.appendChild(chip)});
    const selectedList=document.createElement('div');selectedList.className='selected-item-list';studio.append(pickerBar,popular,selectedList);sourceCatalog.before(studio);
    const renderSelected=()=>{selectedList.replaceChildren();const active=sourceRows.filter(row=>(parseFloat(row.querySelector('input').value)||0)>0);if(!active.length){const empty=document.createElement('div');empty.className='selected-items-empty';empty.innerHTML='<b>No items yet</b><span>Choose a product above or use a quick-add button.</span>';selectedList.appendChild(empty);return}active.forEach(row=>{const sourceInput=row.querySelector('input'),item=document.createElement('div');item.className='selected-item';const copy=document.createElement('span');const title=document.createElement('strong');title.textContent=row.querySelector('strong').textContent;const meta=document.createElement('small');meta.textContent=row.querySelector('small').textContent;copy.append(title,meta);const price=document.createElement('b');price.textContent=row.querySelector('em').textContent;const controls=document.createElement('div');controls.className='item-quantity';const minus=document.createElement('button');minus.type='button';minus.textContent='−';minus.setAttribute('aria-label','Decrease quantity for '+title.textContent);const qty=document.createElement('input');qty.type='number';qty.min='0';qty.step='1';qty.value=sourceInput.value;qty.setAttribute('aria-label','Quantity for '+title.textContent);const plus=document.createElement('button');plus.type='button';plus.textContent='+';plus.setAttribute('aria-label','Increase quantity for '+title.textContent);const remove=document.createElement('button');remove.type='button';remove.className='remove-selected-item';remove.textContent='×';remove.setAttribute('aria-label','Remove '+title.textContent);minus.addEventListener('click',()=>{sourceInput.value=Math.max(0,(parseFloat(sourceInput.value)||0)-1);renderSelected();calculateQuickInvoice()});plus.addEventListener('click',()=>{sourceInput.value=(parseFloat(sourceInput.value)||0)+1;renderSelected();calculateQuickInvoice()});qty.addEventListener('input',()=>{sourceInput.value=Math.max(0,parseFloat(qty.value)||0);calculateQuickInvoice()});remove.addEventListener('click',()=>{sourceInput.value='0';renderSelected();calculateQuickInvoice()});controls.append(minus,qty,plus);item.append(copy,price,controls,remove);selectedList.appendChild(item)})};
    addButton.addEventListener('click',()=>{if(picker.value==='')return;const input=sourceRows[Number(picker.value)]?.querySelector('input');if(input){input.value=Math.max(1,parseFloat(input.value)||0);picker.value='';renderSelected();calculateQuickInvoice()}});picker.addEventListener('change',()=>{if(picker.value!=='')addButton.focus()});renderSelected();
  }
  quickInvoice.addEventListener('input',calculateQuickInvoice);quickInvoice.addEventListener('change',event=>{if(event.target.name==='customer_mode')syncCustomerMode();if(event.target.name==='customer_id'){const option=event.target.selectedOptions[0],address=quickInvoice.querySelector('[name="delivery_address"]');if(address&&!address.value)address.value=[option?.dataset.address,option?.dataset.area].filter(Boolean).join(', ')}calculateQuickInvoice()});
  quickInvoice.querySelector('[data-product-search]')?.addEventListener('input',event=>{const query=event.target.value.trim().toLowerCase();quickInvoice.querySelectorAll('[data-product-row]').forEach(row=>row.classList.toggle('is-hidden',query!==''&&!row.dataset.name.includes(query)));quickInvoice.querySelectorAll('[data-product-category]').forEach(category=>category.classList.toggle('is-empty',!category.querySelector('[data-product-row]:not(.is-hidden)')))});
  const totalAnnouncement=quickInvoice.querySelector('[data-quick-total]')?.parentElement;if(totalAnnouncement){totalAnnouncement.setAttribute('aria-live','polite');totalAnnouncement.setAttribute('aria-atomic','true')}
  syncCustomerMode();calculateQuickInvoice();
}

/* Unified Invoice & Quotation Studio */
const documentStudio=document.querySelector('[data-document-studio]');
if(documentStudio){
  const itemsHost=documentStudio.querySelector('[data-studio-items]'),template=documentStudio.querySelector('[data-studio-item-template]');
  const currency=documentStudio.dataset.currency||'USD';
  let studioDirty=false,studioSubmitting=false;
  const numeric=value=>Math.max(0,Number.parseFloat(value)||0);
  const moneyValue=value=>numeric(value).toFixed(2);
  const workflowButtons=Array.from(document.querySelectorAll('.studio-workflow [data-studio-jump]'));
  const setActiveStudioStep=id=>{
    const index=Math.max(0,workflowButtons.findIndex(button=>button.dataset.studioJump===id));
    workflowButtons.forEach((button,buttonIndex)=>{
      button.classList.toggle('is-active',buttonIndex===index);
      button.classList.toggle('is-complete',buttonIndex<index);
      if(buttonIndex===index)button.setAttribute('aria-current','step');else button.removeAttribute('aria-current');
    });
    const progress=document.querySelector('[data-studio-progress]');
    if(progress)progress.style.width=`${workflowButtons.length>1?(index/(workflowButtons.length-1))*100:0}%`;
  };
  const reindexStudioItems=()=>{
    itemsHost.querySelectorAll('[data-studio-item]').forEach((row,index)=>{
      const fields=[['[data-item-product]','product_id'],['[data-item-description]','description'],['[data-item-qty]','quantity'],['[data-item-price]','unit_price'],['[data-item-tax]','tax_rate']];
      fields.forEach(([selector,key])=>{const field=row.querySelector(selector);if(field)field.name=`items[${index}][${key}]`});
    });
  };
  const calculateStudio=()=>{
    let subtotal=0,tax=0,units=0,activeLines=0;const taxableLines=[];
    itemsHost.querySelectorAll('[data-studio-item]').forEach(row=>{
      const quantity=numeric(row.querySelector('[data-item-qty]')?.value),price=numeric(row.querySelector('[data-item-price]')?.value),rate=numeric(row.querySelector('[data-item-tax]')?.value),description=row.querySelector('[data-item-description]')?.value.trim()||'';
      const line=quantity*price;
      subtotal+=line;taxableLines.push({line,rate,row});
      if(description&&quantity>0){activeLines++;units+=quantity}
      const output=row.querySelector('[data-item-total]');if(output)output.textContent=`${currency} ${line.toFixed(2)}`;
    });
    const discountType=documentStudio.querySelector('[name="discount_type"]')?.value||'fixed',discountInput=numeric(documentStudio.querySelector('[name="discount_value"]')?.value),discount=discountType==='percent'?subtotal*Math.min(100,discountInput)/100:Math.min(subtotal,discountInput);
    const taxableRatio=subtotal>0?(subtotal-discount)/subtotal:0;taxableLines.forEach(item=>{const lineTax=item.line*taxableRatio*item.rate/100;tax+=lineTax;const output=item.row.querySelector('[data-item-total]');if(output)output.textContent=`${currency} ${(item.line+lineTax).toFixed(2)}`});
    const deliverySelected=documentStudio.querySelector('[name="fulfilment_method"]:checked')?.value==='Delivery',delivery=deliverySelected?numeric(documentStudio.querySelector('[data-delivery-fee]')?.value):0,total=Math.max(0,subtotal-discount+tax+delivery);
    [['[data-studio-subtotal]',subtotal],['[data-studio-discount]',discount],['[data-studio-tax]',tax],['[data-studio-delivery]',delivery],['[data-studio-total]',total]].forEach(([selector,value])=>{const node=documentStudio.querySelector(selector);if(node)node.textContent=moneyValue(value)});
    const lineSummary=documentStudio.querySelector('[data-summary-lines]');if(lineSummary)lineSummary.textContent=activeLines?`${activeLines} line${activeLines===1?'':'s'} · ${units.toLocaleString(undefined,{maximumFractionDigits:2})} unit${units===1?'':'s'}`:'No items yet';
    const deliveryFields=documentStudio.querySelector('[data-delivery-fields]');if(deliveryFields)deliveryFields.hidden=!deliverySelected;
    const address=documentStudio.querySelector('[data-delivery-address]'),fee=documentStudio.querySelector('[data-delivery-fee]'),deliveryReady=!deliverySelected||(address?.value.trim()&&numeric(fee?.value)>0),warning=documentStudio.querySelector('[data-delivery-warning]');
    if(address)address.required=false;if(fee)fee.required=false;if(warning)warning.hidden=deliveryReady;
    const customerMode=documentStudio.querySelector('[name="customer_mode"]:checked')?.value;
    const customerReady=customerMode==='new'?Boolean(documentStudio.querySelector('[name="new_customer_name"]')?.value.trim()||documentStudio.querySelector('[name="new_customer_company"]')?.value.trim()):Boolean(documentStudio.querySelector('[data-studio-customer]')?.value);
    const readiness={customer:customerReady,items:activeLines>0,delivery:Boolean(deliveryReady)};
    let readyCount=0;
    Object.entries(readiness).forEach(([key,ready])=>{const item=documentStudio.querySelector(`[data-readiness="${key}"]`);if(item)item.classList.toggle('is-ready',ready);if(ready)readyCount++});
    const readinessScore=Math.round((readyCount/Object.keys(readiness).length)*100),score=documentStudio.querySelector('[data-readiness-score]'),readinessProgress=documentStudio.querySelector('[data-readiness-progress]');
    if(score)score.textContent=String(readinessScore);if(readinessProgress)readinessProgress.style.width=`${readinessScore}%`;
  };
  const updateSummaryCustomer=()=>{
    const isNew=documentStudio.querySelector('[name="customer_mode"]:checked')?.value==='new';
    const newName=documentStudio.querySelector('[name="new_customer_company"]')?.value.trim()||documentStudio.querySelector('[name="new_customer_name"]')?.value.trim();
    const selected=documentStudio.querySelector('[data-studio-customer]')?.selectedOptions[0]?.textContent.trim();
    const output=documentStudio.querySelector('[data-summary-customer]');if(output)output.textContent=(isNew?newName:(selected&&selected!=='Choose a customer'?selected:''))||'No customer selected';
  };
  const syncStudioCustomer=()=>{
    const isNew=documentStudio.querySelector('[name="customer_mode"]:checked')?.value==='new',existing=documentStudio.querySelector('[data-existing-customer]'),newFields=documentStudio.querySelector('[data-new-customer]'),select=documentStudio.querySelector('[data-studio-customer]'),newName=documentStudio.querySelector('[name="new_customer_name"]');
    if(existing)existing.hidden=isNew;if(newFields)newFields.hidden=!isNew;if(select)select.required=!isNew;if(newName)newName.required=isNew;updateSummaryCustomer();
  };
  const configureStudioRow=(row,productData=null)=>{
    const select=row.querySelector('[data-item-product]'),description=row.querySelector('[data-item-description]'),price=row.querySelector('[data-item-price]'),tax=row.querySelector('[data-item-tax]'),qty=row.querySelector('[data-item-qty]');
    if(productData){select.value=String(productData.id||'');description.value=productData.name||'';price.value=productData.price||'0';tax.value=productData.tax||'0';qty.value=productData.quantity||'1'}
    select.addEventListener('change',()=>{const option=select.selectedOptions[0];if(option?.value){description.value=option.dataset.name||option.textContent.trim();price.value=option.dataset.price||'0';tax.value=option.dataset.tax||'0'}calculateStudio()});
    row.querySelector('[data-remove-studio-item]')?.addEventListener('click',()=>{if(itemsHost.querySelectorAll('[data-studio-item]').length===1){select.value='';description.value='';price.value='';qty.value='1';tax.value='0'}else row.remove();reindexStudioItems();calculateStudio();studioDirty=true});
  };
  const addStudioRow=(productData=null)=>{
    const row=template.content.firstElementChild.cloneNode(true);itemsHost.appendChild(row);configureStudioRow(row,productData);reindexStudioItems();calculateStudio();row.scrollIntoView({behavior:'smooth',block:'nearest'});row.querySelector(productData?'[data-item-qty]':'[data-item-description]')?.focus();studioDirty=true;
  };
  itemsHost.querySelectorAll('[data-studio-item]').forEach(row=>configureStudioRow(row));reindexStudioItems();
  documentStudio.querySelector('[data-add-custom-line]')?.addEventListener('click',()=>addStudioRow());
  const catalogSelect=documentStudio.querySelector('[data-catalog-select]'),addSelectedProduct=documentStudio.querySelector('[data-add-selected-product]');
  const addCatalogProduct=(productData)=>{
    const existing=Array.from(itemsHost.querySelectorAll('[data-studio-item]')).find(row=>row.querySelector('[data-item-product]')?.value===String(productData.id));
    if(existing){const quantity=existing.querySelector('[data-item-qty]');quantity.value=numeric(quantity.value)+1;existing.classList.add('studio-item-flash');setTimeout(()=>existing.classList.remove('studio-item-flash'),700);calculateStudio();studioDirty=true;return}
    const blank=Array.from(itemsHost.querySelectorAll('[data-studio-item]')).find(row=>!row.querySelector('[data-item-description]')?.value.trim()&&!row.querySelector('[data-item-product]')?.value);
    const data={id:productData.id,name:productData.name,price:productData.price,tax:productData.tax,quantity:1};
    if(blank){const select=blank.querySelector('[data-item-product]'),description=blank.querySelector('[data-item-description]'),price=blank.querySelector('[data-item-price]'),tax=blank.querySelector('[data-item-tax]'),qty=blank.querySelector('[data-item-qty]');select.value=String(data.id);description.value=data.name;price.value=data.price;tax.value=data.tax;qty.value='1';reindexStudioItems();calculateStudio();qty.focus()}else addStudioRow(data);
    studioDirty=true;
  };
  catalogSelect?.addEventListener('change',()=>{if(addSelectedProduct)addSelectedProduct.disabled=!catalogSelect.value});
  addSelectedProduct?.addEventListener('click',()=>{const option=catalogSelect?.selectedOptions[0];if(!option?.value)return;addCatalogProduct({id:option.value,name:option.dataset.name||option.textContent.trim(),price:option.dataset.price||'0',tax:option.dataset.tax||'0'});catalogSelect.value='';addSelectedProduct.disabled=true});
  documentStudio.querySelectorAll('[name="customer_mode"]').forEach(input=>input.addEventListener('change',syncStudioCustomer));
  documentStudio.querySelector('[data-customer-search]')?.addEventListener('input',event=>{const query=event.target.value.trim().toLowerCase(),select=documentStudio.querySelector('[data-studio-customer]');Array.from(select.options).forEach((option,index)=>{if(index===0)return;option.hidden=query!==''&&!option.textContent.toLowerCase().includes(query)});if(select.selectedOptions[0]?.hidden)select.value=''});
  documentStudio.querySelector('[data-studio-customer]')?.addEventListener('change',event=>{const option=event.target.selectedOptions[0],address=documentStudio.querySelector('[data-delivery-address]');if(address&&!address.value&&option?.value)address.value=[option.dataset.address,option.dataset.area].filter(Boolean).join(', ');updateSummaryCustomer()});
  documentStudio.querySelector('[data-scroll-items]')?.addEventListener('click',()=>documentStudio.querySelector('#studio-items')?.scrollIntoView({behavior:'smooth'}));
  documentStudio.querySelectorAll('[data-studio-jump]').forEach(button=>button.addEventListener('click',()=>{
    setActiveStudioStep(button.dataset.studioJump);documentStudio.querySelector(`#${button.dataset.studioJump}`)?.scrollIntoView({behavior:'smooth',block:'start'});
  }));
  documentStudio.querySelectorAll('[data-studio-next]').forEach(button=>button.addEventListener('click',()=>{
    setActiveStudioStep(button.dataset.studioNext);documentStudio.querySelector(`#${button.dataset.studioNext}`)?.scrollIntoView({behavior:'smooth',block:'start'});
  }));
  documentStudio.querySelector('[data-review-summary]')?.addEventListener('click',()=>documentStudio.querySelector('.studio-summary')?.scrollIntoView({behavior:'smooth',block:'start'}));
  documentStudio.querySelectorAll('[data-delivery-preset]').forEach(button=>button.addEventListener('click',()=>{
    const fee=documentStudio.querySelector('[data-delivery-fee]');
    if(!fee)return;
    fee.value=button.dataset.deliveryPreset;
    if(button.dataset.deliveryPreset==='')fee.focus();
    calculateStudio();studioDirty=true;
  }));
  documentStudio.addEventListener('input',event=>{studioDirty=true;if(event.target.matches('[name^="new_customer"]'))updateSummaryCustomer();calculateStudio()});
  documentStudio.addEventListener('change',()=>{studioDirty=true;syncStudioCustomer();calculateStudio()});
  documentStudio.addEventListener('submit',event=>{
    const submitter=event.submitter;
    if(studioSubmitting){event.preventDefault();return}
    const customerMode=documentStudio.querySelector('[name="customer_mode"]:checked')?.value,customerOk=customerMode==='new'?(documentStudio.querySelector('[name="new_customer_name"]')?.value.trim()||documentStudio.querySelector('[name="new_customer_company"]')?.value.trim()):documentStudio.querySelector('[data-studio-customer]')?.value;
    const validLines=Array.from(itemsHost.querySelectorAll('[data-studio-item]')).filter(row=>row.querySelector('[data-item-description]')?.value.trim()&&numeric(row.querySelector('[data-item-qty]')?.value)>0);
    const issuing=submitter?.value==='issue',deliverySelected=documentStudio.querySelector('[name="fulfilment_method"]:checked')?.value==='Delivery',address=documentStudio.querySelector('[data-delivery-address]'),fee=documentStudio.querySelector('[data-delivery-fee]'),deliveryReady=!deliverySelected||(address?.value.trim()&&numeric(fee?.value)>0);
    if(issuing&&deliverySelected&&!deliveryReady){event.preventDefault();const field=!address?.value.trim()?address:fee;field?.setCustomValidity(!address?.value.trim()?'Enter the delivery address before issuing.':'Enter the agreed delivery fee before issuing.');field?.reportValidity();field?.addEventListener('input',()=>field.setCustomValidity(''),{once:true});documentStudio.querySelector('#studio-fulfilment')?.scrollIntoView({behavior:'smooth',block:'start'});return}
    if(!customerOk||!validLines.length||!documentStudio.checkValidity()){event.preventDefault();documentStudio.reportValidity();const target=!customerOk?documentStudio.querySelector('#studio-customer'):!validLines.length?documentStudio.querySelector('#studio-items'):documentStudio.querySelector(':invalid')?.closest('.studio-section');target?.scrollIntoView({behavior:'smooth',block:'start'});return}
    studioSubmitting=true;studioDirty=false;if(submitter){submitter.disabled=true;submitter.dataset.original=submitter.textContent;submitter.textContent=submitter.value==='issue'?'Issuing…':'Saving…'}
  });
  window.addEventListener('beforeunload',event=>{if(studioDirty&&!studioSubmitting){event.preventDefault();event.returnValue=''}});
  document.addEventListener('keydown',event=>{if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==='s'){event.preventDefault();documentStudio.querySelector('.studio-draft')?.click()}});
  if('IntersectionObserver' in window){
    const sectionObserver=new IntersectionObserver(entries=>{const visible=entries.filter(entry=>entry.isIntersecting).sort((a,b)=>b.intersectionRatio-a.intersectionRatio)[0];if(visible)setActiveStudioStep(visible.target.id)},{rootMargin:'-22% 0px -58% 0px',threshold:[0.05,0.25,0.5]});
    documentStudio.querySelectorAll('.studio-section').forEach(section=>sectionObserver.observe(section));
  }
  syncStudioCustomer();calculateStudio();
}

/* Make the payment receipt available as soon as an invoice has a recorded payment. */
const documentActions=document.querySelector('.document-state-actions');
const paymentPanel=Array.from(document.querySelectorAll('.panel')).find(panel=>panel.querySelector('.panel-head h2')?.textContent.trim()==='Payments received');
if(documentActions&&paymentPanel?.querySelector('tbody tr')){
  const documentId=new URLSearchParams(window.location.search).get('id');
  if(documentId&&!documentActions.querySelector('.receipt-action')){
    const receipt=document.createElement('a');
    receipt.className='button primary receipt-action';receipt.target='_blank';receipt.rel='noopener';
    receipt.href=`print.php?id=${encodeURIComponent(documentId)}&mode=receipt`;
    receipt.textContent='Open payment receipt';
    documentActions.insertBefore(receipt,documentActions.children[1]||null);
  }
}

/* Copy invoice-specific hosted Paynow links without exposing credentials. */
document.querySelector('[data-copy-paynow]')?.addEventListener('click',async event=>{
  const button=event.currentTarget,url=document.querySelector('[data-paynow-url]')?.value;
  if(!url)return;
  try{
    await navigator.clipboard.writeText(url);
    const original=button.textContent;button.textContent='Copied';
    setTimeout(()=>button.textContent=original,1800);
  }catch(error){
    const input=document.querySelector('[data-paynow-url]');input?.select();
    button.textContent='Select and copy the link';
  }
});
