'use client';

import React, { useEffect } from 'react';

interface ShopifyOAuthEscapeProps {
  authorizeUrl: string;
  shop: string;
}

/**
 * Clean, fail-safe breakout component that escapes the Shopify Admin iframe
 * to perform top-level navigation to the official Shopify OAuth authorization screen.
 *
 * This completely bypasses App Bridge URL rewriting, preventing the 404 error
 * (admin.shopify.com/store/<shop>/apps/<client_id>/meta-connector/api/auth/shopify).
 */
export default function ShopifyOAuthEscape({ authorizeUrl, shop }: ShopifyOAuthEscapeProps) {
  useEffect(() => {
    if (typeof window === 'undefined') return;

    // 1. Try Shopify App Bridge v4 top-level open
    try {
      const shopify = (window as any).shopify;
      if (shopify && typeof shopify.open === 'function') {
        shopify.open(authorizeUrl, '_top');
        return;
      }
    } catch {}

    // 2. Try window.top direct navigation
    try {
      if (window.top && window.top !== window) {
        window.top.location.href = authorizeUrl;
        return;
      }
    } catch {}

    // 3. Fallback: Submit hidden top-level form to escape sandbox
    try {
      const form = document.getElementById('shopify-oauth-escape-form') as HTMLFormElement | null;
      if (form) {
        form.submit();
        return;
      }
    } catch {}

    // 4. If outside iframe, navigate directly
    try {
      if (!window.top || window.top === window) {
        window.location.href = authorizeUrl;
      }
    } catch {}
  }, [authorizeUrl]);

  const handleManualAuthorize = (e: React.MouseEvent) => {
    try {
      const shopify = typeof window !== 'undefined' ? (window as any).shopify : null;
      if (shopify && typeof shopify.open === 'function') {
        e.preventDefault();
        shopify.open(authorizeUrl, '_top');
        return;
      }
    } catch {}
  };

  return (
    <div className="min-h-screen bg-slate-50 flex flex-col items-center justify-center p-4">
      {/* Hidden fallback form targeting top window */}
      <form
        id="shopify-oauth-escape-form"
        action={authorizeUrl}
        method="GET"
        target="_top"
        className="hidden"
      />

      {/* Inline early breakout script to execute immediately on parse */}
      <script
        dangerouslySetInnerHTML={{
          __html: `
            (function() {
              try {
                if (window.shopify && typeof window.shopify.open === 'function') {
                  window.shopify.open(${JSON.stringify(authorizeUrl)}, '_top');
                  return;
                }
              } catch(e) {}
              try {
                if (window.top && window.top !== window) {
                  window.top.location.href = ${JSON.stringify(authorizeUrl)};
                  return;
                }
              } catch(e) {}
              try {
                var f = document.getElementById('shopify-oauth-escape-form');
                if (f) { f.submit(); }
              } catch(e) {}
            })();
          `,
        }}
      />

      <div className="max-w-md w-full bg-white rounded-2xl border border-slate-200/80 shadow-lg p-6 sm:p-8 text-center space-y-5">
        <div className="w-14 h-14 bg-theme text-white rounded-2xl flex items-center justify-center text-2xl mx-auto shadow-sm">
          ⚡
        </div>

        <div className="space-y-1.5">
          <h1 className="text-xl font-bold text-slate-900 tracking-tight">
            Connecting to Shopify
          </h1>
          <p className="text-xs text-slate-500 leading-relaxed">
            Redirecting to authorize permissions for{' '}
            <span className="font-semibold text-slate-800 font-mono">{shop}</span>
          </p>
        </div>

        <div className="flex items-center justify-center gap-2 py-3">
          <div className="w-6 h-6 border-3 border-theme border-t-transparent rounded-full animate-spin"></div>
          <span className="text-xs font-semibold text-slate-600">
            Opening Shopify Authorization...
          </span>
        </div>

        <div className="pt-2 border-t border-slate-100">
          <p className="text-[11px] text-slate-400 mb-3">
            If your browser does not redirect automatically:
          </p>
          <a
            href={authorizeUrl}
            target="_top"
            rel="noopener noreferrer"
            onClick={handleManualAuthorize}
            className="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 bg-slate-900 hover:bg-slate-800 text-white rounded-xl text-xs font-bold transition-all shadow-sm cursor-pointer"
          >
            <span>Authorize App on Shopify</span>
            <i className="fa-solid fa-arrow-right text-[10px]" />
          </a>
        </div>
      </div>
    </div>
  );
}
