/**
 * SERP Preview Component
 *
 * Shows a preview of how the page will appear in search results.
 *
 * @package
 */

import { __ } from '@wordpress/i18n';

const getUrlPreview = (url = '') => {
  try {
    const parsed = new URL(url || `${window.location.origin}/sample-page`, window.location.origin);
    const domain = (parsed.hostname || window.location.hostname || '').toLowerCase();
    const breadcrumb = parsed.pathname
      .split('/')
      .map((segment) => decodeURIComponent(segment).trim().toLowerCase())
      .filter(Boolean)
      .join(' › ');

    return { domain, breadcrumb };
  } catch (error) {
    return {
      domain: window.location.hostname.toLowerCase(),
      breadcrumb: '',
    };
  }
};

const SERPPreview = ({ title, url, description }) => {
  // Truncate title if too long
  const displayTitle =
    title && title.length > 60
      ? title.substring(0, 57) + '…'
      : title || __('Page Title', 'prorank-seo');

  // Truncate description if too long
  const displayDescription =
    description && description.length > 160
      ? description.substring(0, 157) + '…'
      : description ||
        __(
          'This is a preview of how your page will appear in search results. Add a meta description to control this text.',
          'prorank-seo'
        );

  // Format URL for display
  const displayUrl = url || `${window.location.origin}/sample-page`;
  const { domain, breadcrumb } = getUrlPreview(displayUrl);

  return (
    <div
      className="prorank-serp-preview"
      role="region"
      aria-label={__('Search result preview', 'prorank-seo')}
    >
      <div className="prorank-serp-preview__inner">
        {/* Favicon placeholder */}
        <div className="prorank-serp-preview__favicon">
          <span className="dashicons dashicons-admin-site"></span>
        </div>

        <div className="prorank-serp-preview__content">
          {/* Site name */}
          <div className="prorank-serp-preview__site">{domain}</div>

          {/* Breadcrumb */}
          {breadcrumb && <div className="prorank-serp-preview__breadcrumb">{breadcrumb}</div>}

          {/* Title */}
          <h3 className="prorank-serp-preview__title">{displayTitle}</h3>

          {/* Description */}
          <div className="prorank-serp-preview__description">{displayDescription}</div>
        </div>
      </div>
    </div>
  );
};

export default SERPPreview;
