// views/reconcile.jsx — tie the ledger to what the bank actually says
function ReconcileView() {
  const s = useStore();
  const books = useBooks();
  const banks = s.bankAccounts || [];
  const [bankId, setBankId] = React.useState(() => (banks[0] || {}).id || '');
  const [asOn, setAsOn] = React.useState(cashToday());
  const [onlyOpen, setOnlyOpen] = React.useState(true);

  const bank = banks.find(b => b.id === bankId) || banks[0] || {};
  const meta = (books.recon || {})[bank.id] || {};
  const rec = React.useMemo(
    () => bank.id ? bankRecon(s, books, bank.id, asOn) : null,
    [s.transactions, s.bankAccounts, books.tx, books.recon, bank.id, asOn]
  );

  const [stmtInput, setStmtInput] = React.useState('');
  React.useEffect(() => { setStmtInput(meta.balance == null ? '' : String(meta.balance)); }, [bank.id, meta.balance]);

  function commitStmt() {
    const v = stmtInput.trim();
    BooksStore.setRecon(bank.id, { balance: v === '' ? null : Number(v.replace(/,/g, '')), asOn });
  }

  if (!banks.length || !rec) {
    return (
      <div>
        <div className="page-head"><div><h1 className="page-title">Reconcile<em>.</em></h1></div></div>
        <div className="card">Add a bank account in Masters first.</div>
      </div>
    );
  }

  const rows = onlyOpen ? rec.open : rec.txs;
  const overview = reconAll(s, books, asOn);

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Reconcile<em>.</em></h1>
          <p className="page-sub">
            Tick every line that appears on the bank's own statement. What's left is what the bank hasn't shown yet —
            and anything that difference doesn't explain is a real error worth finding.
          </p>
        </div>
      </div>

      <div className="rec-strip">
        {overview.map(({ bank: b, rec: r }) => (
          <button key={b.id} className={'rec-tile ' + (b.id === bank.id ? 'on' : '')} onClick={() => setBankId(b.id)}>
            <div className="rec-tile-name">
              <span className="bank-swatch" style={{ background: b.color, width: 10, height: 10, borderRadius: 3 }}></span>
              {b.short || b.name}
            </div>
            <div className="rec-tile-val num">{fmtINR(r.ledger)}</div>
            <div className="rec-tile-note">
              {r.stmt == null
                ? <span className="muted">no statement figure</span>
                : r.explained
                  ? <span className="t-credit">reconciled</span>
                  : <span className="t-debit">{fmtINR(Math.abs(r.unexplained))} off</span>}
            </div>
          </button>
        ))}
      </div>

      <div className="toolbar" style={{ marginTop: 16 }}>
        <label className="field-label" style={{ margin: 0 }}>As on</label>
        <input className="input" type="date" style={{ width: 150 }} value={asOn} onChange={e => setAsOn(e.target.value)} />
        <div className="sep"></div>
        <label className="field-label" style={{ margin: 0 }}>Closing balance per bank</label>
        <input className="input mono" style={{ width: 160 }} inputMode="decimal" placeholder="e.g. 482310.50"
          value={stmtInput} onChange={e => setStmtInput(e.target.value)} onBlur={commitStmt}
          onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur(); }} />
        <div style={{ flex: 1 }}></div>
        <span className="muted" style={{ fontSize: 12 }}>{rec.ticked} of {rec.count} ticked</span>
      </div>

      <div className="rec-sum card">
        <div className="rec-line"><span>Balance per books, {fmtDate(rec.asOn)}</span><b className="num">{fmtINR(rec.ledger)}</b></div>
        <div className="rec-line"><span>Balance per bank statement</span><b className="num">{rec.stmt == null ? '—' : fmtINR(rec.stmt)}</b></div>
        <div className="rec-line total">
          <span>Difference</span>
          <b className={'num ' + (rec.stmt == null ? '' : Math.abs(rec.diffAll) < 1 ? 't-credit' : 't-debit')}>
            {rec.stmt == null ? '—' : fmtINR(rec.diffAll)}
          </b>
        </div>

        {rec.stmt != null && rec.open.length > 0 && Math.abs(rec.diffAll) >= 1 && (
          <>
            <div className="rule-label" style={{ margin: '16px 0 6px' }}>Could the unticked lines explain it?</div>
            <div className="rec-line sub">
              <span>{rec.open.length} line{rec.open.length === 1 ? '' : 's'} not ticked as seen on a statement</span>
              <b className="num">{fmtINR(rec.netOpen)}</b>
            </div>
            <div className="rec-line sub">
              <span>Difference after allowing for them</span>
              <b className={'num ' + (Math.abs(rec.diffOpen) < 1 ? 't-credit' : 't-debit')}>{fmtINR(rec.diffOpen)}</b>
            </div>
          </>
        )}

        {rec.stmt == null ? (
          <div className="rec-verdict muted">Enter the closing balance from your bank statement above to complete the reconciliation.</div>
        ) : rec.explained ? (
          <div className="rec-verdict ok">
            ✓ Reconciled.{' '}
            {rec.basis === 'cleared'
              ? 'The books agree with the bank exactly.'
              : 'The gap is fully accounted for by the ' + rec.open.length + ' line' + (rec.open.length === 1 ? '' : 's') + " the bank hasn't shown yet."}
          </div>
        ) : (
          <div className="rec-verdict bad">
            <b>{fmtINR(Math.abs(rec.unexplained))} unexplained.</b> The books are {rec.unexplained > 0 ? 'higher' : 'lower'} than the bank —
            usually a statement row that was never imported, a duplicate import, or an amount typed wrong.
            {rec.stmtDate && rec.stmtDate !== rec.asOn && <> Check that your statement figure is as on <b>{fmtDate(rec.asOn)}</b> too.</>}
          </div>
        )}
      </div>

      <div className="toolbar" style={{ marginTop: 16 }}>
        <button className={'btn btn-sm ' + (onlyOpen ? 'btn-primary' : 'btn-ghost')} onClick={() => setOnlyOpen(true)}>Unticked ({rec.open.length})</button>
        <button className={'btn btn-sm ' + (!onlyOpen ? 'btn-primary' : 'btn-ghost')} onClick={() => setOnlyOpen(false)}>All ({rec.count})</button>
        <div style={{ flex: 1 }}></div>
        <button className="btn btn-sm btn-ghost" onClick={() => {
          if (!rows.length) return;
          if (confirm('Tick all ' + rows.length + ' line' + (rows.length === 1 ? '' : 's') + ' shown as seen on the bank statement?')) {
            BooksStore.setTxMany(rows.map(t => t.id), { reconciled: true });
          }
        }}>Tick all shown</button>
        <button className="btn btn-sm btn-ghost" onClick={() => {
          if (!rec.txs.length) return;
          if (confirm('Untick every line on this account?')) BooksStore.setTxMany(rec.txs.map(t => t.id), { reconciled: false });
        }}>Reset account</button>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <table className="tbl">
          <thead><tr>
            <th style={{ width: 44 }}></th>
            <th style={{ width: 90 }}>Date</th>
            <th>Particulars</th>
            <th style={{ width: 110 }}>Type</th>
            <th style={{ width: 130, textAlign: 'right' }}>Amount</th>
            <th style={{ width: 130, textAlign: 'right' }}>Balance</th>
          </tr></thead>
          <tbody>
            {rows.map(t => (
              <tr key={t.id} className={t.reconciled ? 'rec-done' : ''}>
                <td>
                  <input type="checkbox" checked={t.reconciled}
                    onChange={() => BooksStore.setTx(t.id, { reconciled: !t.reconciled })}
                    title={t.reconciled ? 'Seen on the statement' : 'Not yet seen on the statement'} />
                </td>
                <td className="num" style={{ fontSize: 12 }}>{fmtDate(t.date)}</td>
                <td>
                  <div style={{ fontSize: 12.5, whiteSpace: 'normal', wordBreak: 'break-word', lineHeight: 1.35 }}>{t.particulars}</div>
                </td>
                <td>
                  {t.type === 'transfer' ? <span className="tag tag-transfer">transfer</span>
                    : t.type === 'income' ? <span className="tag tag-income">income</span>
                    : t.type === 'expense' ? <span className="tag tag-expense">expense</span>
                    : <span className="tag tag-empty">unclassified</span>}
                </td>
                <td className={'num ' + (t.direction === 'credit' ? 't-credit' : 't-debit')} style={{ textAlign: 'right', fontWeight: 600 }}>
                  {t.direction === 'credit' ? '' : '− '}{fmtINR(t.amount)}
                </td>
                <td className="num" style={{ textAlign: 'right', fontSize: 12, color: 'var(--ink-2)' }}>{fmtINR(t.balance)}</td>
              </tr>
            ))}
            {!rows.length && (
              <tr><td colSpan={6} style={{ textAlign: 'center', padding: 40, color: 'var(--ink-3)' }}>
                {rec.count ? 'Every line on this account is ticked.' : 'No transactions on this account up to ' + fmtDate(asOn) + '.'}
              </td></tr>
            )}
          </tbody>
        </table>
      </div>

      <div className="muted" style={{ fontSize: 11, padding: '10px 2px', maxWidth: 720, lineHeight: 1.6 }}>
        Ticking a line records it as seen on a bank statement. It changes no amount, date or classification — the ledger and
        your P&amp;L are untouched. The tick marks sync with the rest of your books, so your partner sees the same state.
      </div>
    </div>
  );
}

Object.assign(window, { ReconcileView });
