"use client";

import { Globe } from "lucide-react";

interface SerpPreviewProps {
  title: string;
  description: string;
  url: string;
}

export function SerpPreview({ title, description, url }: SerpPreviewProps) {
  const formatUrl = (fullUrl: string) => {
    try {
      let formattedUrl = fullUrl;
      if (!/^https?:\/\//i.test(fullUrl)) {
        formattedUrl = `https://${fullUrl}`;
      }
      const urlObject = new URL(formattedUrl);
      const path = urlObject.pathname === "/" ? "" : urlObject.pathname;
      // remove trailing slash
      const displayPath = path.endsWith('/') ? path.slice(0, -1) : path;
      return `${urlObject.hostname}${displayPath}`;
    } catch (error) {
      return fullUrl;
    }
  };

  const displayUrl = formatUrl(url);

  return (
    <div className="p-4 border rounded-lg bg-muted/50 w-full font-sans">
      <div className="flex items-center gap-2">
        <div className="w-7 h-7 bg-background rounded-full flex items-center justify-center border">
          <Globe className="w-4 h-4 text-muted-foreground" />
        </div>
        <div>
          <p className="text-sm text-foreground font-medium -mb-0.5">
            {displayUrl.split("/")[0]}
          </p>
          <p className="text-xs text-muted-foreground">{displayUrl}</p>
        </div>
      </div>
      <h3 className="text-xl text-blue-600 dark:text-blue-400 mt-2 truncate font-medium">
        {title || "Meta Title Preview"}
      </h3>
      <p className="text-sm text-muted-foreground mt-1 line-clamp-2">
        {description ||
          "This is where the meta description will be displayed. It provides a brief summary of the page's content for search engine users."}
      </p>
    </div>
  );
}