/* Payments module */
(function () {
  const { useState } = React;
  const Icon = window.Icon, PageHead = window.PageHead, LineChart = window.LineChart, BarChart = window.BarChart;
  const D = window.YEIDA, fmt = D.fmtINR;

  function Payments({ go, toast }) {
    const [tab, setTab] = useState('dues');
    const [pay, setPay] = useState(null); // due being paid
    const totalDue = D.dues.reduce((s, d) => s + d.amount, 0);

    return (
      <div>
        <PageHead title="Payments" subtitle="Authority challans & dues plus construction milestone payments">
          <button className="btn btn-outline" onClick={() => setTab('history')}><Icon name="history" size={18} />History</button>
          <button className="btn btn-primary" onClick={() => setPay({ label: 'All Outstanding Dues', amount: totalDue })}><Icon name="rupee" size={18} />Pay All Dues</button>
        </PageHead>

        {/* summary cards */}
        <div className="stagger" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 18 }}>
          {[
            ['Outstanding', fmt(totalDue), 'amber', 'rupee', '3 dues pending'],
            ['Paid (FY 25-26)', fmt(265370), 'emerald', 'checkCircle', '5 transactions'],
            ['Next Due', '30 Jun', 'blue', 'calendar', 'Lease Rent 2026-27'],
            ['Total Premium', fmt(D.property.totalValue), 'navy', 'building', '90% paid'],
          ].map(([l, v, c, ic, sub]) => {
            const cc = { blue: ['var(--blue-50)', 'var(--blue-600)'], emerald: ['var(--emerald-50)', 'var(--emerald-700)'], amber: ['var(--amber-50)', 'var(--amber-600)'], navy: ['#e9eefb', 'var(--navy-700)'] }[c];
            return (
              <div key={l} className="card card-pad">
                <div className="row spread"><span style={{ width: 40, height: 40, borderRadius: 11, display: 'grid', placeItems: 'center', background: cc[0], color: cc[1] }}><Icon name={ic} size={20} /></span></div>
                <div className="num" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 24, marginTop: 14 }}>{v}</div>
                <div style={{ fontSize: 13.5, color: 'var(--muted)', fontWeight: 600 }}>{l}</div>
                <div className="faint" style={{ fontSize: 12, marginTop: 3 }}>{sub}</div>
              </div>
            );
          })}
        </div>

        {/* tabs */}
        <div className="row gap-2" style={{ marginBottom: 18, borderBottom: '1px solid var(--line)', flexWrap: 'wrap' }}>
          {[['dues', 'Outstanding Dues'], ['history', 'Payment History'], ['receipts', 'Receipts'], ['construction', 'Construction Payments'], ['analytics', 'Financial Analytics']].map(([k, l]) => (
            <button key={k} onClick={() => setTab(k)} style={{ padding: '11px 4px', marginRight: 18, background: 'none', border: 'none', borderBottom: '2.5px solid ' + (tab === k ? 'var(--blue-600)' : 'transparent'), color: tab === k ? 'var(--ink)' : 'var(--muted)', fontWeight: tab === k ? 700 : 500, fontSize: 14.5, cursor: 'pointer', marginBottom: -1 }}>{l}</button>
          ))}
        </div>

        {tab === 'dues' && <Dues onPay={setPay} onChallan={() => toast && toast('e-Challan generated · CH-2026-0606-18')} />}
        {tab === 'history' && <History />}
        {tab === 'receipts' && <Receipts toast={toast} />}
        {tab === 'construction' && <ConstructionPayments toast={toast} />}
        {tab === 'analytics' && <Analytics />}

        {pay && <PayModal due={pay} onClose={() => setPay(null)} onDone={() => { setPay(null); toast && toast('Payment successful · receipt sent to email'); }} />}
      </div>
    );
  }

  function Dues({ onPay, onChallan }) {
    return (
      <div className="card anim-fade-up" style={{ overflow: 'hidden' }}>
        <table className="tbl">
          <thead><tr><th>Description</th><th>Type</th><th>Due Date</th><th>Status</th><th style={{ textAlign: 'right' }}>Amount</th><th></th></tr></thead>
          <tbody>
            {D.dues.map(d => (
              <tr key={d.id}>
                <td><div style={{ fontWeight: 600, color: 'var(--ink)' }}>{d.label}</div><div className="faint" style={{ fontSize: 12 }}>{d.id}</div></td>
                <td>{d.type}</td>
                <td className="num">{d.due}</td>
                <td><span className={'badge badge-' + (d.status === 'overdue' ? 'red' : d.status === 'due' ? 'amber' : 'gray')}>{d.status === 'overdue' ? 'Overdue' : d.status === 'due' ? 'Due soon' : 'Upcoming'}</span></td>
                <td className="num" style={{ textAlign: 'right', fontWeight: 700, color: 'var(--ink)' }}>{fmt(d.amount)}</td>
                <td style={{ textAlign: 'right' }}>
                  <div className="row gap-2" style={{ justifyContent: 'flex-end' }}>
                    <button className="btn btn-outline btn-sm" onClick={onChallan}><Icon name="receipt" size={15} />Challan</button>
                    <button className="btn btn-primary btn-sm" onClick={() => onPay(d)}>Pay</button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  function History() {
    return (
      <div className="card anim-fade-up" style={{ overflow: 'hidden' }}>
        <table className="tbl">
          <thead><tr><th>Transaction</th><th>Date</th><th>Mode</th><th>Challan</th><th>Status</th><th style={{ textAlign: 'right' }}>Amount</th><th></th></tr></thead>
          <tbody>
            {D.payments.map(p => (
              <tr key={p.id}>
                <td><div style={{ fontWeight: 600, color: 'var(--ink)' }}>{p.label}</div><div className="faint num" style={{ fontSize: 12 }}>{p.id}</div></td>
                <td className="num">{p.date}</td>
                <td>{p.mode}</td>
                <td className="num faint" style={{ fontSize: 13 }}>{p.challan}</td>
                <td><span className="badge badge-green"><Icon name="check" size={13} />{p.status}</span></td>
                <td className="num" style={{ textAlign: 'right', fontWeight: 700, color: 'var(--ink)' }}>{fmt(p.amount)}</td>
                <td style={{ textAlign: 'right' }}><button className="icon-btn" title="Download receipt"><Icon name="download" size={18} /></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  function Receipts({ toast }) {
    return (
      <div className="anim-fade-up" style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16 }}>
        {D.payments.map(p => (
          <div key={p.id} className="card card-pad card-hover">
            <div className="row spread" style={{ marginBottom: 12 }}>
              <span style={{ width: 42, height: 42, borderRadius: 11, display: 'grid', placeItems: 'center', background: 'var(--emerald-50)', color: 'var(--emerald-700)' }}><Icon name="receipt" size={21} /></span>
              <span className="badge badge-green"><Icon name="check" size={12} />Paid</span>
            </div>
            <div style={{ fontWeight: 700, fontSize: 14.5 }}>{p.label}</div>
            <div className="faint num" style={{ fontSize: 12, marginTop: 3 }}>{p.challan} · {p.date}</div>
            <div className="num" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 21, margin: '12px 0' }}>{fmt(p.amount)}</div>
            <div className="row gap-2">
              <button className="btn btn-outline btn-sm" style={{ flex: 1 }} onClick={() => toast && toast('Receipt downloaded')}><Icon name="download" size={15} />Download</button>
              <button className="btn btn-ghost btn-sm" style={{ border: '1px solid var(--line)' }}><Icon name="eye" size={15} /></button>
            </div>
          </div>
        ))}
      </div>
    );
  }

  function ConstructionPayments({ toast }) {
    const CP = D.constructionPayments;
    const C = D.construction;
    const paid = CP.filter(p => p.status === 'Paid').reduce((s, p) => s + p.amount, 0);
    const upcoming = CP.filter(p => p.status !== 'Paid').reduce((s, p) => s + p.amount, 0);
    return (
      <div className="anim-fade-up">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16, marginBottom: 18 }}>
          {[['Estimated Build Cost', fmt(C.estimatedCost), 'navy', 'building'], ['Paid to Contractor', fmt(paid), 'emerald', 'checkCircle'], ['Upcoming Milestones', fmt(upcoming), 'amber', 'clock']].map(([l, v, c, ic]) => {
            const cc = { emerald: ['var(--emerald-50)', 'var(--emerald-700)'], amber: ['var(--amber-50)', 'var(--amber-600)'], navy: ['#e9eefb', 'var(--navy-700)'] }[c];
            return (
              <div key={l} className="card card-pad">
                <span style={{ width: 40, height: 40, borderRadius: 11, display: 'grid', placeItems: 'center', background: cc[0], color: cc[1] }}><Icon name={ic} size={20} /></span>
                <div className="num" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 23, marginTop: 12 }}>{v}</div>
                <div style={{ fontSize: 13.5, color: 'var(--muted)', fontWeight: 600 }}>{l}</div>
              </div>
            );
          })}
        </div>
        <div className="card" style={{ overflow: 'hidden' }}>
          <div className="row spread" style={{ padding: '16px 20px 4px' }}>
            <h3 style={{ fontSize: 17 }}>Milestone Payments &amp; Invoices</h3>
            <span className="muted" style={{ fontSize: 12.5 }}>Contractor · {C.contractor.name}</span>
          </div>
          <table className="tbl">
            <thead><tr><th>Milestone</th><th>Invoice</th><th>Vendor</th><th>Date</th><th>Status</th><th style={{ textAlign: 'right' }}>Amount</th><th></th></tr></thead>
            <tbody>
              {CP.map(p => (
                <tr key={p.id}>
                  <td style={{ fontWeight: 600, color: 'var(--ink)' }}>{p.milestone}</td>
                  <td className="num faint">{p.id}</td>
                  <td>{p.vendor}</td>
                  <td className="num">{p.date}</td>
                  <td><span className={'badge badge-' + (p.status === 'Paid' ? 'green' : 'amber')}>{p.status === 'Paid' ? <Icon name="check" size={12} /> : null}{p.status}</span></td>
                  <td className="num" style={{ textAlign: 'right', fontWeight: 700, color: 'var(--ink)' }}>{fmt(p.amount)}</td>
                  <td style={{ textAlign: 'right' }}>{p.status === 'Paid' ? <button className="icon-btn" title="Receipt" onClick={() => toast && toast('Receipt downloaded')}><Icon name="download" size={18} /></button> : <button className="btn btn-primary btn-sm" onClick={() => toast && toast('Milestone payment scheduled')}>Pay</button>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  function Analytics() {
    return (
      <div className="anim-fade-up">
        <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18, marginBottom: 18 }}>
          <div className="card card-pad">
            <h3 style={{ fontSize: 17 }}>Cumulative payments</h3>
            <p className="muted" style={{ fontSize: 13, marginBottom: 14 }}>Premium + lease rent paid since allotment</p>
            <LineChart data={[1.2, 1.8, 2.4, 3.1, 3.9, 4.6, 5.4, 6.0, 6.5, 6.95]} h={180} color="var(--emerald-600)" fill="rgba(15,157,107,.12)" />
            <div className="row spread" style={{ marginTop: 8, fontSize: 12, color: 'var(--faint)', fontWeight: 600 }}><span>2019</span><span>2021</span><span>2023</span><span>2025</span><span>2026</span></div>
          </div>
          <div className="card card-pad">
            <h3 style={{ fontSize: 17 }}>By category</h3>
            <p className="muted" style={{ fontSize: 13, marginBottom: 18 }}>Lifetime breakdown</p>
            {[['Location Premium', 82, 'var(--blue-500)'], ['Lease Rent', 11, 'var(--emerald-500)'], ['Fees & Charges', 5, 'var(--amber-500)'], ['Utilities', 2, 'var(--navy-700)']].map(([l, p, c]) => (
              <div key={l} style={{ marginBottom: 14 }}>
                <div className="row spread" style={{ fontSize: 13, marginBottom: 6 }}><span style={{ fontWeight: 600 }}>{l}</span><span className="num faint">{p}%</span></div>
                <div className="progress"><span style={{ width: p + '%', background: c }} /></div>
              </div>
            ))}
          </div>
        </div>
        <div className="card card-pad">
          <h3 style={{ fontSize: 17, marginBottom: 4 }}>Yearly payments</h3>
          <p className="muted" style={{ fontSize: 13, marginBottom: 18 }}>Total paid per financial year (₹ lakh)</p>
          <BarChart data={[1.2, 1.4, 1.1, 1.6, 1.9, 2.2, 2.0, 2.6]} w={760} h={120} color="var(--blue-500)" gap={14} />
          <div className="row spread" style={{ marginTop: 8, fontSize: 12, color: 'var(--faint)', fontWeight: 600 }}>{['19', '20', '21', '22', '23', '24', '25', '26'].map(y => <span key={y}>FY{y}</span>)}</div>
        </div>
      </div>
    );
  }

  function PayModal({ due, onClose, onDone }) {
    const [method, setMethod] = useState('upi');
    const [stage, setStage] = useState('select');
    const methods = [['upi', 'UPI', 'phone'], ['card', 'Debit/Credit Card', 'payments'], ['net', 'Net Banking', 'building']];
    const pay = () => { setStage('processing'); setTimeout(() => setStage('done'), 1600); };
    return (
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(8,26,57,.5)', backdropFilter: 'blur(3px)', display: 'grid', placeItems: 'center', zIndex: 1000, padding: 20 }}>
        <div onClick={e => e.stopPropagation()} className="anim-pop card" style={{ width: 440, maxWidth: '100%', padding: 0, overflow: 'hidden' }}>
          {stage !== 'done' ? (
            <>
              <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line)' }} className="row spread">
                <h3 style={{ fontSize: 18 }}>Complete Payment</h3>
                <button className="icon-btn" onClick={onClose}><Icon name="x" /></button>
              </div>
              <div style={{ padding: 24 }}>
                <div style={{ background: 'var(--bg)', borderRadius: 13, padding: '16px 18px', marginBottom: 20 }}>
                  <div className="muted" style={{ fontSize: 13 }}>{due.label}</div>
                  <div className="num" style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 30, marginTop: 4 }}>{fmt(due.amount)}</div>
                </div>
                <div style={{ fontWeight: 700, fontSize: 13.5, marginBottom: 10 }}>Payment Method</div>
                <div className="col gap-2" style={{ marginBottom: 22 }}>
                  {methods.map(([k, l, ic]) => (
                    <button key={k} onClick={() => setMethod(k)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '13px 15px', borderRadius: 12, border: '1.5px solid ' + (method === k ? 'var(--blue-400)' : 'var(--line)'), background: method === k ? 'var(--blue-50)' : '#fff', cursor: 'pointer' }}>
                      <span style={{ width: 38, height: 38, borderRadius: 10, display: 'grid', placeItems: 'center', background: method === k ? 'var(--blue-500)' : 'var(--bg-2)', color: method === k ? '#fff' : 'var(--muted)' }}><Icon name={ic} size={18} /></span>
                      <span style={{ fontWeight: 600, fontSize: 14.5, flex: 1, textAlign: 'left' }}>{l}</span>
                      <span style={{ width: 19, height: 19, borderRadius: 99, border: '2px solid ' + (method === k ? 'var(--blue-500)' : '#cdd7e4'), display: 'grid', placeItems: 'center' }}>{method === k && <span style={{ width: 9, height: 9, borderRadius: 99, background: 'var(--blue-500)' }} />}</span>
                    </button>
                  ))}
                </div>
                <button className="btn btn-primary btn-block btn-lg" onClick={pay} disabled={stage === 'processing'}>
                  {stage === 'processing' ? <><span style={{ width: 17, height: 17, border: '2px solid rgba(255,255,255,.4)', borderTopColor: '#fff', borderRadius: 99, animation: 'spin .7s linear infinite' }} />Processing…</> : <><Icon name="lock" size={17} />Pay {fmt(due.amount)}</>}
                </button>
                <div className="faint row gap-2 center" style={{ fontSize: 11.5, marginTop: 12 }}><Icon name="shield" size={14} />Secured by YEIDA Payment Gateway</div>
              </div>
            </>
          ) : (
            <div style={{ padding: '44px 30px', textAlign: 'center' }}>
              <div style={{ width: 72, height: 72, borderRadius: 99, margin: '0 auto 16px', display: 'grid', placeItems: 'center', background: 'var(--emerald-500)', color: '#fff', boxShadow: '0 14px 30px -10px rgba(15,157,107,.6)' }} className="anim-pop"><Icon name="check" size={38} /></div>
              <h3 style={{ fontSize: 22 }}>Payment Successful</h3>
              <p className="muted" style={{ fontSize: 14, marginTop: 8 }}>{fmt(due.amount)} paid · Receipt CH-2026-0606-18</p>
              <div className="row gap-3 center" style={{ marginTop: 22 }}>
                <button className="btn btn-outline"><Icon name="download" size={17} />Receipt</button>
                <button className="btn btn-primary" onClick={onDone}>Done</button>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  }

  window.Payments = Payments;
})();
