'use client';

import React, { useEffect, useState } from 'react';
import { AlertCircle, RefreshCw } from 'lucide-react';
import { config } from '../lib/config';

export default function CMSConnectivityNotice() {
  const [, setStatus] = useState<'checking' | 'ok' | 'error'>('checking');
  const [errorMsg, setErrorMsg] = useState('');
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    // Only show if we've detected an issue AND we are in a context where we want to see it
    const checkCMS = async () => {
      const isDebug = new URLSearchParams(window.location.search).has('cms_debug');
      const isLocal = config.isDevelopment;
      const isTesting = config.isTesting;
      const target = process.env.NEXT_PUBLIC_TARGET || '';
      const isBranch = target === 'branch';

      // Only proceed with check if it's developer context (Local, Testing, or Branch preview)
      // Staging and Production should NEVER see this unless forced with ?cms_debug
      if (!isLocal && !isTesting && !isBranch && !isDebug) return;

      try {
        const response = await fetch('/api/health/cms');
        const data = await response.json();

        if (data.status !== 'ok') {
          setStatus('error');
          setErrorMsg(data.message);
          setIsVisible(true);
        } else {
          setStatus('ok');
          setIsVisible(false);
        }
      } catch {
        // If it's a connection error, only show if we are really debugging
        if (isDebug || isLocal) {
          setStatus('error');
          setErrorMsg('Could not connect to CMS health endpoint');
          setIsVisible(true);
        }
      }
    };

    checkCMS();
  }, []);

  if (!isVisible) return null;

  return (
    <div className="fixed bottom-4 right-4 z-[9999] animate-slide-up">
      <div className="bg-red-500/90 backdrop-blur-md border border-red-400 text-white p-4 rounded-2xl shadow-2xl max-w-sm">
        <div className="flex items-start gap-3">
          <div className="bg-white/20 p-2 rounded-lg">
            <AlertCircle className="w-5 h-5" />
          </div>
          <div className="flex-1">
            <h4 className="font-bold text-sm mb-1">CMS Issue Detected</h4>
            <p className="text-xs opacity-90 leading-relaxed mb-3">
              {errorMsg === 'relation "products" does not exist'
                ? 'The database schema is missing. Please run migrations for this environment.'
                : 'A content service is unavailable. Check the deployment logs for details.'}
            </p>
            <div className="flex gap-2">
              <button
                onClick={() => window.location.reload()}
                className="bg-white text-red-600 text-[10px] font-bold uppercase tracking-wider px-3 py-1.5 rounded-lg flex items-center gap-2 hover:bg-neutral-100 transition-colors"
              >
                <RefreshCw className="w-3 h-3" />
                Retry
              </button>
              <button
                onClick={() => setIsVisible(false)}
                className="bg-black/20 text-white text-[10px] font-bold uppercase tracking-wider px-3 py-1.5 rounded-lg hover:bg-black/30 transition-colors"
              >
                Dismiss
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
