/**
 * SHOPIFY CHECKOUT UI EXTENSION
 * ------------------------------------------------------------------
 * This extension displays a "Pay with Interac" banner on the
 * "Thank You" or Order Status page.
 * * It grabs the Order ID, Total Amount, and Customer Email, then
 * generates a link to your Python backend to process the payment.
 */

import "@shopify/ui-extensions/preact";
import { render } from "preact";

// Entry point: Renders the Extension component into the page body
export default async () => {
  render(<Extension />, document.body);
};

function Extension() {
  // 1. CONFIGURATION
  // This is your live Python server where the payment logic lives.
  const SERVER_URL = "https://emtwerx.fintechwerx.com";

  // --- DATA FETCHING STRATEGY ---
  // We need to robustly find the Order ID. Shopify stores this in different
  // places depending on whether the user is on the "Checkout" or "Thank You" page.

  // 2. ATTEMPT 1: Order Confirmation (Best for Thank You Page)
  // The 'orderConfirmation' object usually contains the finalized Order ID.
  // @ts-ignore
  let rawId = shopify.orderConfirmation?.value?.order?.id;

  // 3. ATTEMPT 2: Fallback (Standard Order Object)
  // If 'orderConfirmation' is empty, we check the standard 'order' object.
  if (!rawId) {
    // @ts-ignore
    rawId = shopify.order?.id?.value;
  }

  // 4. CLEAN THE ID (CRITICAL STEP)
  // Shopify returns IDs in GraphQL format: "gid://shopify/Order/12345"
  // Your backend only wants the number "12345".
  // We use .split('/').pop() to take just the last part of the string.
  const orderId = rawId ? rawId.split("/").pop() : "checkout_id";

  // 5. GET FINANCIAL & USER DATA
  // We use '||' (OR) operators to provide safe defaults if data is missing
  // so the extension doesn't crash.
  // @ts-ignore
  const amount = shopify.cost?.totalAmount?.value?.amount || "0.00";
  // @ts-ignore
  const email = shopify.buyerIdentity?.email?.value || shopify.order?.email?.value || "guest@example.com";
  // @ts-ignore
  const shopDomain = shopify.shop?.myshopifyDomain || "unknown";

  // --- LOGIC ---
  // Construct the secure link that sends data to your Python backend
  const paymentLink = `${SERVER_URL}/start-payment?order_id=${orderId}&amount=${amount}&email=${email}&shop=${shopDomain}`;

  // Debugging: This prints to the browser console (Inspect Element -> Console)
  // useful for verifying if we are getting the correct "cleaned" ID.
  console.log("DEBUG ORDER ID:", { rawId, finalId: orderId });

  // --- UI RENDERING ---
  // Returns a yellow 'Warning' tone banner to grab attention
  return (
    <s-banner heading="Complete Your Payment" tone="warning">
      <s-stack gap="base">
        {/* Informative Text */}
        <s-text>
          Order <s-text>#{orderId}</s-text> placed. Please complete the transfer
          to finalize.
        </s-text>

        {/* The Action Button/Link */}
        <s-button href={paymentLink} variant="primary">
          Pay with Interac Now
        </s-button>
      </s-stack>
    </s-banner>
  );
}
