"use client";

import { useState, useRef, useCallback } from "react";
import styles from "@/components/windows/WindowContent.module.css";
import { ArrowLeft, ArrowRight, RotateCw, Home, Search } from "lucide-react";

// 🧠 Debug toggle
const DEBUG =
  (typeof process !== "undefined" &&
    process.env.NODE_ENV !== "production") ||
  (typeof process !== "undefined" &&
    process.env.NEXT_PUBLIC_DEBUG === "true");

const dlog = (...args: any[]) => {
  if (DEBUG) console.log("[BrowserContent]", ...args);
};

interface BrowserContentProps {
  url: string;
}

export default function BrowserContent({ url: initialUrl }: BrowserContentProps) {
  const safeUrl =
    initialUrl && typeof initialUrl === "string"
      ? initialUrl
      : "https://example.com";

  const [currentUrl, setCurrentUrl] = useState(safeUrl);
  const [inputUrl, setInputUrl] = useState(safeUrl);
  const iframeRef = useRef<HTMLIFrameElement | null>(null);

  // 🧭 Input handlers
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputUrl(e.target.value);
  };

  const handleNavigate = (e: React.FormEvent) => {
    e.preventDefault();
    let urlToLoad = inputUrl.trim();
    if (!urlToLoad.startsWith("http://") && !urlToLoad.startsWith("https://")) {
      urlToLoad = `https://${urlToLoad}`;
    }
    setCurrentUrl(urlToLoad);
    dlog(`🌐 Navigating to ${urlToLoad}`);
  };

  const handleReload = () => {
    if (iframeRef.current) {
      iframeRef.current.src = currentUrl;
      dlog(`🔄 Reloading ${currentUrl}`);
    }
  };

  const handleGoHome = () => {
    setCurrentUrl(safeUrl);
    setInputUrl(safeUrl);
    dlog("🏠 Returning to home URL");
  };

  const handleGoBack = () => {
    alert(
      "Browser back functionality is limited in this demo due to browser security (CORS)."
    );
    dlog("⚠️ Back navigation attempted");
  };

  const handleGoForward = () => {
    alert(
      "Browser forward functionality is limited in this demo due to browser security (CORS)."
    );
    dlog("⚠️ Forward navigation attempted");
  };

  return (
    <div className={styles.browserContainer}>
      <div className={styles.browserToolbar}>
        <button onClick={handleGoBack} aria-label="Go back" title="Back">
          <ArrowLeft size={20} />
        </button>
        <button onClick={handleGoForward} aria-label="Go forward" title="Forward">
          <ArrowRight size={20} />
        </button>
        <button onClick={handleReload} aria-label="Reload page" title="Reload">
          <RotateCw size={20} />
        </button>
        <button onClick={handleGoHome} aria-label="Go home" title="Home">
          <Home size={20} />
        </button>

        <form
          onSubmit={handleNavigate}
          style={{ flexGrow: 1, display: "flex" }}
          title="Address Bar"
        >
          <input
            type="text"
            value={inputUrl}
            onChange={handleInputChange}
            placeholder="Enter URL or search"
            aria-label="URL input"
          />
          <button type="submit" aria-label="Go" title="Go">
            <Search size={20} />
          </button>
        </form>
      </div>

      <iframe
        ref={iframeRef}
        src={currentUrl}
        title="Browser"
        sandbox="allow-scripts allow-same-origin allow-popups allow-forms"
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"
        style={{
          flexGrow: 1,
          border: "none",
          background: "#fff",
        }}
        loading="lazy"
      />
    </div>
  );
}
