import { Controller, Get, Header, Query } from '@nestjs/common';
import { PrismaService } from '../common/prisma.service';

/**
 * Storefront script + config. The ScriptTag (injected on install) loads
 * marcadeo.js on the online store AND the order-status page. It:
 *  1. captures the Marcadeo click_id into a cart attribute (attribution), and
 *  2. on the thank-you page, shows an optional "become an affiliate" popup.
 */
@Controller('storefront')
export class StorefrontController {
  constructor(private prisma: PrismaService) {}

  private appUrl() {
    return (process.env.SHOPIFY_APP_URL || '').replace(/\/$/, '');
  }

  /** Order-status config for a shop (read by the storefront script; public + CORS). */
  @Get('popup-config')
  async popupConfig(@Query('shop') shop: string) {
    const merchant = shop ? await this.prisma.merchant.findUnique({ where: { shop } }) : null;
    if (!merchant) return { enabled: false, removeTracking: false };
    return {
      enabled: merchant.postCheckoutEnabled,
      removeTracking: merchant.removeTrackingAfterOrder,
      heading: merchant.postCheckoutHeading,
      text: merchant.postCheckoutText,
      button: merchant.postCheckoutButton,
      signupUrl: `${this.appUrl()}/signup`,
    };
  }

  @Get('marcadeo.js')
  @Header('Content-Type', 'application/javascript; charset=utf-8')
  @Header('Cache-Control', 'public, max-age=300')
  script(): string {
    const api = this.appUrl();
    return `(function () {
  var API = ${JSON.stringify(api)};
  // 1) Capture Marcadeo click_id -> cart attribute (attribution).
  try {
    var KEY = 'marcadeo_click_id';
    var qs = new URLSearchParams(window.location.search);
    var cid = qs.get('click_id');
    if (cid) { try { localStorage.setItem(KEY, cid); } catch (e) {} }
    var stored = cid; try { stored = stored || localStorage.getItem(KEY); } catch (e) {}
    if (stored) {
      fetch('/cart/update.js', { method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ attributes: { click_id: stored } }) }).catch(function () {});
    }
  } catch (e) {}

  // 2) Post-checkout popup on the thank-you / order-status page.
  try {
    var onOrderStatus = !!(window.Shopify && window.Shopify.Checkout) ||
      /\\/(thank[-_]?you|orders)\\b/.test(window.location.pathname);
    var shop = (window.Shopify && window.Shopify.shop) || window.location.hostname;
    if (!onOrderStatus) return;
    if (sessionStorage.getItem('trackaff_popup_shown')) return;
    fetch(API + '/api/storefront/popup-config?shop=' + encodeURIComponent(shop))
      .then(function (r) { return r.json(); })
      .then(function (c) {
        if (!c) return;
        // Clear the click_id after the order if the merchant opted in.
        if (c.removeTracking) { try { localStorage.removeItem('marcadeo_click_id'); } catch (e) {} }
        if (!c.enabled) return;
        sessionStorage.setItem('trackaff_popup_shown', '1');
        var box = document.createElement('div');
        box.style.cssText = 'position:fixed;bottom:20px;right:20px;max-width:320px;background:#fff;color:#111a2e;border-radius:14px;box-shadow:0 12px 40px rgba(0,0,0,.18);padding:18px 20px;z-index:99999;font-family:system-ui,-apple-system,sans-serif;line-height:1.5';
        var close = '<button aria-label="Close" style="position:absolute;top:8px;right:10px;border:0;background:none;font-size:18px;color:#94a3b8;cursor:pointer">×</button>';
        box.innerHTML = close +
          '<div style="font-weight:700;font-size:1.02rem;margin-bottom:4px">' + (c.heading || '') + '</div>' +
          '<div style="font-size:.88rem;color:#48546e;margin-bottom:12px">' + (c.text || '') + '</div>' +
          '<a href="' + c.signupUrl + '" target="_blank" style="display:inline-block;background:#16294d;color:#fff;text-decoration:none;font-weight:600;font-size:.9rem;padding:.55rem 1rem;border-radius:9px">' + (c.button || 'Join') + '</a>';
        document.body.appendChild(box);
        box.querySelector('button').onclick = function () { box.remove(); };
      }).catch(function () {});
  } catch (e) {}
})();`;
  }
}
