/**
 * Internal Linking Pages Hub
 *
 * Main component for Internal Linking full page views with modern UI
 *
 * @package
 * @since   1.0.0
 */

import { useState, useEffect, useMemo } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import ProrankHeader from '../../components/ProrankHeader';
import ProrankDivider from '../../components/ProrankDivider';
import ModuleNav from '../../components/ModuleNav';
import headerBadges from '../../utils/headerBadges';
import '../../styles/features/_internal-linking.css';
import LinkingDashboard from './LinkingDashboard';
import LinksReport from './LinksReport';
import BrokenLinksReport from './BrokenLinksReport';
import VisualLinkMapLite from './VisualLinkMapLite';
import AutoLinkingTool from './AutoLinkingTool';
import InternalLinkingSettings from '../../settings/OnPageSEO/InternalLinking/InternalLinkingSettings';

const InternalLinkingPages = () => {
  const allTabs = [
    {
      name: 'dashboard',
      title: __('Dashboard', 'prorank-seo'),
    },
    {
      name: 'links-report',
      title: __('Links Report', 'prorank-seo'),
    },
    {
      name: 'visual-map',
      title: __('Link Map', 'prorank-seo'),
    },
    {
      name: 'broken-links',
      title: __('Broken Links', 'prorank-seo'),
    },
    {
      name: 'auto-linking',
      title: __('Auto Linking', 'prorank-seo'),
    },
    {
      name: 'settings',
      title: __('Settings', 'prorank-seo'),
    },
  ];

  const tabs = allTabs;

  const availableTabNames = useMemo(() => new Set(tabs.map((tab) => tab.name)), [tabs]);

  useEffect(() => {
    document.title = `${__('Internal Linking', 'prorank-seo')} ‹ ${__('ProRank SEO', 'prorank-seo')} — WordPress`;
  }, []);

  // Check for tab in URL hash
  const getInitialTab = () => {
    const hash = window.location.hash;
    const tabMatch = hash.match(/tab=([^&]+)/);
    if (tabMatch) {
      const tabName = tabMatch[1];
      // Map old tab names to new ones
      const tabMap = {
        'orphans': 'links-report',
        'opportunities': 'links-report',
        'analysis': 'links-report',
        'broken': 'broken-links',
      };
      const resolved = tabMap[tabName] || tabName;
      if (!availableTabNames.has(resolved)) {
        return 'dashboard';
      }
      return resolved;
    }
    return 'dashboard';
  };

  const [activeTab, setActiveTab] = useState(getInitialTab());

  useEffect(() => {
    if (!availableTabNames.has(activeTab)) {
      setActiveTab('dashboard');
    }
  }, [activeTab, availableTabNames]);

  // Update URL when tab changes
  const handleTabChange = (tabName) => {
    setActiveTab(tabName);
    const currentHash = window.location.hash;
    const baseHash = currentHash.split('?')[0];
    window.location.hash = `${baseHash}?tab=${tabName}`;
  };

  // Listen for hash changes
  useEffect(() => {
    const handleHashChange = () => {
      const newTab = getInitialTab();
      if (newTab !== activeTab) {
        setActiveTab(newTab);
      }
    };

    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, [activeTab]);

  const renderTabContent = () => {
    switch (activeTab) {
      case 'dashboard':
        return <LinkingDashboard />;
      case 'links-report':
        return <LinksReport />;
      case 'visual-map':
        return <VisualLinkMapLite />;
      case 'broken-links':
        return <BrokenLinksReport />;
      case 'auto-linking':
        return <AutoLinkingTool />;
      case 'settings':
        return <InternalLinkingSettings />;
      default:
        return <LinkingDashboard />;
    }
  };

  return (
    <div className="prorank-page">
      <ProrankHeader
        title={__('Internal Linking', 'prorank-seo')}
        subtitle={__('Manage internal links, discover opportunities, and fix broken links', 'prorank-seo')}
        badges={headerBadges['internal-linking']}
      />

      <div className="prorank-content">
        <ModuleNav
          modules={tabs.map((tab) => ({
            id: tab.name,
            label: tab.title,
          }))}
          activeModule={activeTab}
          onModuleChange={handleTabChange}
        />

        <ProrankDivider />

        <div className="pr:mt-6">{renderTabContent()}</div>
      </div>
    </div>
  );
};

export default InternalLinkingPages;
