/**
Copyright 2024 Google LLC
... (لایسنس و توضیحات دیگر مثل قبل) ...
*/

import React, { useEffect, useRef, useState } from "react";
import './App.scss';
import { LiveAPIProvider, useLiveAPIContext } from "./contexts/LiveAPIContext";
import ControlTray from "./components/control-tray/ControlTray";
import { IOSModal } from "./components/ios-modal/IOSModal";
import { isIOS } from "./lib/platform";
import cn from "classnames";
import { LiveConfig } from "./multimodal-live-types";

const myCustomInstruction = `
... (دستورالعمل سفارشی شما بدون تغییر) ...
`.trim();

const initialAppConfig: LiveConfig = {
  model: "models/gemini-2.0-flash-exp",
  systemInstruction: {
    parts: [{ text: myCustomInstruction }],
  },
};

// آیکون انسان از HTML شما (برای لوگوی بزرگ و کوچک)
const SvgHumanIcon = () => (
    <svg width="70" height="70" viewBox="0 0 88 89" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M75.1481 81.6361H12.9259C9.66667 81.6361 7 78.9721 7 75.7161V58.5112C7 57.5862 7 57.1052 7.44444 56.2172C8.85185 52.9612 13 50.2232 19.4815 47.8922C24.1111 56.6982 33.3704 62.6921 44 62.6921C54.6296 62.6921 63.9259 56.6982 68.5185 47.8922C75 50.1862 79.1852 52.9982 80.5556 56.2172C81 56.6612 81 57.6232 81 58.5112V75.7161C81 78.9721 78.3333 81.6361 75.0741 81.6361H75.1481Z" stroke="currentColor" strokeWidth="6.42146" strokeLinecap="round" strokeLinejoin="round"/><path d="M44.0371 50.1862C33.8519 50.1862 25.5186 41.8612 25.5186 31.6863V26.1363C25.5186 15.9613 33.8519 7.63635 44.0371 7.63635C54.2223 7.63635 62.5556 15.9613 62.5556 26.1363V31.6863C62.5556 41.8612 54.2223 50.1862 44.0371 50.1862Z" stroke="currentColor" strokeWidth="6.42146" strokeLinecap="round" strokeLinejoin="round"/></svg>
);

// *** NEW: SVG آیکون میکروفون از HTML مرجع شما ***
// این آیکون برای حالت فعال میکروفون (PauseIcon فعلی) استفاده خواهد شد
// و آیکون دیگر (MicrophoneIcon فعلی) برای حالت غیرفعال
const SvgReferenceMicrophoneIcon = () => (
    <svg width="38" height="38" viewBox="0 0 69 68" fill="none" xmlns="http://www.w3.org/2000/svg" transform="scale(0.55)">
        <path opacity="0.4" d="M49.9479 27.1824C49.0803 27.1824 48.3907 27.872 48.3907 28.7396V32.2544C48.3907 40.1293 41.984 46.5361 34.109 46.5361C26.234 46.5361 19.8273 40.1293 19.8273 32.2544V28.7173C19.8273 27.8497 19.1377 27.1601 18.2701 27.1601C17.4025 27.1601 16.7129 27.8497 16.7129 28.7173V32.2321C16.7129 41.2861 23.6758 48.7384 32.5518 49.5393V54.2776C32.5518 55.1452 33.2414 55.8348 34.109 55.8348C34.9766 55.8348 35.6662 55.1452 35.6662 54.2776V49.5393C44.52 48.7607 51.5051 41.2861 51.5051 32.2321V28.7173C51.4829 27.872 50.7933 27.1824 49.9479 27.1824Z" fill="#BE123C"/>
        <path d="M34.1099 11.3434C28.682 11.3434 24.2773 15.7481 24.2773 21.176V32.5658C24.2773 37.9938 28.682 42.3984 34.1099 42.3984C39.5379 42.3984 43.9425 37.9938 43.9425 32.5658V21.176C43.9425 15.7481 39.5379 11.3434 34.1099 11.3434ZM37.0241 26.8042C36.8684 27.3826 36.3567 27.7608 35.7784 27.7608C35.6671 27.7608 35.5559 27.7385 35.4447 27.7163C34.5771 27.4716 33.665 27.4716 32.7974 27.7163C32.0856 27.9165 31.396 27.4938 31.218 26.8042C31.0178 26.1146 31.4404 25.4027 32.1301 25.2247C33.4426 24.8688 34.8218 24.8688 36.1343 25.2247C36.8017 25.4027 37.2021 26.1146 37.0241 26.8042ZM38.2031 22.4885C38.0029 23.0224 37.5135 23.3339 36.9796 23.3339C36.8239 23.3339 36.6904 23.3116 36.5347 23.2671C34.9775 22.6887 33.2423 22.6887 31.6852 23.2671C31.0178 23.5118 30.2614 23.1559 30.0167 22.4885C29.772 21.8212 30.128 21.0648 30.7953 20.8423C32.9309 20.0637 35.289 20.0637 37.4245 20.8423C38.0919 21.087 38.4478 21.8212 38.2031 22.4885Z" fill="#BE123C"/>
    </svg>
);


const AppInternalLogic: React.FC<{
  isMicActive: boolean;
  isCamActive: boolean;
  setIsMicActive: React.Dispatch<React.SetStateAction<boolean>>;
  setIsCamActive: React.Dispatch<React.SetStateAction<boolean>>;
  createLogoFunction: (isMini: boolean, isActive: boolean, type?: 'human' | 'ai', forFooter?: boolean) => React.ReactNode; // Added forFooter
  videoRef: React.RefObject<HTMLVideoElement>;
  notificationPopoverRef: React.RefObject<HTMLDivElement>;
  notificationButtonRef: React.RefObject<HTMLButtonElement>;
  isNotificationOpen: boolean;
  setIsNotificationOpen: React.Dispatch<React.SetStateAction<boolean>>;
}> = ({
  isMicActive,
  isCamActive,
  setIsMicActive,
  setIsCamActive,
  createLogoFunction,
  videoRef,
  notificationPopoverRef,
  notificationButtonRef,
  isNotificationOpen,
  setIsNotificationOpen
}) => {
  const { connected, disconnect } = useLiveAPIContext();

  useEffect(() => {
    if (!isMicActive && !isCamActive && connected) {
      disconnect();
    }
  }, [isMicActive, isCamActive, connected, disconnect]);

  return (
    <div className="w-full flex flex-col items-center justify-center min-h-screen text-foreground antialiased">
      <div className="main-wrapper max-w-3xl w-full flex flex-col items-center justify-center h-full relative"> {/* Added class main-wrapper */}
        <div className="header-controls">
          <div id="notification-trigger-container">
            <button
              ref={notificationButtonRef}
              id="notification-button"
              aria-label="Notifications"
              className="header-button"
              onClick={(e) => {
                  e.stopPropagation();
                  setIsNotificationOpen(!isNotificationOpen);
                }}
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
            </button>
          </div>
          <div className="back-button-container">
            <button
              id="back-button"
              aria-label="Go back"
              className="header-button"
              onClick={() => alert('Back clicked (implement navigation)')}
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"></path></svg>
            </button>
          </div>
        </div>

        <div ref={notificationPopoverRef} id="notification-popover-wrapper" className="notification-popover-wrapper">
          <div
            id="notification-popover"
            className={cn("popover-content", {
              "open animate-popover-open-top-center": isNotificationOpen,
              "animate-popover-close-top-center": !isNotificationOpen && document.getElementById('notification-popover')?.classList.contains('open'),
            })}
          >
            <div className="notification-popover-text-content">
              مدل‌های هوش مصنوعی می‌توانند اشتباه کنند، صحت اطلاعات مهم را بررسی کنید و از وارد کردن اطلاعات حساس بپرهیزید.
            </div>
          </div>
        </div>

        {/* Media and Large Logo Area */}
        <div className="media-area w-full flex flex-col items-center justify-center flex-grow relative"> {/* Added class media-area */}
          <video
            id="video-feed"
            ref={videoRef}
            autoPlay
            playsInline
            className={cn(
              "absolute top-0 left-0 w-full h-full object-cover scale-x-[-1]",
              { "hidden": !isCamActive }
            )}
          />
          {/* Large Logo - Only when Mic is active AND Cam is NOT active */}
          {isMicActive && !isCamActive && (
            <div
              id="large-logo-container"
              className="absolute top-0 left-0 w-full h-full flex items-center justify-center"
            >
              {createLogoFunction(false, true, 'human', false)}
            </div>
          )}
        </div>

        <ControlTray
          videoRef={videoRef}
          supportsVideo={true}
          onVideoStreamChange={(stream) => { /* ... */ }}
          isAppMicActive={isMicActive}
          onAppMicToggle={setIsMicActive}
          isAppCamActive={isCamActive}
          onAppCamToggle={setIsCamActive}
          createLogoFunction={createLogoFunction}
          // Pass SvgReferenceMicrophoneIcon to ControlTray
          ReferenceMicrophoneIcon={SvgReferenceMicrophoneIcon}
        />
      </div>
    </div>
  );
}

const logoColorConfig = {
  blue: { // For human
    ping: "bg-blue-200 dark:bg-blue-700",
    outer: "bg-blue-200 dark:bg-blue-700",
    mid: "bg-blue-300 dark:bg-blue-600",
    inner: "bg-blue-400 dark:bg-blue-500",
  },
  green: { // For AI (if you add it)
    ping: "bg-green-200 dark:bg-green-700",
    outer: "bg-green-200 dark:bg-green-700",
    mid: "bg-green-300 dark:bg-green-600",
    inner: "bg-green-400 dark:bg-green-500",
  },
  gray: { // Default/Fallback
    ping: "bg-gray-200 dark:bg-gray-700",
    outer: "bg-gray-200 dark:bg-gray-700",
    mid: "bg-gray-300 dark:bg-gray-600",
    inner: "bg-gray-400 dark:bg-gray-500",
  }
};

function App() {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [showIOSModal, setShowIOSModal] = useState(false);
  const [isAllowedOrigin, setIsAllowedOrigin] = useState<boolean | null>(null);

  const [isMicActive, setIsMicActive] = useState(false);
  const [isCamActive, setIsCamActive] = useState(false);
  const [isNotificationOpen, setIsNotificationOpen] = useState(false);

  const notificationPopoverRef = useRef<HTMLDivElement>(null);
  const notificationButtonRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (isIOS()) {
      setShowIOSModal(true);
    }
    const timer = setTimeout(() => {
        setIsAllowedOrigin(true);
    }, 100);
    return () => clearTimeout(timer);
  }, []);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        isNotificationOpen &&
        notificationPopoverRef.current &&
        !notificationPopoverRef.current.contains(event.target as Node) &&
        notificationButtonRef.current &&
        !notificationButtonRef.current.contains(event.target as Node)
      ) {
        setIsNotificationOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isNotificationOpen]);

  if (isAllowedOrigin === null) {
    return <div style={{ padding: '20px', textAlign: 'center' }}>در حال بررسی دسترسی...</div>;
  }

  const createLogoFunction = (isMini: boolean, isActive: boolean, type: 'human' | 'ai' = 'human', forFooter: boolean = false) => {
    if (!isActive) return null;

    // Use blue for human, green for AI, gray as fallback
    const colorKey = type === 'human' ? 'blue' : (type === 'ai' ? 'green' : 'gray');
    const currentColors = logoColorConfig[colorKey as keyof typeof logoColorConfig] || logoColorConfig.gray;

    const size = isMini ? 80 : 200; // Size for the overall logo animation
    const iconSize = isMini ? 35 : 70; // This is for the SvgHumanIcon's container, actual SVG might have own size
    
    // Adjust inset for icon based on whether it's for footer or large display
    // This is crucial for centering the icon within the pulsing circles.
    let iconInset;
    if (isMini) { // Small logo (for footer)
        iconInset = 22; // Original value for small
    } else { // Large logo (center screen)
        iconInset = 65; // Original value for large
    }
    
    const insetBase = {
        ping: isMini ? 10 : 40,
        outer: 0,
        mid: isMini ? 5 : 20,
        inner: isMini ? 12 : 50,
        icon: iconInset
    };


    return (
      <div className={cn("logo-animation-wrapper", {"for-footer": forFooter})} style={{ width: `${size}px`, height: `${size}px` }}>
        <div className={`absolute rounded-full opacity-50 animate-ping ${currentColors.ping}`} style={{ inset: `${insetBase.ping}px` }}></div>
        <div className={`absolute rounded-full opacity-50 ${currentColors.outer}`} style={{ inset: `${insetBase.outer}px` }}></div>
        <div className={`absolute rounded-full opacity-50 ${currentColors.mid}`} style={{ inset: `${insetBase.mid}px` }}></div>
        <div className={`absolute rounded-full opacity-50 ${currentColors.inner}`} style={{ inset: `${insetBase.inner}px` }}></div>
        <div className="z-10 absolute flex items-center justify-center" style={{ inset: `${insetBase.icon}px` }}>
          {type === 'human' && <SvgHumanIcon />}
          {/* Add AI icon here if needed: type === 'ai' && <SvgAiIcon /> */}
        </div>
      </div>
    );
  };


  return (
    <LiveAPIProvider initialConfig={initialAppConfig}>
      <AppInternalLogic
        isMicActive={isMicActive}
        setIsMicActive={setIsMicActive}
        isCamActive={isCamActive}
        setIsCamActive={setIsCamActive}
        createLogoFunction={createLogoFunction}
        videoRef={videoRef}
        notificationPopoverRef={notificationPopoverRef}
        notificationButtonRef={notificationButtonRef}
        isNotificationOpen={isNotificationOpen}
        setIsNotificationOpen={setIsNotificationOpen}
      />
      <IOSModal isOpen={showIOSModal} onClose={() => setShowIOSModal(false)} />
    </LiveAPIProvider>
  );
}

export default App;