/* ============================================================================
 * DrNick · mock conversation engine
 * Pure data: maps a user utterance -> an ordered list of "steps" the widget
 * plays back (tool calls, streamed markdown, confirm cards). No real network.
 * Exposes window.DrNickEngine
 * ==========================================================================*/
(function () {
  // confirm_token mimic: short-lived, bound, one-time (UI illustration only)
  function token() {
    return 'cf_' + Math.random().toString(36).slice(2, 10);
  }

  const balanceAnswer =
`Here's where your wallet stands right now:

- **USDO** — \`1,250.00 USDO\` · Pegged · 1.00 USD
- **USDT** — \`842.50 USDT\`
- **OHO** — \`16,400.00 OHO\`

Your USDO is fully reserved — **1:1** backing, attested live. Want me to convert some USDT to USDO, or break down recent activity?`;

  const reservesAnswer =
`USDO reserves are **live and attested**:

| Metric | Value |
| --- | --- |
| Reserve ratio | 1.00 : 1.00 |
| Total reserves | \`$17,613,805.34\` |
| USDO in circulation | \`17,613,805 USDO\` |

Attestation refreshes every 60s. Reserves are held in cash & short-dated treasuries. You can [view the full attestation](https://onfa.example/attestation).`;

  const docAnswer =
`I read your statement. Quick summary:

- Net inflow this month: \`+2,310.00 USDO\`
- Largest outflow: \`-500.00 USDO\` (swap → USDT)
- 14 confirmed transactions, **0 pending**

Nothing looks unusual. Want me to chart the monthly flow or export a clean CSV?`;

  const fallbackAnswer =
`I can help with that. As your ONFA advisor I can:

1. Check balances & transaction history
2. Convert between USDO and other tokens
3. Pull live reserves & attestation
4. Read documents you upload (PDF, docx, xlsx, images)

What would you like to do?`;

  // ---- intent matching ------------------------------------------------------
  function classify(text, hasFile) {
    const t = (text || '').toLowerCase();
    if (hasFile) return 'doc';
    if (/(balance|how much|wallet|holdings|portfolio)/.test(t)) return 'balance';
    if (/(convert|swap|exchange)/.test(t)) return 'swap';
    if (/(reserve|attest|backing|peg|backed)/.test(t)) return 'reserves';
    if (/(statement|analyz|document|pdf|file|read)/.test(t)) return 'doc';
    return 'fallback';
  }

  function parseSwap(text) {
    // pull "500" and tokens; default to 500 USDT -> USDO
    const m = (text || '').match(/([\d,]+(?:\.\d+)?)/);
    const amt = m ? parseFloat(m[1].replace(/,/g, '')) : 500;
    const from = /usdo\s*(to|->|→)/.test((text || '').toLowerCase()) ? 'USDO' : 'USDT';
    const to = from === 'USDT' ? 'USDO' : 'USDT';
    return { amt, from, to };
  }

  function fmt(n) {
    return n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  function respond(text, hasFile) {
    const kind = classify(text, hasFile);

    if (kind === 'balance') {
      return [
        { type: 'tool', name: 'onfa_api.get_balance', label: 'Looking up your balance', ms: 1100 },
        { type: 'stream', markdown: balanceAnswer },
      ];
    }
    if (kind === 'reserves') {
      return [
        { type: 'tool', name: 'onfa_api.get_reserves', label: 'Fetching live reserves', ms: 1100 },
        { type: 'stream', markdown: reservesAnswer },
      ];
    }
    if (kind === 'doc') {
      return [
        { type: 'tool', name: 'doc_read', label: 'Reading your document', ms: 1300 },
        { type: 'tool', name: 'rag_search', label: 'Indexing for context', ms: 900 },
        { type: 'stream', markdown: docAnswer },
      ];
    }
    if (kind === 'swap') {
      const s = parseSwap(text);
      // illustrative quote: 1 USDT ≈ 0.9994 USDO
      const rate = 0.9994;
      const out = s.from === 'USDT' ? s.amt * rate : s.amt / rate;
      const fee = s.amt * 0.0005;
      return [
        { type: 'tool', name: 'onfa_api.quote_swap', label: 'Quoting your swap', ms: 1000 },
        {
          type: 'confirm',
          action: 'swap',
          title: 'Confirm swap',
          summary: `Convert ${fmt(s.amt)} ${s.from} to ${s.to}`,
          confirm_token: token(),
          ttl: '4:58',
          lines: [
            { k: 'You send', v: `${fmt(s.amt)} ${s.from}` },
            { k: 'You receive', v: `${fmt(out)} ${s.to}`, gold: true },
            { k: 'Rate', v: `1 ${s.from} = ${rate.toFixed(4)} ${s.to}` },
            { k: 'Network fee', v: `${fmt(fee)} ${s.from}` },
          ],
          meta: { ...s, out },
        },
      ];
    }
    return [{ type: 'stream', markdown: fallbackAnswer }];
  }

  function confirmResult(card) {
    const s = card.meta;
    if (s.kind === 'delegate') {
      const md =
`**Delegation confirmed.** \`${fmt(s.amt)} USDO\` → ZenInvest · Flexible

- Status: **Confirmed**
- Est. yield: \`6.20%\` / yr, accruing daily
- Tx hash: \`0x4be1…9af2\`

You can redeem anytime. Want me to set a monthly top-up?`;
      return [
        { type: 'tool', name: 'onfa_api.execute_delegate', label: 'Executing delegation', ms: 1300 },
        { type: 'stream', markdown: md },
      ];
    }
    const md =
`**Swap confirmed.** \`${fmt(s.amt)} ${s.from}\` → \`${fmt(s.out)} ${s.to}\`

- Status: **Confirmed**
- Tx hash: \`0x7af3…b21c\`
- New USDO balance: \`${fmt(1250 + (s.to === 'USDO' ? s.out : -s.out))} USDO\`

Anything else I can line up for you?`;
    return [
      { type: 'tool', name: 'onfa_api.execute_swap', label: 'Executing swap', ms: 1300 },
      { type: 'stream', markdown: md },
    ];
  }

  const greeting = {
    name: 'Dr.Nick',
    role: 'ONFA Advisor',
    headline: "I'm Dr.Nick, your ONFA advisor.",
    sub: 'Ask me about your balance, swaps, reserves, or drop in a document to analyze. Financial actions always preview before they run.',
    chips: [
      "What's my USDO balance?",
      'Convert 500 USDT to USDO',
      'Show USDO reserves',
      'Analyze my statement',
    ],
  };

  // ── Quick-action bar flows (persistent buttons above the composer) ─────────
  const historyAnswer =
`Your last few confirmed transactions:

| Date | Activity | Amount |
| --- | --- | --- |
| May 31 | Received USDO | \`+2,000.00\` |
| May 29 | Swap USDT → USDO | \`499.70\` |
| May 28 | OHO mining reward | \`+340.00\` |

All **confirmed**, nothing pending. Want the full statement exported?`;

  const yieldAnswer =
`Here's where you could earn on idle USDO:

- **ZenInvest · Flexible** — \`6.20%\` / yr, withdraw anytime
- **ZenInvest · 90-day** — \`8.40%\` / yr, locked term

Your USDO stays **pegged · 1.00 USD** and fully reserved throughout. Want me to delegate some now?`;

  function quick(key) {
    if (key === 'balance') {
      return [
        { type: 'tool', name: 'onfa_api.get_balance', label: 'Looking up your balance', ms: 1000 },
        { type: 'stream', markdown: balanceAnswer },
      ];
    }
    if (key === 'history') {
      return [
        { type: 'tool', name: 'onfa_api.tx_history', label: 'Pulling your history', ms: 1000 },
        { type: 'stream', markdown: historyAnswer },
      ];
    }
    if (key === 'yield') {
      return [
        { type: 'tool', name: 'onfa_api.list_yield', label: 'Checking yield options', ms: 1000 },
        { type: 'stream', markdown: yieldAnswer },
      ];
    }
    if (key === 'delegate') {
      const amt = 500, rate = 6.2;
      return [
        { type: 'tool', name: 'onfa_api.quote_delegate', label: 'Quoting your delegation', ms: 1000 },
        {
          type: 'confirm',
          action: 'delegate',
          title: 'Confirm delegation',
          summary: `Delegate ${fmt(amt)} USDO to ZenInvest`,
          confirm_token: token(),
          ttl: '4:58',
          lines: [
            { k: 'You delegate', v: `${fmt(amt)} USDO` },
            { k: 'Est. yield', v: `${rate.toFixed(2)}% / yr`, gold: true },
            { k: 'Term', v: 'Flexible' },
            { k: 'Fee', v: '0.00 USDO' },
          ],
          meta: { amt, kind: 'delegate' },
        },
      ];
    }
    return [{ type: 'stream', markdown: fallbackAnswer }];
  }

  const quickActions = [
    { key: 'delegate', label: 'Ủy thác' },
    { key: 'yield', label: 'Nhận lãi' },
    { key: 'balance', label: 'Số dư' },
    { key: 'history', label: 'Lịch sử' },
  ];

  window.DrNickEngine = { respond, confirmResult, greeting, quick, quickActions };
})();
