/**
 * Chat Window Component
 * The main chat interface with appearance settings support
 * 
 * @since 1.5.0 - Added full appearance preset support
 * @since 1.5.1 - Added opening screen support
 * @since 1.6.0 - Added mobile-specific layout (vw/vh units)
 */

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ChatHeader } from './ChatHeader';
import { CartDrawer } from './CartDrawer';
import { MessageList } from './MessageList';
import { InputArea } from './InputArea';
import { OpeningScreen } from './widgets/OpeningScreen';
import { useChatStore } from '@/store/chatStore';
import { resolveValue, GlobalValues, clampWidth, clampHeight } from '@/utils/resolveAppearance';
import { t } from '@/lib/i18n';

// Mobile detection hook (viewport-based, responsive to resize)
function useIsMobile(breakpoint = 768) {
  const [isMobile, setIsMobile] = useState(() => 
    typeof window !== 'undefined' ? window.innerWidth < breakpoint : false
  );
  
  useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth < breakpoint);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [breakpoint]);
  
  return isMobile;
}

export function ChatWindow() {
  const { isOpen, isCartOpen, config, messages, sendMessage, addScriptedExchange } = useChatStore();
  const isMobile = useIsMobile();
  const isRtl = window.boostbot_config?.is_rtl ?? true;
  const showWatermark = !!config.watermark?.enabled && !!config.watermark?.text;
  const isTestMode = config.is_test_mode === true;
  const showCartUi = config.woocommerce?.active === true && config.woocommerce?.show_cart_button === true;
  
  // Check if we should show opening screen
  const openingScreen = config.opening_screen;
  const hasOpeningScreen = openingScreen?.has_opening_screen && openingScreen?.mode;
  // Hide opening screen as soon as user sends any message
  const hasUserMessages = messages.some(m => m.role === 'user');
  const showOpeningScreen = hasOpeningScreen && !hasUserMessages;
  
  // Handle opening screen button/question click (questions_ai mode)
  // Passes AI instructions as context for the AI to use when answering
  const handleOpeningAction = (message: string, aiInstructions?: string) => {
    sendMessage(message, aiInstructions ? { aiInstructions } : undefined);
  };
  
  // Handle Q&A answer display (questions_answers mode)
  // Shows the pre-built answer directly without calling the AI
  const handleAnswerShow = (question: string, answer: string) => {
    addScriptedExchange(question, answer);
  };
  
  // Get appearance settings
  const globalValues = (config.appearance_preset?.global_values || {}) as GlobalValues;
  const windowSettings = config.element_settings?.chatWindow || config.appearance_preset?.element_settings?.chatWindow;
  
  // Resolve window settings with defaults and clamping
  const rawWidth = resolveValue(windowSettings?.width, globalValues, '380px');
  const rawHeight = resolveValue(windowSettings?.height, globalValues, '600px');
  const width = clampWidth(rawWidth, 'chatWindow', '380px');
  const height = clampHeight(rawHeight, 'chatWindow', '600px');
  const background = resolveValue(windowSettings?.background, globalValues, '#FFFFFF');
  const borderRadius = resolveValue(windowSettings?.borderRadius, globalValues, '16px');
  const shadow = resolveValue(windowSettings?.shadow, globalValues, '4px 10px 15px -3px rgba(0, 0, 0, 0.2)');
  const padding = resolveValue(windowSettings?.padding, globalValues, '0');
  const borderType = windowSettings?.borderType || 'solid';
  const borderWidth = (() => {
    const bw = (windowSettings as any)?.borderWidth;
    if (bw && typeof bw === 'object') {
      const o = bw as any;
      if (typeof o.top === 'string' && typeof o.right === 'string' && typeof o.bottom === 'string' && typeof o.left === 'string') {
        return `${o.top} ${o.right} ${o.bottom} ${o.left}`;
      }
    }
    return resolveValue(bw, globalValues, '1px');
  })();
  const borderColor = resolveValue(windowSettings?.borderColor, globalValues, 'rgba(0,0,0,0.05)');
  
  // Position based on config (from bubble settings or direct config)
  const bubbleSettings = config.element_settings?.chatBubble || config.appearance_preset?.element_settings?.chatBubble;
  const position = (bubbleSettings?.position || config.position || 'bottom-right') as
    | 'bottom-right'
    | 'bottom-left'
    | 'top-right'
    | 'top-left';
  const margin = (() => {
    const m = (bubbleSettings as any)?.margin
    if (m && typeof m === 'object' && 'top' in m && 'right' in m && 'bottom' in m && 'left' in m) {
      return {
        top: m.top || '24px',
        right: m.right || '24px',
        bottom: m.bottom || '24px',
        left: m.left || '24px',
      }
    }
    const resolved = resolveValue(m, globalValues, '24px')
    return { top: resolved, right: resolved, bottom: resolved, left: resolved }
  })();
  
  // Mobile layout settings (from config, with defaults)
  const mobileWidthVw = config.mobile_layout?.width_vw ?? 94;
  const mobileHeightVh = config.mobile_layout?.height_vh ?? 75;
  const mobileMarginTopVh = config.mobile_layout?.margin_top_vh ?? 20;
  // Note: bottom margin is implicit (100 - top - height), not used in CSS directly
  // Side margin is auto-calculated from width (centered)
  const mobileMarginSideVw = (100 - mobileWidthVw) / 2;
  
  // Position styles - mobile uses centered positioning with vw/vh units
  const desktopPositionStyles =
    position === 'bottom-left'
      ? { left: margin.left, right: 'auto' }
      : position === 'top-left'
        ? { left: margin.left, right: 'auto' }
        : position === 'top-right'
          ? { right: margin.right, left: 'auto' }
          : { right: margin.right, left: 'auto' };
  
  // Mobile: center horizontally, position from top with explicit height
  // Note: We use top + height (not both top and bottom) to avoid CSS conflicts
  const mobilePositionStyles = {
    left: `${mobileMarginSideVw}vw`,
    right: `${mobileMarginSideVw}vw`,
    top: `${mobileMarginTopVh}vh`,
    // Don't set bottom - let height determine it
    width: `${mobileWidthVw}vw`,
    height: `${mobileHeightVh}vh`,
    maxWidth: `calc(100vw - ${mobileMarginSideVw * 2}vw)`,
    maxHeight: `${mobileHeightVh}vh`,
  };
  
  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          className="bb-chat-window fixed z-[9999999] flex flex-col overflow-hidden"
          style={isMobile ? {
            // Mobile: centered with vw/vh units
            ...mobilePositionStyles,
            backgroundColor: background,
            borderRadius,
            boxShadow: shadow,
            padding,
            borderStyle: isTestMode ? 'dashed' : borderType,
            borderWidth: isTestMode ? '2px' : (borderType === 'none' ? '0' : borderWidth),
            borderColor: isTestMode ? '#d97706' : borderColor,
          } : {
            // Desktop: bubble-based positioning
            ...desktopPositionStyles,
            bottom: position.startsWith('bottom')
              ? `calc(80px + ${margin.bottom})`
              : 'auto',
            top: position.startsWith('top')
              ? `calc(80px + ${margin.top})`
              : 'auto',
            width: `min(${width}, calc(100vw - 2rem))`,
            height: `min(${height}, calc(100vh - 120px))`,
            maxHeight: 'calc(100vh - 120px)',
            backgroundColor: background,
            borderRadius,
            boxShadow: shadow,
            padding,
            borderStyle: isTestMode ? 'dashed' : borderType,
            borderWidth: isTestMode ? '2px' : (borderType === 'none' ? '0' : borderWidth),
            borderColor: isTestMode ? '#d97706' : borderColor,
          }}
          dir={isRtl ? 'rtl' : 'ltr'}
          initial={{ opacity: 0, y: 20, scale: 0.95 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: 20, scale: 0.95 }}
          transition={{ type: 'spring', stiffness: 300, damping: 25 }}
          role="dialog"
          aria-modal="true"
          aria-label={t('Chat with bot')}
        >
          {isTestMode && (
            <div className="absolute top-2 start-1/2 -translate-x-1/2 z-20 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-amber-100 text-amber-700 border border-amber-300">
              {t('Test mode')}
            </div>
          )}

          {/* Header */}
          <ChatHeader />
          
          {showCartUi && isCartOpen ? (
            <div className="flex-1 overflow-hidden p-3 pt-0">
              <CartDrawer />
            </div>
          ) : (
            <>
              {/* Messages Area */}
              <div 
                className="flex-1 overflow-hidden relative"
                style={{ backgroundColor: background }}
              >
                {/* Keep MessageList mounted to avoid first-render race conditions for streaming placeholders.
                    When Opening Screen is visible we hide interactions/visibility via CSS instead of unmounting. */}
                <div className={showOpeningScreen ? 'h-full opacity-0 pointer-events-none' : 'h-full'}>
                  <MessageList />
                </div>
                
                {/* Opening Screen - show after welcome message if configured */}
                {showOpeningScreen && openingScreen && (
                  <div className="absolute inset-0 flex flex-col">
                    <OpeningScreen
                      data={{
                        mode: openingScreen.mode!,
                        questions: openingScreen.questions?.map((q, i) => ({ id: i, ...q })),
                        ai_instructions: openingScreen.ai_instructions,
                        qa_pairs: openingScreen.qa_pairs?.map((qa, i) => ({ id: i, ...qa })),
                      }}
                      onQuestionClick={handleOpeningAction}
                      onAnswerShow={handleAnswerShow}
                      primaryColor={config.primary_color || '#3BC2D0'}
                      welcomeText={openingScreen.show_welcome !== false ? openingScreen.welcome_text : undefined}
                      botName={config.bot_name}
                      avatarUrl={config.avatar_url}
                      language={config.language}
                    />
                  </div>
                )}
              </div>
              
              {/* Input Area */}
              <div className="bb-chat-footer">
                <InputArea />
                {showWatermark && (
                  <div className="bb-watermark text-[10px] text-gray-400 text-center py-2 border-t border-gray-100">
                    {config.watermark!.text}
                  </div>
                )}
              </div>
            </>
          )}
        </motion.div>
      )}
    </AnimatePresence>
  );
}
