import React, { useState, useRef, useEffect } from "react";
import { createRoot } from "react-dom/client";

// --- Icons ---
const UploadIcon = () => (
  <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="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
);
const XIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
);
const FileImageIcon = () => (
  <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="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>
);
const PdfIcon = () => (
  <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="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>
);
const HtmlIcon = () => (
  <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"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg>
);
const LoaderIcon = () => (
  <svg className="animate-spin" 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="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
);
const LensIcon = () => (
  <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="M2 12h20"/><path d="M12 2v20"/><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="4"/></svg>
);
const PrintIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
);
const DownloadIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
);
const HistoryIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20v-6M6 20V10M18 20V4"/></svg>
);
const BrandLogo = ({ className = "h-9 w-auto" }: { className?: string }) => (
  <span className="inline-flex items-center bg-[#1a1a1a] px-4 py-2.5 rounded-md">
    <img src="/logo.png" alt="TRD Studios" className={className} />
  </span>
);
const InfoIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
);

// --- Constants ---
const APP_GRADIENT = "linear-gradient(126deg, #c3e0d4 -20%, rgb(230, 244, 255) 35.69%, rgb(221, 203, 247) 75.03%, rgb(250, 230, 243) 100%)";


// --- Types ---
interface Report {
  id: string;
  type: 'heuristics' | 'laws';
  html: string;
  url: string;
  timestamp: Date;
}

interface Asset {
  file: File;
  preview: string;
  base64: string;
  mimeType: string;
  name: string;
}

declare global {
  interface Window {
    Razorpay?: any;
  }
}

type Pricing = {
  amount: number;
  currency: "INR" | "USD";
  displayAmount: string;
  country: string;
  orderId: string;
  keyId: string;
};

const isValidEmail = (v: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);

const HISTORY_STORAGE_KEY = "ux-lens.history.v1";
const MAX_HISTORY = 5;

const checkCookiesEnabled = (): boolean => {
  if (typeof document === "undefined") return false;
  if (typeof navigator !== "undefined" && navigator.cookieEnabled === false) return false;
  try {
    const probe = `__uxlens_cookie_probe_${Date.now()}`;
    document.cookie = `${probe}=1; path=/; SameSite=Lax`;
    const ok = document.cookie.includes(`${probe}=1`);
    if (ok) {
      // Clear probe.
      document.cookie = `${probe}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
    }
    return ok;
  } catch {
    return false;
  }
};

const loadHistoryFromStorage = (): Report[] => {
  if (typeof window === "undefined") return [];
  try {
    const raw = window.localStorage.getItem(HISTORY_STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    const revived: Report[] = parsed.map((r: any): Report => ({
      id: String(r.id || ""),
      type: r.type === "laws" ? "laws" : "heuristics",
      html: typeof r.html === "string" ? r.html : "",
      url: typeof r.url === "string" ? r.url : "",
      timestamp: r.timestamp ? new Date(r.timestamp) : new Date(),
    }));
    return revived.filter((r) => r.id && r.html).slice(0, MAX_HISTORY);
  } catch {
    return [];
  }
};

const saveHistoryToStorage = (reports: Report[]): void => {
  if (typeof window === "undefined") return;
  try {
    const trimmed = reports.slice(0, MAX_HISTORY);
    window.localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(trimmed));
  } catch (err) {
    console.warn("Could not save history to localStorage:", err);
  }
};

const isValidUrl = (v: string) => {
  try {
    const u = new URL(v);
    return u.protocol === "http:" || u.protocol === "https:";
  } catch {
    return false;
  }
};

const MAX_TOTAL_UPLOAD_BYTES = 10 * 1024 * 1024;
const MAX_PER_FILE_UPLOAD_BYTES = 5 * 1024 * 1024;
const MAX_CONTEXT_CHARS = 500;

const formatBytes = (n: number) => {
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
  return `${(n / (1024 * 1024)).toFixed(1)} MB`;
};

const loadRazorpayScript = (): Promise<boolean> =>
  new Promise((resolve) => {
    if (window.Razorpay) return resolve(true);
    const s = document.createElement("script");
    s.src = "https://checkout.razorpay.com/v1/checkout.js";
    s.onload = () => resolve(true);
    s.onerror = () => resolve(false);
    document.body.appendChild(s);
  });

// --- Main App Component ---

const App = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [url, setUrl] = useState("");
  const [context, setContext] = useState("");
  const [auditType, setAuditType] = useState<"heuristics" | "laws">("heuristics");
  const [assets, setAssets] = useState<Asset[]>([]);
  const [assetsError, setAssetsError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [loadingLogs, setLoadingLogs] = useState<string[]>([]);
  const [showDocumentation, setShowDocumentation] = useState(false);
  
  // History State
  const [reports, setReports] = useState<Report[]>([]);
  const [activeReportId, setActiveReportId] = useState<string | null>(null);

  // Cookies / localStorage availability gate. We persist history to
  // localStorage but treat cookie consent as the user-facing toggle.
  const [cookiesEnabled, setCookiesEnabled] = useState<boolean>(true);

  const [error, setError] = useState<string | null>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);

  // On mount: detect cookie support and load any persisted history.
  useEffect(() => {
    const ok = checkCookiesEnabled();
    setCookiesEnabled(ok);
    if (ok) {
      const persisted = loadHistoryFromStorage();
      if (persisted.length) {
        setReports(persisted);
        setActiveReportId(persisted[0].id);
      }
    }
  }, []);

  // Persist whenever reports change.
  useEffect(() => {
    if (!cookiesEnabled) return;
    saveHistoryToStorage(reports);
  }, [reports, cookiesEnabled]);

  // --- Loading Simulator Effect ---
  useEffect(() => {
    if (!loading) {
        setLoadingLogs([]);
        return;
    }

    const heuristicSteps = [
      "Initialising AI vision core...",
      "Processing assets. Normalising dimensions and colour...",
      "Building DOM tree representation...",
      "Checking Visibility of system status...",
      "Checking Match between system and real world...",
      "Checking User control and freedom...",
      "Checking Consistency and standards...",
      "Checking Error prevention...",
      "Checking Recognition vs recall...",
      "Checking Flexibility and efficiency...",
      "Checking Aesthetic and minimalist design...",
      "Checking Error handling...",
      "Checking Help and documentation...",
      "Synthesising violations into risk matrix...",
      "Building user journey maps...",
      "Compiling final HTML report..."
    ];

    const lawsSteps = [
      "Initialising AI vision core...",
      "Processing assets. Normalising dimensions and colour...",
      "Building DOM tree representation...",
      "Checking Jakob’s Law...",
      "Calculating Hick’s Law...",
      "Measuring Fitts’s Law...",
      "Analysing Miller’s Law...",
      "Reviewing Law of Proximity...",
      "Checking Law of Similarity...",
      "Evaluating Law of Common Region...",
      "Applying Von Restorff Effect...",
      "Assessing Aesthetic Usability Effect...",
      "Checking Peak End Rule...",
      "Synthesising violations into risk matrix...",
      "Building user journey maps...",
      "Compiling final HTML report..."
    ];

    const steps = auditType === 'heuristics' ? heuristicSteps : lawsSteps;
    
    // Initial State
    setLoadingLogs([steps[0]]);
    
    let currentStep = 0;

    const intervalId = setInterval(() => {
      currentStep++;
      if (currentStep < steps.length) {
        setLoadingLogs(prev => {
           // Keep the last 4 logs for the fading effect
           const newLogs = [...prev, steps[currentStep]];
           return newLogs.slice(-4); 
        });
      }
    }, 1500); // Advance step every 1.5 seconds

    return () => clearInterval(intervalId);
  }, [loading, auditType]);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files) return;
    const files = Array.from(e.target.files) as File[];

    // Validate file types before reading any of them. Only PDF, JPG, PNG.
    const ALLOWED_MIME = new Set(["image/jpeg", "image/jpg", "image/png", "application/pdf"]);
    const wrongType = files.find((f) => !ALLOWED_MIME.has(f.type));
    if (wrongType) {
      setAssetsError(
        `${wrongType.name || "Unsupported file"} is not allowed. Only PDF, JPG, and PNG are accepted.`
      );
      e.target.value = "";
      return;
    }

    // Validate per-file size before reading any of them.
    const oversized = files.find((f) => f.size > MAX_PER_FILE_UPLOAD_BYTES);
    if (oversized) {
      setAssetsError(
        `${oversized.name} is ${formatBytes(oversized.size)}. Each file must be ${formatBytes(MAX_PER_FILE_UPLOAD_BYTES)} or smaller.`
      );
      e.target.value = "";
      return;
    }

    // Validate combined size of (existing + new) before reading any of them.
    const existingTotal = assets.reduce((sum: number, a: Asset) => sum + a.file.size, 0);
    const incomingTotal = files.reduce((sum: number, f: File) => sum + f.size, 0);
    const projectedTotal = existingTotal + incomingTotal;
    if (projectedTotal > MAX_TOTAL_UPLOAD_BYTES) {
      setAssetsError(
        `Combined size would be ${formatBytes(projectedTotal)}. Total uploads must stay under ${formatBytes(MAX_TOTAL_UPLOAD_BYTES)}.`
      );
      e.target.value = "";
      return;
    }

    setAssetsError(null);
    const newAssets: Asset[] = [];
    for (const file of files) {
      const base64 = await fileToBase64(file);
      const preview = file.type.startsWith("image/") ? URL.createObjectURL(file) : "";

      newAssets.push({
        file,
        preview,
        base64: base64.split(",")[1], // Remove data URL prefix
        mimeType: file.type,
        name: file.name,
      });
    }
    setAssets((prev) => [...prev, ...newAssets]);
    // Reset the input so the user can re-pick the same file if they remove it.
    e.target.value = "";
  };

  const fileToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });
  };

  const removeAsset = (index: number) => {
    setAssets((prev: Asset[]) => prev.filter((_, i) => i !== index));
    setAssetsError(null);
  };

  const totalAssetBytes = assets.reduce((sum: number, a: Asset) => sum + a.file.size, 0);
  const sizeLimitsOk =
    totalAssetBytes <= MAX_TOTAL_UPLOAD_BYTES &&
    assets.every((a: Asset) => a.file.size <= MAX_PER_FILE_UPLOAD_BYTES);

  const generateReport = async () => {
    setError(null);

    const trimmedName = name.trim();
    const trimmedEmail = email.trim();
    const trimmedUrl = url.trim();

    if (trimmedName.length < 4) {
      setError("Name must be at least 4 characters.");
      return;
    }
    if (!isValidEmail(trimmedEmail)) {
      setError("Please enter a valid email address.");
      return;
    }
    if (!trimmedUrl && assets.length === 0) {
      setError("Please enter a website URL or upload at least one screenshot/file.");
      return;
    }
    if (trimmedUrl && !isValidUrl(trimmedUrl)) {
      setError("Please enter a valid URL (e.g. https://example.com).");
      return;
    }
    if (assets.length > 0 && !context.trim()) {
      setError("Additional context is required when files are uploaded.");
      return;
    }
    if (!sizeLimitsOk) {
      setError(
        `Uploads exceed limits (max ${formatBytes(MAX_PER_FILE_UPLOAD_BYTES)} per file, ${formatBytes(MAX_TOTAL_UPLOAD_BYTES)} total).`
      );
      return;
    }

    setLoading(true);

    let auditId = "";
    const reportCancelled = async (status: "cancelled" | "failed", errorMessage?: string) => {
      if (!auditId) return;
      try {
        await fetch("/api/cancel", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ auditId, status, errorMessage }),
        });
      } catch (e) {
        console.warn("Failed to record cancel/fail status:", e);
      }
    };

    try {
      // 1. Create Razorpay order — server validates inputs again, derives
      //    pricing from the trusted IP header, and inserts the initial DB row.
      const orderResp = await fetch("/api/order", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: trimmedName,
          email: trimmedEmail,
          auditType,
          url: trimmedUrl,
          context,
          assetFilenames: assets.map((a) => a.name),
        }),
      });
      if (!orderResp.ok) {
        let detail = "";
        try {
          const errBody = await orderResp.json();
          detail = errBody?.error || JSON.stringify(errBody);
        } catch {
          detail = (await orderResp.text().catch(() => "")) || "no response body";
        }
        console.error("/api/order failed:", orderResp.status, detail);
        throw new Error(`Could not create payment order (HTTP ${orderResp.status}): ${detail}`);
      }
      const order: Pricing & { auditId: string } = await orderResp.json();
      auditId = order.auditId;

      // 2. Load Razorpay checkout
      const ok = await loadRazorpayScript();
      if (!ok || !window.Razorpay) {
        await reportCancelled("failed", "Razorpay script failed to load.");
        throw new Error("Could not load Razorpay checkout. Please try again.");
      }

      // 3. Open checkout and wait for payment
      const payment = await new Promise<{
        razorpay_payment_id: string;
        razorpay_order_id: string;
        razorpay_signature: string;
      }>((resolve, reject) => {
        const rzp = new window.Razorpay({
          key: order.keyId,
          amount: order.amount,
          currency: order.currency,
          order_id: order.orderId,
          name: "TRD Studios",
          description: `UX Lens audit — ${order.displayAmount}`,
          prefill: { name: trimmedName, email: trimmedEmail },
          theme: { color: "#4338ca" },
          handler: (resp: any) => resolve(resp),
          modal: {
            ondismiss: () => reject(new Error("Payment was cancelled.")),
          },
        });
        rzp.on("payment.failed", (resp: any) =>
          reject(new Error(resp?.error?.description || "Payment failed."))
        );
        rzp.open();
      }).catch(async (err: Error) => {
        const isCancel = /cancel/i.test(err.message);
        await reportCancelled(isCancel ? "cancelled" : "failed", err.message);
        throw err;
      });

      // 4. Generate report with payment proof
      const today = new Date().toLocaleDateString("en-GB", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });

      const response = await fetch("/api/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          auditId,
          razorpayPaymentId: payment.razorpay_payment_id,
          razorpaySignature: payment.razorpay_signature,
          today,
          assets: assets.map((a: Asset) => ({
            mimeType: a.mimeType,
            base64: a.base64,
            name: a.name,
          })),
        }),
      });

      if (!response.ok) {
        const errBody = await response.json().catch(() => ({} as any));
        throw new Error(errBody?.error || `Request failed with status ${response.status}`);
      }

      const result = await response.json();
      const { html, warnings } = result || {};
      if (Array.isArray(warnings) && warnings.length) {
        console.warn("Post-generation warnings from /api/generate:", warnings);
      }

      const newReport: Report = {
        id: Date.now().toString(),
        type: auditType,
        html: html || "",
        url: trimmedUrl,
        timestamp: new Date(),
      };

      setReports((prev: Report[]) => [newReport, ...prev].slice(0, MAX_HISTORY));
      setActiveReportId(newReport.id);
    } catch (err: any) {
      console.error(err);
      setError(err.message || "Failed to generate report. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  const openPrintWindow = (html: string) => {
    const printWindow = window.open('', '_blank');
    if (printWindow) {
      printWindow.document.write(html);
      printWindow.document.close();
      setTimeout(() => {
        printWindow.print();
      }, 500);
    }
  };

  const downloadHtml = (html: string) => {
    const blob = new Blob([html], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `UX_Lens_Report_${new Date().toISOString().slice(0, 10)}.html`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const activeReport = reports.find(r => r.id === activeReportId);

  return (
    <div className="min-h-screen text-slate-800 font-sans selection:bg-indigo-100 selection:text-indigo-900 flex flex-col" style={{
      background: APP_GRADIENT
    }}>
      
      {/* Documentation Modal */}
      {showDocumentation && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm animate-in fade-in duration-200">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-5xl max-h-[90vh] overflow-hidden flex flex-col">
            {/* Modal Header */}
            <div className="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
               <div className="flex items-center space-x-3">
                  <div className="bg-indigo-600 rounded-lg p-2 text-white">
                    <LensIcon />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-slate-900 leading-tight">UX Lens Documentation</h2>
                    <p className="text-slate-500 text-sm font-medium">Made by TRD Studios</p>
                  </div>
               </div>
               <button 
                  onClick={() => setShowDocumentation(false)}
                  className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors"
                >
                  <XIcon />
                </button>
            </div>
            
            {/* Modal Scrollable Content */}
            <div className="p-8 space-y-10 overflow-y-auto custom-scrollbar flex-1 bg-white">
              
              {/* Introduction */}
              <section className="prose prose-slate max-w-none">
                <p className="text-lg text-slate-600 leading-relaxed">
                  UX Lens is an automated audit tool. It acts as a research partner for product teams. It combines vision analysis with industry standards like Nielsen’s Heuristics and UX Laws. It identifies friction points in designs systematically. The tool turns static files and URLs into strategic reports. This saves time between discovery and fixing issues.
                </p>
              </section>

              {/* System Workflow Visualization */}
              <section>
                <h3 className="text-lg font-bold text-slate-900 mb-6 flex items-center">
                   <div className="w-8 h-8 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center text-sm font-bold mr-3">1</div>
                   System Workflow
                </h3>
                
                <div className="relative">
                   {/* Connecting Line */}
                   <div className="absolute top-1/2 left-0 w-full h-1 bg-slate-100 -translate-y-1/2 hidden md:block z-0"></div>
                   
                   <div className="grid grid-cols-1 md:grid-cols-4 gap-6 relative z-10">
                      {/* Step 1: Input */}
                      <div className="bg-white border border-slate-200 p-5 rounded-xl shadow-sm flex flex-col items-center text-center group hover:border-indigo-300 transition-colors h-full justify-center">
                         <div className="w-12 h-12 bg-white border-2 border-indigo-100 text-indigo-600 rounded-full flex items-center justify-center mb-3 text-xl font-bold group-hover:bg-indigo-50 group-hover:border-indigo-200 transition-colors shadow-sm">
                           📂
                         </div>
                         <h4 className="font-bold text-slate-900 mb-1">Input Data</h4>
                         <p className="text-xs text-slate-500 leading-relaxed">The system takes URLs, static images, and context. It prepares this data for analysis.</p>
                      </div>

                      {/* Step 2: Vision AI */}
                      <div className="bg-white border border-slate-200 p-5 rounded-xl shadow-sm flex flex-col items-center text-center group hover:border-purple-300 transition-colors h-full justify-center">
                         <div className="w-12 h-12 bg-white border-2 border-purple-100 text-purple-600 rounded-full flex items-center justify-center mb-3 text-xl font-bold group-hover:bg-purple-50 group-hover:border-purple-200 transition-colors shadow-sm">
                           🧠
                         </div>
                         <h4 className="font-bold text-slate-900 mb-1">Vision AI</h4>
                         <p className="text-xs text-slate-500 leading-relaxed">Gemini Vision simulates eye-tracking. It scans the layout for visual hierarchy.</p>
                      </div>

                      {/* Step 3: Logic Layer (Split) */}
                      <div className="flex flex-col gap-3 h-full justify-center">
                         <div className="bg-white border border-slate-200 p-3 rounded-xl shadow-sm flex items-center space-x-3 group hover:border-blue-300 transition-colors">
                            <div className="w-8 h-8 bg-blue-50 text-blue-600 rounded-full flex flex-none items-center justify-center text-sm font-bold">H</div>
                            <div className="text-left">
                               <h4 className="font-bold text-slate-900 text-sm">UX Heuristics</h4>
                               <p className="text-[10px] text-slate-500 leading-tight">Checks Nielsen's 10 Principles.</p>
                            </div>
                         </div>
                         <div className="bg-white border border-slate-200 p-3 rounded-xl shadow-sm flex items-center space-x-3 group hover:border-blue-300 transition-colors">
                            <div className="w-8 h-8 bg-blue-50 text-blue-600 rounded-full flex flex-none items-center justify-center text-sm font-bold">L</div>
                            <div className="text-left">
                               <h4 className="font-bold text-slate-900 text-sm">Laws of UX</h4>
                               <p className="text-[10px] text-slate-500 leading-tight">Checks Gestalt laws.</p>
                            </div>
                         </div>
                      </div>

                      {/* Step 4: Output */}
                      <div className="bg-white border border-slate-200 p-5 rounded-xl shadow-sm flex flex-col items-center text-center group hover:border-green-300 transition-colors h-full justify-center">
                         <div className="w-12 h-12 bg-white border-2 border-green-100 text-green-600 rounded-full flex items-center justify-center mb-3 text-xl font-bold group-hover:bg-green-50 group-hover:border-green-200 transition-colors shadow-sm">
                           📊
                         </div>
                         <h4 className="font-bold text-slate-900 mb-1">Strategic Output</h4>
                         <p className="text-xs text-slate-500 leading-relaxed">It generates an HTML report. This includes charts and prioritised issues.</p>
                      </div>
                   </div>
                </div>
              </section>

              {/* Data Types */}
              <section>
                 <h3 className="text-lg font-bold text-slate-900 mb-4 flex items-center">
                    <div className="w-8 h-8 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center text-sm font-bold mr-3">2</div>
                    Multi-modal Inputs
                </h3>
                <div className="grid md:grid-cols-3 gap-4">
                   <div className="bg-slate-50 rounded-lg p-5 border border-slate-100">
                      <div className="font-bold text-slate-800 text-sm mb-2 flex items-center"><span className="mr-2">🔗</span> URL and Context</div>
                      <p className="text-xs text-slate-500 leading-relaxed">
                        The URL provides domain knowledge. Context helps calibrate the score for specific users.
                      </p>
                   </div>
                   <div className="bg-slate-50 rounded-lg p-5 border border-slate-100">
                      <div className="font-bold text-slate-800 text-sm mb-2 flex items-center"><span className="mr-2">🖼️</span> Visual Assets</div>
                      <p className="text-xs text-slate-500 leading-relaxed">
                        Upload <strong>Screenshots</strong>, <strong>PDFs</strong>, or <strong>HTML</strong> files. The model identifies contrast issues and visual clutter.
                      </p>
                   </div>
                   <div className="bg-slate-50 rounded-lg p-5 border border-slate-100">
                      <div className="font-bold text-slate-800 text-sm mb-2 flex items-center"><span className="mr-2">📈</span> Actionable Output</div>
                      <p className="text-xs text-slate-500 leading-relaxed">
                        The report gives code-ready advice. It separates critical blockers from cosmetic fixes.
                      </p>
                   </div>
                </div>
              </section>
            </div>
            
            {/* Modal Footer */}
            <div className="p-6 border-t border-slate-100 bg-slate-50 flex flex-col sm:flex-row justify-between items-center gap-4">
               <a
                href="https://thereformdesign.com"
                target="_blank"
                rel="noopener noreferrer"
                aria-label="TRD Studios"
                className="flex items-center transition-opacity hover:opacity-80 px-2 py-2"
              >
                <BrandLogo className="h-8 w-auto" />
              </a>

              <button 
                onClick={() => setShowDocumentation(false)}
                className="bg-slate-900 text-white px-6 py-2.5 rounded-lg font-medium hover:bg-slate-800 transition-colors shadow-sm w-full sm:w-auto"
              >
                Close Documentation
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Header */}
      <header className="bg-white/80 backdrop-blur-md border-b border-white/40 sticky top-0 z-10 flex-none">
        <div className="w-full px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <div className="bg-indigo-600 rounded-xl p-2 text-white shadow-lg shadow-indigo-200">
              <LensIcon />
            </div>
            <div>
              <h1 className="text-xl font-bold text-slate-900 tracking-tight leading-none">UX Lens</h1>
              <p className="text-[10px] font-semibold text-slate-500 uppercase tracking-wider">Intelligent Website Audit Platform</p>
            </div>
          </div>
          <button 
            onClick={() => setShowDocumentation(true)}
            className="text-sm font-medium text-slate-600 hover:text-indigo-600 transition-colors flex items-center space-x-1"
          >
            <InfoIcon />
            <span>Documentation</span>
          </button>
        </div>
      </header>

      <main className="w-full px-4 sm:px-6 lg:px-8 py-6 flex-grow flex flex-col">
        <div className="flex-1 grid grid-cols-1 lg:grid-cols-[400px_1fr] gap-6 items-stretch">
          
          {/* Left Column: Inputs */}
          <div className="space-y-6 w-full">
            
            {/* Context Card */}
            <div className="bg-white rounded-2xl shadow-xl shadow-slate-200/50 border border-white/50 overflow-hidden backdrop-blur-sm">
              <div className="p-5 border-b border-slate-100 bg-slate-50/50">
                <h3 className="font-semibold text-slate-900">Audit Configuration</h3>
                <p className="text-xs text-slate-500 mt-1">Setup your analysis parameters</p>
              </div>
              
              <div className="p-5 space-y-5">
                {/* Method Selection */}
                <div className="grid grid-cols-2 gap-3">
                  <button
                    onClick={() => setAuditType("heuristics")}
                    disabled={loading}
                    className={`p-3 rounded-lg border text-sm font-medium transition-all ${
                      auditType === "heuristics"
                        ? "border-indigo-600 bg-indigo-50 text-indigo-700 ring-1 ring-indigo-600 shadow-sm"
                        : "border-slate-200 hover:border-slate-300 text-slate-600 hover:bg-slate-50 bg-white"
                    } ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
                  >
                    Nielsen's Heuristics
                  </button>
                  <button
                    onClick={() => setAuditType("laws")}
                    disabled={loading}
                    className={`p-3 rounded-lg border text-sm font-medium transition-all ${
                      auditType === "laws"
                        ? "border-indigo-600 bg-indigo-50 text-indigo-700 ring-1 ring-indigo-600 shadow-sm"
                        : "border-slate-200 hover:border-slate-300 text-slate-600 hover:bg-slate-50 bg-white"
                    } ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
                  >
                    Laws of UX
                  </button>
                </div>

                {/* Name and Email */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      Your Name <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      placeholder="Name"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      disabled={loading}
                      aria-invalid={name.length > 0 && name.trim().length < 4}
                      className={`w-full px-3 py-2 border rounded-lg focus:ring-2 outline-none transition-all disabled:opacity-50 disabled:bg-slate-100 bg-white ${
                        name.length > 0 && name.trim().length < 4
                          ? "border-red-400 focus:ring-red-300 focus:border-red-500"
                          : "border-slate-300 focus:ring-indigo-500 focus:border-indigo-500"
                      }`}
                    />
                    {name.length > 0 && name.trim().length < 4 && (
                      <p className="text-xs text-red-500 mt-1">Name must be at least 4 characters.</p>
                    )}
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      Email <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="email"
                      placeholder="you@company.com"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      disabled={loading}
                      aria-invalid={email.length > 0 && !isValidEmail(email)}
                      className={`w-full px-3 py-2 border rounded-lg focus:ring-2 outline-none transition-all disabled:opacity-50 disabled:bg-slate-100 bg-white ${
                        email.length > 0 && !isValidEmail(email)
                          ? "border-red-400 focus:ring-red-300 focus:border-red-500"
                          : "border-slate-300 focus:ring-indigo-500 focus:border-indigo-500"
                      }`}
                    />
                    {email.length > 0 && !isValidEmail(email) && (
                      <p className="text-xs text-red-500 mt-1">Please enter a valid email address.</p>
                    )}
                  </div>
                </div>

                {/* URL Input */}
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    Website URL
                  </label>
                  <input
                    type="url"
                    placeholder="https://example.com"
                    value={url}
                    onChange={(e) => setUrl(e.target.value)}
                    disabled={loading}
                    aria-invalid={url.length > 0 && !isValidUrl(url.trim())}
                    className={`w-full px-3 py-2 border rounded-lg focus:ring-2 outline-none transition-all disabled:opacity-50 disabled:bg-slate-100 bg-white ${
                      url.length > 0 && !isValidUrl(url.trim())
                        ? "border-red-400 focus:ring-red-300 focus:border-red-500"
                        : "border-slate-300 focus:ring-indigo-500 focus:border-indigo-500"
                    }`}
                  />
                  {url.length > 0 && !isValidUrl(url.trim()) ? (
                    <p className="text-xs text-red-500 mt-1">
                      Please enter a valid URL starting with http:// or https://.
                    </p>
                  ) : (
                    <p className="text-[11px] text-slate-500 mt-1">
                      Provide a URL <span className="font-medium">or</span> upload screenshots/files below.
                    </p>
                  )}
                </div>

                {/* Context Input */}
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    Additional Context{" "}
                    {assets.length > 0 ? (
                      <span className="text-red-500">*</span>
                    ) : (
                      <span className="text-slate-400 font-normal">(Optional)</span>
                    )}
                  </label>
                  <textarea
                    rows={4}
                    maxLength={MAX_CONTEXT_CHARS}
                    placeholder={
                      assets.length > 0
                        ? "Required when files are uploaded — describe the product, target audience, and primary goals so the model knows what to look at."
                        : "Describe the company, target audience, and primary goals..."
                    }
                    value={context}
                    onChange={(e) => setContext(e.target.value.slice(0, MAX_CONTEXT_CHARS))}
                    disabled={loading}
                    aria-invalid={assets.length > 0 && !context.trim()}
                    className={`w-full px-3 py-2 border rounded-lg focus:ring-2 outline-none transition-all resize-none text-sm disabled:opacity-50 disabled:bg-slate-100 bg-white ${
                      assets.length > 0 && !context.trim()
                        ? "border-red-400 focus:ring-red-300 focus:border-red-500"
                        : "border-slate-300 focus:ring-indigo-500 focus:border-indigo-500"
                    }`}
                  />
                  <div className="flex items-center justify-between mt-1">
                    <p className={`text-xs ${assets.length > 0 && !context.trim() ? "text-red-500" : "text-transparent"}`}>
                      Additional context is required when files are uploaded.
                    </p>
                    <p className={`text-xs ${context.length >= MAX_CONTEXT_CHARS ? "text-red-500 font-medium" : "text-slate-400"}`}>
                      {context.length} / {MAX_CONTEXT_CHARS}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {/* Assets Card */}
            <div className="bg-white rounded-2xl shadow-xl shadow-slate-200/50 border border-white/50 overflow-hidden backdrop-blur-sm">
               <div className="p-5 border-b border-slate-100 bg-slate-50/50 flex justify-between items-center">
                <div>
                  <h3 className="font-semibold text-slate-900">
                    Screenshots and Files <span className="text-slate-400 font-normal text-sm">(Optional)</span>
                  </h3>
                  <p className="text-xs text-slate-500 mt-1">
                    PDF, JPG or PNG only — max {formatBytes(MAX_PER_FILE_UPLOAD_BYTES)} per file, {formatBytes(MAX_TOTAL_UPLOAD_BYTES)} total.
                  </p>
                  {assets.length > 0 && (
                    <p className={`text-xs mt-1 ${totalAssetBytes > MAX_TOTAL_UPLOAD_BYTES ? "text-red-500 font-medium" : "text-slate-500"}`}>
                      Used: {formatBytes(totalAssetBytes)} of {formatBytes(MAX_TOTAL_UPLOAD_BYTES)}
                    </p>
                  )}
                </div>
                <button 
                  onClick={() => !loading && fileInputRef.current?.click()}
                  disabled={loading}
                  className={`text-xs bg-white border border-slate-200 hover:border-indigo-300 hover:text-indigo-600 px-3 py-1.5 rounded-md font-medium transition-all ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
                >
                  Add Files
                </button>
              </div>

              <div className="p-5">
                <input
                  type="file"
                  multiple
                  accept="image/jpeg,image/png,application/pdf,.jpg,.jpeg,.png,.pdf"
                  ref={fileInputRef}
                  onChange={handleFileChange}
                  className="hidden"
                />

                {assetsError && (
                  <div className="mb-3 px-3 py-2 bg-red-50 border border-red-200 rounded-md text-xs text-red-600">
                    {assetsError}
                  </div>
                )}

                {assets.length === 0 ? (
                  <div 
                    onClick={() => !loading && fileInputRef.current?.click()}
                    className={`border-2 border-dashed border-slate-200 rounded-xl p-8 flex flex-col items-center justify-center text-center hover:bg-slate-50 hover:border-indigo-300 transition-all cursor-pointer group bg-slate-50/50 ${loading ? 'opacity-50 cursor-not-allowed pointer-events-none' : ''}`}
                  >
                    <div className="w-10 h-10 bg-indigo-50 text-indigo-500 rounded-full flex items-center justify-center mb-3 group-hover:scale-110 transition-transform shadow-sm">
                      <UploadIcon />
                    </div>
                    <p className="text-sm font-medium text-slate-700">Click to upload assets</p>
                    <p className="text-xs text-slate-400 mt-1">JPG, PNG, PDF, HTML supported</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    <div className="grid grid-cols-2 gap-3 max-h-64 overflow-y-auto pr-1 scrollbar-thin">
                      {assets.map((asset, idx) => (
                        <div key={idx} className="relative group rounded-lg overflow-hidden border border-slate-200 shadow-sm bg-slate-50 h-24 flex items-center justify-center">
                          {asset.mimeType.startsWith('image/') ? (
                             <img src={asset.preview} alt="preview" className="w-full h-full object-cover" />
                          ) : asset.mimeType === 'application/pdf' ? (
                             <div className="flex flex-col items-center text-red-500">
                                <PdfIcon />
                                <span className="text-[10px] font-medium mt-1 text-slate-600 truncate max-w-[80px]">{asset.file.name}</span>
                             </div>
                          ) : (
                             <div className="flex flex-col items-center text-orange-500">
                                <HtmlIcon />
                                <span className="text-[10px] font-medium mt-1 text-slate-600 truncate max-w-[80px]">{asset.file.name}</span>
                             </div>
                          )}
                          
                          <button
                            onClick={() => !loading && removeAsset(idx)}
                            disabled={loading}
                            className={`absolute top-1 right-1 bg-white hover:bg-red-50 text-slate-600 hover:text-red-600 p-1.5 rounded-full opacity-0 group-hover:opacity-100 transition-all shadow-md ${loading ? 'hidden' : ''}`}
                          >
                            <XIcon />
                          </button>
                        </div>
                      ))}
                    </div>
                    <div 
                      onClick={() => !loading && fileInputRef.current?.click()}
                      className={`text-center text-sm text-indigo-600 font-medium cursor-pointer hover:underline py-2 ${loading ? 'opacity-50 pointer-events-none' : ''}`}
                    >
                      + Add more assets
                    </div>
                  </div>
                )}
              </div>
            </div>

            <button
              onClick={generateReport}
              disabled={
                loading ||
                !cookiesEnabled ||
                name.trim().length < 4 ||
                !isValidEmail(email) ||
                (url.trim() !== "" && !isValidUrl(url.trim())) ||
                (!url.trim() && assets.length === 0) ||
                (assets.length > 0 && !context.trim()) ||
                !sizeLimitsOk
              }
              title={!cookiesEnabled ? "Enable cookies to proceed" : undefined}
              className={`w-full py-4 rounded-xl flex items-center justify-center space-x-2 font-semibold text-white transition-all shadow-lg hover:shadow-xl shadow-indigo-500/30 transform active:scale-[0.98] ${
                loading ||
                !cookiesEnabled ||
                name.trim().length < 4 ||
                !isValidEmail(email) ||
                (url.trim() !== "" && !isValidUrl(url.trim())) ||
                (!url.trim() && assets.length === 0) ||
                (assets.length > 0 && !context.trim()) ||
                !sizeLimitsOk
                  ? "bg-slate-400 cursor-not-allowed shadow-none"
                  : "bg-indigo-600 hover:bg-indigo-700"
              }`}
            >
              {loading ? (
                <>
                  <LoaderIcon />
                  <span>Generating audit...</span>
                </>
              ) : (
                <span>Generate Report</span>
              )}
            </button>
            {!cookiesEnabled && (
              <div className="mt-3 px-3 py-2 bg-amber-50 border border-amber-200 rounded-md text-xs text-amber-700 flex items-start gap-2">
                <span aria-hidden="true">⚠️</span>
                <span>
                  Cookies are disabled in your browser. Enable cookies for this site to proceed
                  &mdash; we use them to keep your last {MAX_HISTORY} reports available between visits.
                </span>
              </div>
            )}
          </div>

          {/* Right Column: Report */}
          <div className="flex flex-col w-full min-h-[calc(100vh-9rem)]">
            
            {/* Report Tabs - History System */}
            {reports.length > 0 && (
              <div className="mb-4">
                <div className="flex items-baseline justify-between mb-2 ml-1">
                  <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                    Report History
                  </div>
                  <div className="text-[10px] text-slate-400">
                    Showing {reports.length} of {MAX_HISTORY} max — older reports are dropped automatically
                  </div>
                </div>
                <div className="flex space-x-2 overflow-x-auto pb-2 custom-scrollbar">
                  {reports.map((r) => (
                    <button
                      key={r.id}
                      onClick={() => setActiveReportId(r.id)}
                      className={`flex flex-col items-start px-4 py-2 rounded-lg text-sm transition-all whitespace-nowrap border min-w-[140px] text-left ${
                        activeReportId === r.id
                          ? "bg-white border-white/50 text-indigo-700 shadow-lg shadow-indigo-100 ring-1 ring-indigo-500/20"
                          : "bg-white/40 border-transparent text-slate-600 hover:bg-white/60"
                      }`}
                    >
                      <div className="flex items-center space-x-2 mb-1 w-full">
                         <span className={`w-2 h-2 rounded-full ${r.type === 'heuristics' ? 'bg-indigo-500' : 'bg-purple-500'}`}></span>
                         <span className="font-bold text-xs uppercase opacity-80">{r.type === 'heuristics' ? 'Heuristics' : 'Laws of UX'}</span>
                      </div>
                      <div className="font-medium truncate w-full mb-0.5" title={r.url}>{r.url.replace("https://", "").replace("www.", "")}</div>
                      <div className="text-[10px] opacity-60">
                        {r.timestamp.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})} • {r.timestamp.toLocaleDateString([], { month: 'short', day: 'numeric' })}
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div className="bg-white rounded-2xl shadow-xl shadow-slate-200/50 border border-white/50 flex-1 flex flex-col relative overflow-hidden backdrop-blur-sm">
              
              {!activeReport && !loading && !error && (
                <div className="flex-1 flex flex-col items-center justify-center text-center p-12 opacity-60">
                  <div className="w-24 h-24 bg-slate-50 rounded-full flex items-center justify-center mb-6 shadow-inner">
                    <FileImageIcon />
                  </div>
                  <h3 className="text-xl font-semibold text-slate-900 mb-2">Ready to Audit</h3>
                  <p className="text-slate-500 max-w-sm">
                    Upload screenshots, PDFs or HTML files to start generating your professional UX report.
                  </p>
                </div>
              )}

              {loading && (
                <div className="flex-1 flex flex-col items-center justify-center p-12 bg-white/80 backdrop-blur z-20 absolute inset-0">
                   <div className="animate-spin text-indigo-600 mb-6 drop-shadow-md">
                     <svg className="w-12 h-12" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                     </svg>
                   </div>
                   <h3 className="text-lg font-semibold text-slate-800 animate-pulse mb-4">Analysing Interface...</h3>
                   
                   {/* Increased height from h-32 to h-48 and added padding-bottom to fix cropping */}
                   <div className="flex flex-col items-center space-y-2 w-full max-w-md h-48 overflow-hidden relative pb-2">
                      {/* Gradient Mask for fading out top items */}
                      <div className="absolute top-0 left-0 right-0 h-10 bg-gradient-to-b from-white to-transparent z-10 pointer-events-none"></div>

                      {loadingLogs.map((log, index) => {
                         // Calculate opacity: newest (last item) is 1, others fade out
                         const isLast = index === loadingLogs.length - 1;
                         const opacityClass = isLast 
                            ? "opacity-100 font-medium text-indigo-700 transform scale-105" 
                            : index === loadingLogs.length - 2 
                               ? "opacity-60 text-slate-600" 
                               : "opacity-30 text-slate-400 blur-[0.5px]";
                         
                         return (
                            <p key={index} className={`text-sm text-center transition-all duration-500 ease-in-out px-4 ${opacityClass}`}>
                               {log}
                            </p>
                         );
                      })}
                   </div>

                   <div className="mt-8 space-y-3 w-64">
                     <div className="h-1.5 bg-slate-100 rounded-full overflow-hidden">
                       <div className="h-full bg-indigo-500 w-2/3 animate-[shimmer_1.5s_infinite]"></div>
                     </div>
                     <div className="h-1.5 bg-slate-100 rounded-full overflow-hidden">
                       <div className="h-full bg-indigo-300 w-1/2 animate-[shimmer_1.5s_infinite_200ms]"></div>
                     </div>
                   </div>
                </div>
              )}

              {error && (
                <div className="flex-1 flex flex-col items-center justify-center p-12 text-center">
                  <div className="w-16 h-16 bg-red-50 text-red-500 rounded-full flex items-center justify-center mb-4 shadow-sm">
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="13"/><circle cx="12" cy="17" r="0.5" fill="currentColor"/></svg>
                  </div>
                  <h3 className="text-lg font-semibold text-slate-900">Analysis Failed</h3>
                  <p className="text-slate-500 mt-1 mb-6 max-w-sm">{error}</p>
                  <button onClick={generateReport} className="text-indigo-600 font-medium hover:underline">Try Again</button>
                </div>
              )}

              {activeReport && (
                <div className="flex flex-col h-full">
                   {/* Report Actions Toolbar */}
                   <div className="bg-slate-50/80 backdrop-blur border-b border-slate-200 px-4 py-3 flex items-center justify-between">
                      <div className="flex items-center space-x-2">
                         <div className="bg-green-100 text-green-700 px-2 py-0.5 rounded text-xs font-bold uppercase tracking-wide">
                           {activeReport.type === 'heuristics' ? "Nielsen's Audit" : "Laws Audit"}
                         </div>
                         <span className="text-xs text-slate-500 truncate max-w-[200px] font-medium">
                            {activeReport.url}
                         </span>
                      </div>
                      <div className="flex items-center space-x-3">
                         <button 
                            onClick={() => openPrintWindow(activeReport.html)}
                            className="flex items-center space-x-1.5 text-slate-600 hover:text-indigo-600 text-sm font-medium transition-colors bg-white px-3 py-1.5 rounded border border-slate-200 shadow-sm hover:shadow"
                         >
                            <PrintIcon />
                            <span>Print</span>
                         </button>
                         <button 
                            onClick={() => downloadHtml(activeReport.html)}
                            className="flex items-center space-x-1.5 text-white hover:bg-indigo-700 bg-indigo-600 text-sm font-medium transition-colors px-3 py-1.5 rounded shadow-sm hover:shadow"
                         >
                            <DownloadIcon />
                            <span>Download</span>
                         </button>
                      </div>
                   </div>
                   
                   {/* Iframe Container */}
                   <div className="flex-1 bg-white relative">
                      <iframe 
                        srcDoc={activeReport.html}
                        className="w-full h-full border-0 absolute inset-0"
                        title={`UX Audit Report - ${activeReport.id}`}
                        sandbox="allow-same-origin allow-scripts allow-popups"
                      />
                   </div>
                </div>
              )}

            </div>
          </div>
        </div>
      </main>

      {/* Global Footer */}
      <footer className="mt-auto border-t border-white/20 bg-white/30 backdrop-blur-md">
         <div className="w-full px-4 sm:px-6 lg:px-8 py-8 flex flex-col md:flex-row items-center justify-between gap-4">
             <div className="text-center md:text-left">
                <a
                  href="https://thereformdesign.com"
                  target="_blank"
                  rel="noopener noreferrer"
                  aria-label="TRD Studios"
                  className="inline-block hover:opacity-80 transition-opacity"
                >
                  <BrandLogo className="h-9 w-auto" />
                </a>
             </div>
             
             <div className="text-center md:text-right max-w-md">
                 <p className="text-[11px] text-slate-600 leading-tight mb-1">
                   Need help? Email{" "}
                   <a href="mailto:hello@thereformdesign.com" className="text-indigo-600 hover:text-indigo-800 hover:underline font-medium">
                     hello@thereformdesign.com
                   </a>
                 </p>
                 <p className="text-[10px] text-slate-500 leading-tight">
                   Disclaimer: This AI tool serves as a starting point for analysis. While powerful, it can make mistakes. Always verify findings with professional human judgment and user testing.
                 </p>
             </div>
         </div>
      </footer>
    </div>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(<App />);