/**
 * Font Delivery Health — read-only visibility panel (free build).
 *
 * Uses the free ui-kit <Card> + Tailwind pr: utilities so it is visually
 * native to the free Asset Optimisation page. Same read-only data contract as
 * premium: GET /prorank-seo/v1/font-optimization/health (which reuses the
 * existing FontOptimizationModule::get_stats() — single source of truth). No
 * toggles, no mutation; preload suggestions are advisory only.
 */

import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Alert, Button, Card } from '../../../components/ui';
import * as React from 'react';

interface HealthFlag {
  code: string;
  severity: 'critical' | 'high' | 'medium' | 'low';
  message: string;
  recommendation: string;
}

interface FontHealth {
  status?: string;
  settings?: {
    host_google_fonts_locally?: boolean;
    font_display_swap?: boolean;
    font_subsetting_enabled?: boolean;
    smart_fonts_enabled?: boolean;
    font_preload_enabled?: boolean;
    font_preload_url_count?: number;
  };
  cache?: {
    cached_font_files?: number;
    cached_bytes?: number;
    cached_human?: string;
    google_fonts_found_by_scanner?: number;
  };
  rendered?: {
    fetched?: boolean;
    external_google_fonts?: boolean;
    external_google_count?: number;
    prorank_local_served?: boolean;
    self_hosted_owner?: string;
    font_display_swap_seen?: number;
    preloaded_fonts?: string[];
    preload_suggestions?: string[];
  };
  flags?: HealthFlag[];
}

interface HealthResponse {
  success: boolean;
  health: FontHealth;
}

const yesNo = (v: boolean | undefined): string =>
  v ? __('Yes', 'prorank-seo') : __('No', 'prorank-seo');

const FontDeliveryHealthPanel: React.FC = () => {
  const [health, setHealth] = useState<FontHealth | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const r = await apiFetch<HealthResponse>({
        path: '/prorank-seo/v1/font-optimization/health',
      });
      if (r?.success && r.health) {
        setHealth(r.health);
      } else {
        setError(__('Unexpected response from the font health endpoint.', 'prorank-seo'));
      }
    } catch (e) {
      setError((e as Error)?.message || __('Failed to load font delivery health.', 'prorank-seo'));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const s = health?.settings || {};
  const c = health?.cache || {};
  const r = health?.rendered || {};
  const flags = health?.flags || [];

  const sevClass = (sev: string): string =>
    sev === 'critical' || sev === 'high'
      ? 'pr:border-red-500'
      : sev === 'medium'
        ? 'pr:border-amber-500'
        : 'pr:border-gray-400';

  return (
    <Card>
      <div className="pr:space-y-4">
        <div className="pr:flex pr:items-center pr:justify-between">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Font Delivery Health', 'prorank-seo')}
          </h3>
          {health && (
            <span className="pr:text-xs pr:font-medium pr:text-gray-500">
              {String(health.status || 'unknown').toUpperCase()}
            </span>
          )}
        </div>

        <p className="pr:text-sm pr:text-gray-600">
          {__(
            'Read-only view of how fonts are delivered. Toggles live in the Font Optimisation card above — this only reports state and advisory suggestions.',
            'prorank-seo'
          )}
        </p>

        {loading && (
          <p className="pr:text-sm pr:text-gray-500">{__('Checking font delivery…', 'prorank-seo')}</p>
        )}

        {!loading && error && <Alert variant="error" title={error} />}

        {!loading && !error && health && (
          <>
            <div className="pr:grid pr:grid-cols-2 pr:gap-3 pr:text-sm">
              <div>
                <span className="pr:font-medium pr:text-gray-900">{__('Local Google Fonts hosting', 'prorank-seo')}</span>
                <div className="pr:text-gray-600">{yesNo(s.host_google_fonts_locally)}</div>
              </div>
              <div>
                <span className="pr:font-medium pr:text-gray-900">{__('External Google Fonts on page', 'prorank-seo')}</span>
                <div className="pr:text-gray-600">
                  {r.fetched
                    ? r.external_google_fonts
                      ? `${__('Yes', 'prorank-seo')} (${r.external_google_count})`
                      : __('No', 'prorank-seo')
                    : __('Not checked', 'prorank-seo')}
                </div>
              </div>
              <div>
                <span className="pr:font-medium pr:text-gray-900">{__('ProRank local fonts served', 'prorank-seo')}</span>
                <div className="pr:text-gray-600">
                  {r.fetched ? yesNo(r.prorank_local_served) : __('Not checked', 'prorank-seo')}
                </div>
              </div>
              <div>
                <span className="pr:font-medium pr:text-gray-900">{__('Self-hosted font owner', 'prorank-seo')}</span>
                <div className="pr:text-gray-600">{r.self_hosted_owner || '—'}</div>
              </div>
              <div>
                <span className="pr:font-medium pr:text-gray-900">{__('Cached font files', 'prorank-seo')}</span>
                <div className="pr:text-gray-600">
                  {(c.cached_font_files ?? 0).toLocaleString()} ({c.cached_human || '0 B'})
                </div>
              </div>
              <div>
                <span className="pr:font-medium pr:text-gray-900">{__('font-display: swap', 'prorank-seo')}</span>
                <div className="pr:text-gray-600">
                  {s.font_display_swap ? __('Enabled', 'prorank-seo') : __('Disabled', 'prorank-seo')}
                </div>
              </div>
              <div>
                <span className="pr:font-medium pr:text-gray-900">{__('Critical preload', 'prorank-seo')}</span>
                <div className="pr:text-gray-600">
                  {s.font_preload_enabled
                    ? `${__('Enabled', 'prorank-seo')} (${s.font_preload_url_count ?? 0})`
                    : __('Disabled', 'prorank-seo')}
                </div>
              </div>
              <div>
                <span className="pr:font-medium pr:text-gray-900">{__('Preloaded fonts', 'prorank-seo')}</span>
                <div className="pr:text-gray-600">{(r.preloaded_fonts || []).length}</div>
              </div>
            </div>

            {flags.length === 0 ? (
              <Alert variant="success" title={__('No font delivery problems detected.', 'prorank-seo')} />
            ) : (
              <div className="pr:space-y-2">
                {flags.map((f) => (
                  <div key={f.code} className={`pr:border-l-4 pr:bg-gray-50 pr:p-3 pr:rounded ${sevClass(f.severity)}`}>
                    <div className="pr:text-sm pr:font-semibold pr:text-gray-900">
                      [{f.severity.toUpperCase()}] {f.message}
                    </div>
                    {f.recommendation && (
                      <div className="pr:text-xs pr:text-gray-600 pr:mt-1">{f.recommendation}</div>
                    )}
                  </div>
                ))}
              </div>
            )}

            {(r.preload_suggestions || []).length > 0 && (
              <Alert
                variant="info"
                title={__('Advisory: top above-the-fold fonts not yet preloaded (max 2)', 'prorank-seo')}
              >
                <ul className="pr:list-disc pr:pl-5 pr:text-xs pr:break-all">
                  {(r.preload_suggestions || []).map((u) => (
                    <li key={u}>{u}</li>
                  ))}
                </ul>
                <p className="pr:text-xs pr:text-gray-500 pr:mt-1">
                  {__(
                    'Not applied automatically. Add under Resource Hints → Font preload only if genuinely above-the-fold.',
                    'prorank-seo'
                  )}
                </p>
              </Alert>
            )}

            <div>
              <Button variant="secondary" onClick={load} disabled={loading}>
                {__('Re-check', 'prorank-seo')}
              </Button>
            </div>
          </>
        )}
      </div>
    </Card>
  );
};

export default FontDeliveryHealthPanel;
