document.addEventListener('DOMContentLoaded', () => {
 const base=window.APP_BASE||'', money=v=>`£${Number(v||0).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2})}`;
 const workspace=document.getElementById('investmentWorkspace'), form=document.getElementById('investmentForm'), amount=document.getElementById('investmentAmount'), feedback=document.getElementById('investmentFeedback'); let selected=null,balance=0;
 const notify=(message,ok=false)=>feedback.innerHTML=`<div class="notice ${ok?'notice-success':'notice-error'}">${message}</div>`;
 const renderQuote=()=>{if(!selected)return;const value=Number(amount.value)||0,totalReturn=value*selected.rate/100*selected.months,projected=value+totalReturn,date=new Date();date.setMonth(date.getMonth()+selected.months);document.getElementById('summaryTerm').textContent=`${selected.months} months`;document.getElementById('summaryRate').textContent=`${selected.rate}% monthly`;document.getElementById('summaryDate').textContent=date.toLocaleDateString(undefined,{year:'numeric',month:'short',day:'numeric'});document.getElementById('summaryAmount').textContent=value?`${money(projected)} total · ${money(totalReturn)} returns`:'Enter an amount';document.getElementById('amountHelp').textContent=`Minimum ${money(selected.min)} · Available ${money(balance)}`};
 document.querySelectorAll('.plan-select').forEach(button=>button.addEventListener('click',()=>{selected={key:button.dataset.plan,name:button.dataset.name,min:Number(button.dataset.min),months:Number(button.dataset.months),rate:Number(button.dataset.rate)};document.querySelectorAll('[data-plan-card]').forEach(card=>card.classList.remove('is-selected'));button.closest('[data-plan-card]').classList.add('is-selected');workspace.hidden=false;document.getElementById('selectedPlan').value=selected.key;document.getElementById('selectedPlanName').value=selected.name;amount.min=selected.min;amount.value='';document.getElementById('termsAcknowledgement').checked=false;renderQuote();workspace.scrollIntoView({behavior:'smooth',block:'center'})}));
 document.getElementById('closeInvestment').addEventListener('click',()=>workspace.hidden=true);amount.addEventListener('input',renderQuote);
 const paymentHistory=i=>{const payments=i.return_payments||[],total=Math.max(0,Number(i.expected_return)-Number(i.amount)),paid=payments.filter(p=>p.status==='paid'),paidAmount=paid.reduce((sum,p)=>sum+Number(p.amount),0);if(!payments.length)return `<small>Total scheduled returns: ${money(total)}. No periodic payments recorded for this legacy allocation.</small>`;const entries=payments.map(p=>{const dueDate=new Date(p.due_date.replace(' ','T')).toLocaleDateString(undefined,{year:'numeric',month:'short',day:'numeric'});let statusText=`due ${dueDate}`;if(p.status==='paid'){const paidDate=new Date(p.paid_at.replace(' ','T')).toLocaleDateString(undefined,{year:'numeric',month:'short',day:'numeric'});statusText=`paid ${paidDate}`;}const statusClass=p.status==='paid'?'paid':'due';return `<li><b>Payment ${p.period_number}:</b> ${p.rate_percent}% of ${money(i.amount)} = ${money(p.amount)} <span class="${statusClass}">${statusText}</span></li>`}).join('');return `<details class="return-history"><summary>${money(paidAmount)} of ${money(total)} scheduled returns paid</summary><ul>${entries}</ul></details>`};
 async function loadInvestments(){try{const r=await fetch(`${base}/get_investments.php`),d=await r.json(),list=document.getElementById('investmentList');if(!d.success||!d.investments.length){list.innerHTML='<div class="empty-state">No investment records yet.</div>';return}list.innerHTML=d.investments.map(i=>{const start=new Date(i.start_date.replace(' ','T')),end=new Date(i.end_date.replace(' ','T')),now=new Date(),progress=i.status==='completed'?100:Math.max(0,Math.min(100,((now-start)/(end-start))*100));const principal=i.status==='completed'&&i.credited_amount?`Principal repaid: ${money(i.credited_amount)}`:`Principal maturity: ${money(i.amount)}`;return `<article class="investment-row"><div><b>${i.package_name}</b><small>${money(i.amount)} principal · matures ${end.toLocaleDateString()}</small>${paymentHistory(i)}</div><div><span class="badge ${i.status==='active'?'':'pending'}">${i.status}</span><small>${principal}</small></div><div class="investment-progress"><span style="width:${progress}%"></span></div></article>`}).join('')}catch{document.getElementById('investmentList').innerHTML='<div class="empty-state">Unable to load investment records.</div>'}}
 fetch(`${base}/get_balance.php`).then(r=>r.json()).then(d=>{if(d.success){balance=Number(d.balance);document.getElementById('availableToInvest').textContent=money(balance);renderQuote()}}).catch(()=>{});loadInvestments();
 form.addEventListener('submit',async e=>{e.preventDefault();if(!selected)return;const value=Number(amount.value);if(value<selected.min){notify(`Enter at least ${money(selected.min)} for ${selected.name}.`);amount.focus();return}if(value>balance){notify('The amount exceeds your available balance.');amount.focus();return}if(!document.getElementById('termsAcknowledgement').checked){notify('Please acknowledge the plan conditions before continuing.');return}const button=document.getElementById('submitInvestment');button.disabled=true;button.textContent='Creating investment…';try{const r=await fetch(`${base}/invest.php`,{method:'POST',body:new FormData(form)}),d=await r.json();if(!d.success){notify(d.message||'We could not create the investment.');return}notify(`Investment created. Your first return payment is scheduled according to the plan terms. Maturity date: ${new Date(d.investment.maturity_date.replace(' ','T')).toLocaleDateString()}.`,true);balance-=value;document.getElementById('availableToInvest').textContent=money(balance);workspace.hidden=true;await loadInvestments()}catch{notify('Unable to submit the investment. Please try again.')}finally{button.disabled=false;button.textContent='Confirm investment'}});
});
