// Nordbank — Sherpa checkout integration.
// =============================================================================
//
//   ⚠️  CREDENTIALS — DO NOT SHIP THESE IN PRODUCTION  ⚠️
//
//   The Sherpa API expects a `Client {id}:{secret}` Authorization header.
//   Putting that header in the browser leaks your client secret to every
//   visitor. For production you MUST proxy this call through your own server
//   (a tiny Cloudflare Worker is plenty — see SAMPLE_WORKER below) and call
//   YOUR server from the browser.
//
//   For this demo the call runs client-side. Fill in the two constants here:
//
const SHERPA_CLIENT_ID     = '';      // proxy carries creds — leave blank
const SHERPA_CLIENT_SECRET = '';      // proxy carries creds — leave blank
//
//   Two ways to fill them in:
//     (a) Edit this file directly — quick and dirty for the sales demo.
//     (b) Set `window.SHERPA_CLIENT_ID` and `window.SHERPA_CLIENT_SECRET` in an
//         inline <script> in Nordbank.html BEFORE this file loads — that lets
//         you keep secrets out of the committed source.
//
//   When you move to a proxy, point SHERPA_PROXY_URL at your endpoint and
//   leave the credentials blank; the proxy adds the Authorization header.
//
const SHERPA_PROXY_URL = '/api/sherpa'; // Cloudflare Pages Function — see functions/api/sherpa.js
//
// -----------------------------------------------------------------------------
//   SAMPLE_WORKER — Cloudflare Worker that proxies this call. Deploy this
//   and set SHERPA_PROXY_URL above to its URL.
//
//   // wrangler.toml: bind SHERPA_CLIENT_ID / SHERPA_CLIENT_SECRET as secrets
//   export default {
//     async fetch(request, env) {
//       if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 });
//       const body = await request.text();
//       const r = await fetch('https://sherpa-api.dev.gangkhar.dev/v1/policy/embed-checkout', {
//         method: 'POST',
//         headers: {
//           'Authorization': 'Client ' + env.SHERPA_CLIENT_ID + ':' + env.SHERPA_CLIENT_SECRET,
//           'Content-Type': 'application/json',
//         },
//         body,
//       });
//       return new Response(await r.text(), {
//         status: r.status,
//         headers: {
//           'Content-Type': 'application/json',
//           'Access-Control-Allow-Origin': 'https://your-site.example.com',
//         },
//       });
//     },
//     async options() {
//       return new Response(null, {
//         headers: {
//           'Access-Control-Allow-Origin': 'https://your-site.example.com',
//           'Access-Control-Allow-Methods': 'POST, OPTIONS',
//           'Access-Control-Allow-Headers': 'Content-Type',
//         },
//       });
//     }
//   };
// =============================================================================

const SHERPA_API_URL    = 'https://sherpa-api.dev.gangkhar.dev/v1/policy/embed-checkout';
const SHERPA_EMBED_ORIGIN = 'https://embed.dev.gangkhar.dev';

// Map UI language → Sherpa context (country code + display currency).
const LANG_TO_SHERPA_CONTEXT = {
  no: { country: 'no', displayCurrency: 'nok' },
  da: { country: 'dk', displayCurrency: 'dkk' },
  sv: { country: 'se', displayCurrency: 'sek' },
  fi: { country: 'fi', displayCurrency: 'eur' },
  en: { country: 'no', displayCurrency: 'nok' }, // English visitor defaults to NO/NOK
};

function sherpaContextForLang(lang) {
  return LANG_TO_SHERPA_CONTEXT[lang] || LANG_TO_SHERPA_CONTEXT.no;
}

// Build the request body from the wizard's application state.
function buildSherpaPayload(app, premium) {
  const [firstName, ...rest] = (app.personal.name || '').trim().split(/\s+/);
  const lastName = rest.join(' ') || '';
  const termMonths = String(Math.round((app.termYears || 1) * 12));
  return {
    productName: 'loan_protection_insurance',
    productPlanName: 'coverage',
    quoteParameters: {
      insuranceCoverage: {
        totalSumInsured: app.amount,
        repaymentTerm: termMonths,
      },
    },
    policyParameters: {
      personal: {
        firstName: firstName || '',
        lastName: lastName,
        // We don't ask for gender on the loan form. Sherpa requires it; pass
        // "unspecified" — adjust here if the API rejects it.
        gender: 'unspecified',
        birthDate: app.personal.dob || '',
        email: app.personal.email || '',
        mobilePhone: app.personal.phone || '',
        address: { addressAutocomplete: null },
      },
    },
    premiumsByFrequency: {
      month: {
        premiumWithoutTax: Math.round(premium * 100) / 100,
        salesTax: 0,
        premiumWithTax: Math.round(premium * 100) / 100,
      },
    },
    paymentFrequency: 'month',
    successUrl: location.origin + location.pathname + '#/portal/insurance',
  };
}

// Create an embedded-checkout session.
// Returns: { embedCheckoutSessionId, policyId, policyOrderId, expiresAt }
async function createSherpaCheckout(app, premium) {
  const body = buildSherpaPayload(app, premium);

  // Prefer the server proxy when configured.
  if (SHERPA_PROXY_URL) {
    const res = await fetch(SHERPA_PROXY_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    if (!res.ok) throw new Error('Sherpa proxy returned ' + res.status);
    return res.json();
  }

  // Direct call — only acceptable during the demo. Logs a loud warning.
  if (SHERPA_CLIENT_ID === 'YOUR_CLIENT_ID' || SHERPA_CLIENT_SECRET === 'YOUR_CLIENT_SECRET') {
    console.warn('[sherpa] Using placeholder credentials — request will fail. Edit nordbank/sherpa.jsx (or set window.SHERPA_CLIENT_ID/SECRET) and reload.');
  }
  const clientId     = window.SHERPA_CLIENT_ID     || SHERPA_CLIENT_ID;
  const clientSecret = window.SHERPA_CLIENT_SECRET || SHERPA_CLIENT_SECRET;

  const res = await fetch(SHERPA_API_URL, {
    method: 'POST',
    headers: {
      'Authorization': 'Client ' + clientId + ':' + clientSecret,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });
  if (!res.ok) {
    const text = await res.text().catch(() => '');
    throw new Error('Sherpa API returned ' + res.status + ': ' + text);
  }
  return res.json();
}

Object.assign(window, {
  SHERPA_API_URL,
  SHERPA_EMBED_ORIGIN,
  LANG_TO_SHERPA_CONTEXT,
  sherpaContextForLang,
  buildSherpaPayload,
  createSherpaCheckout,
});
