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

import { __ } from '@wordpress/i18n';
import { resolveVariables, resolveVariableSegments } from '../dynamicVariables';

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, variableContext = {} }) => {
  // Resolve %variables% so they never render as literal tokens.
  const resolvedTitle = resolveVariables(title || '', variableContext);
  const resolvedDescription = resolveVariables(description || '', variableContext);

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

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

  // Render server-only variables muted (bare name) instead of as literal text.
  // Falls back to the plain truncated string when truncation applied.
  const renderWithMutedVariables = (raw, resolved, truncated) => {
    if (!resolved || truncated !== resolved) {
      return truncated;
    }

    return resolveVariableSegments(raw || '', variableContext).map((segment, index) =>
      segment.unknown ? (
        <span
          key={index}
          className="prorank-serp-preview__variable"
          style={{ color: '#9ca3af' }}
        >
          {segment.value}
        </span>
      ) : (
        segment.value
      )
    );
  };

  // 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">
            {renderWithMutedVariables(title, resolvedTitle, displayTitle)}
          </h3>

          {/* Description */}
          <div className="prorank-serp-preview__description">
            {renderWithMutedVariables(description, resolvedDescription, displayDescription)}
          </div>
        </div>
      </div>
    </div>
  );
};

export default SERPPreview;
