import { NextRequest, NextResponse } from 'next/server';
import { buildShopifyAuthUrl } from '@/lib/shopify/oauth';
import { isValidShopifyDomain } from '@/lib/shopify/hmac';
import { APP_CONFIG, APP_URLS, buildAppUrl } from '@/config/app';
import { SHOPIFY_CONFIG } from '@/config/shopify';
import { extractShopDomainFromRequest } from '@/lib/auth/storeContext';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  let shop = searchParams.get('shop') || searchParams.get('shopify_domain');

  // If shop not in query params, inspect session tokens, referer header, or cookies
  if (!shop) {
    const extracted = extractShopDomainFromRequest(req);
    if (extracted) {
      shop = extracted;
    }
  }

  // 1. If valid shop domain identified, proceed with OAuth authorization
  if (shop && isValidShopifyDomain(shop)) {
    const cleanShop = shop.trim().toLowerCase();
    const redirectUri = APP_URLS.authCallback();

    try {
      const { url: authorizeUrl } = buildShopifyAuthUrl(cleanShop, redirectUri);

      // Return JSON directly if requested by client component (settings/catalog page)
      if (searchParams.get('format') === 'json' || req.headers.get('accept')?.includes('application/json')) {
        return NextResponse.json({
          success: true,
          shop: cleanShop,
          url: authorizeUrl,
        });
      }

      // Check if request is loaded inside an iframe
      const secFetchDest = req.headers.get('sec-fetch-dest');
      const isEmbedded = searchParams.get('embedded') === '1' || Boolean(searchParams.get('host'));
      const isIframe = secFetchDest === 'iframe' || isEmbedded;

      // Direct top-level navigation (e.g. from browser address bar or form submit)
      if (!isIframe) {
        return NextResponse.redirect(authorizeUrl);
      }

      // If loaded inside an iframe, escape directly to window.top WITHOUT App Bridge script
      // (App Bridge script was incorrectly intercepting and rewriting the URL to admin.shopify.com 404)
      return new Response(
        `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Connecting to ${cleanShop}...</title>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 80vh; background: #f8fafc; margin: 0;">
  <div style="text-align: center; max-width: 480px; padding: 36px 28px; background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.06); border: 1px solid #e2e8f0; margin: 20px;">
    <div style="width: 56px; height: 56px; border-radius: 14px; background: #0f172a; color: white; display: flex; align-items: center; justify-content: center; font-size: 26px; margin: 0 auto 16px;">
      ⚡
    </div>
    <h2 style="margin: 0 0 8px; color: #0f172a; font-size: 20px; font-weight: 700;">Connecting to Shopify</h2>
    <p style="color: #64748b; font-size: 14px; margin-bottom: 24px; line-height: 1.5;">
      Redirecting to authorize permissions for <strong>${cleanShop}</strong>. If not redirected automatically, please click below:
    </p>
    <form id="esc" action="${authorizeUrl}" method="GET" target="_top" style="display:none;"></form>
    <a href="${authorizeUrl}" target="_top" style="display: inline-block; padding: 12px 28px; background: #0f172a; color: white; border-radius: 10px; text-decoration: none; font-weight: 600; font-size: 14px; transition: background 0.2s;">
      Authorize App on Shopify &rarr;
    </a>
  </div>
  <script>
    var target = ${JSON.stringify(authorizeUrl)};
    try {
      if (window.shopify && typeof window.shopify.open === 'function') {
        window.shopify.open(target, '_top');
      } else if (window.top && window.top !== window) {
        window.top.location.href = target;
      } else {
        document.getElementById('esc').submit();
      }
    } catch (e) {
      try {
        document.getElementById('esc').submit();
      } catch (err) {}
    }
  </script>
</body>
</html>`,
        {
          status: 200,
          headers: {
            'Content-Type': 'text/html; charset=utf-8',
            'Content-Security-Policy': "frame-ancestors https://*.myshopify.com https://admin.shopify.com https://*.shopify.com https://shopify.com 'self';",
          },
        }
      );
    } catch (err) {
      return NextResponse.json(
        { error: err instanceof Error ? err.message : 'OAuth Initialization Failed' },
        { status: 500 }
      );
    }
  }

  // 2. If NO shop parameter provided (e.g. direct visit, reviewer audit, or public landing):
  // Render a clean, standalone Shopify install landing page with store input form.
  const authEndpoint = buildAppUrl('/api/auth/shopify');

  return new Response(
    `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Install ${APP_CONFIG.name}</title>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; }
    body { background-color: #f8fafc; color: #0f172a; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 20px; }
    .card { background: #ffffff; max-width: 460px; width: 100%; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.01); padding: 40px 32px; text-align: center; }
    .logo-badge { width: 56px; height: 56px; border-radius: 16px; background: #0f172a; color: white; display: inline-flex; align-items: center; justify-content: center; font-size: 26px; margin-bottom: 20px; box-shadow: 0 4px 12px rgba(15, 23, 42, 0.15); }
    h1 { font-size: 22px; font-weight: 800; color: #0f172a; margin-bottom: 8px; letter-spacing: -0.02em; }
    p.desc { font-size: 14px; color: #64748b; line-height: 1.5; margin-bottom: 28px; }
    .form-group { text-align: left; margin-bottom: 20px; }
    label { display: block; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: #475569; margin-bottom: 8px; }
    .input-wrapper { display: flex; align-items: center; border: 1.5px solid #cbd5e1; border-radius: 12px; background: #f8fafc; transition: border-color 0.2s, box-shadow 0.2s; overflow: hidden; }
    .input-wrapper:focus-within { border-color: #0f172a; box-shadow: 0 0 0 3px rgba(15, 23, 42, 0.1); background: #ffffff; }
    input[type="text"] { flex: 1; border: none; outline: none; background: transparent; padding: 12px 14px; font-size: 14px; color: #0f172a; font-weight: 500; }
    .btn { display: block; width: 100%; padding: 13px 20px; background: #0f172a; color: #ffffff; border: none; border-radius: 12px; font-size: 14px; font-weight: 700; cursor: pointer; transition: background 0.2s, transform 0.1s; }
    .btn:hover { background: #1e293b; }
    .btn:active { transform: scale(0.99); }
    .features { margin-top: 28px; padding-top: 24px; border-top: 1px solid #f1f5f9; display: flex; justify-content: center; gap: 16px; font-size: 11px; color: #64748b; font-weight: 600; }
    .feature-item { display: flex; align-items: center; gap: 4px; }
  </style>
  <script>
    function handleSubmit(e) {
      e.preventDefault();
      var input = document.getElementById('shopInput');
      var val = (input ? input.value : '').trim().toLowerCase();
      if (!val) return;
      val = val.replace(/^https?:\\/\\//, '').replace(/\\/.*$/, '');
      if (!val.includes('.')) {
        val = val + '.myshopify.com';
      }
      var target = "${authEndpoint}?shop=" + encodeURIComponent(val);
      if (window.top && window.top !== window) {
        window.top.location.href = target;
      } else {
        window.location.href = target;
      }
    }
  </script>
</head>
<body>
  <div class="card">
    <div class="logo-badge">⚡</div>
    <h1>${APP_CONFIG.name}</h1>
    <p class="desc">Connect multiple Facebook Pixels, Conversions API (CAPI), and live dynamic product feeds to your Shopify store.</p>

    <form onsubmit="handleSubmit(event)">
      <div class="form-group">
        <label for="shopInput">Shopify Store Domain</label>
        <div class="input-wrapper">
          <input
            type="text"
            id="shopInput"
            name="shop"
            placeholder="your-store-name.myshopify.com"
            required
            autocomplete="off"
            spellcheck="false"
          />
        </div>
      </div>
      <button type="submit" class="btn">Install App on Shopify &rarr;</button>
    </form>

    <div class="features">
      <div class="feature-item"><span>🔒</span> Official Shopify Partner</div>
      <div class="feature-item"><span>🛡️</span> 100% Embedded App</div>
    </div>
  </div>
</body>
</html>`,
    {
      status: 200,
      headers: {
        'Content-Type': 'text/html; charset=utf-8',
        'Content-Security-Policy': "frame-ancestors https://*.myshopify.com https://admin.shopify.com https://*.shopify.com https://shopify.com 'self';",
      },
    }
  );
}
