'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Link from 'next/link';
import dynamic from 'next/dynamic';
import { Card, CardBody } from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import { ErrorBoundary } from '@/components/ui/ErrorBoundary';
import { ToastProvider, useToast } from '@/components/ui/Toast';
import TierGate from '@/components/ui/TierGate';
import styles from '../../dashboard.module.css';
import type { NavTreeItem } from '@/components/cms/NavTreeEditor';
import { validateNavigation, NavItemData } from '@/lib/cms/nav-validation';
import { normalizeUrl } from '@/lib/cms/link-validation-client';

// Dynamically import the tree editor to avoid SSR issues with dnd-kit
const NavTreeEditor = dynamic(() => import('@/components/cms/NavTreeEditor'), {
  ssr: false,
  loading: () => (
    <div style={{ padding: '2rem', textAlign: 'center', color: '#64748b' }}>
      Loading navigation editor...
    </div>
  ),
});

// ==================== DATA TRANSFORMATION ====================

interface DbNavigationItem {
  id: string;
  dealerId: string;
  label: string;
  pageId: string | null;
  externalUrl: string | null;
  parentId: string | null;
  sortOrder: number;
  isDefault: boolean;
  defaultKey: string | null;
  defaultSortOrder: number | null;
  openInNewTab: boolean;
  isVisible: boolean;
  page?: { slug: string; title: string } | null;
}

function dbItemsToTreeItems(dbItems: DbNavigationItem[]): NavTreeItem[] {
  // Filter visible items and separate parents from children
  const visibleItems = dbItems.filter((item) => item.isVisible);
  const parents = visibleItems.filter((item) => !item.parentId);
  const childrenByParent = new Map<string, DbNavigationItem[]>();

  visibleItems
    .filter((item) => item.parentId)
    .forEach((item) => {
      const existing = childrenByParent.get(item.parentId!) || [];
      existing.push(item);
      childrenByParent.set(item.parentId!, existing);
    });

  // Sort parents by sortOrder
  parents.sort((a, b) => a.sortOrder - b.sortOrder);

  // Build tree
  return parents.map((parent) => {
    const children = (childrenByParent.get(parent.id) || [])
      .sort((a, b) => a.sortOrder - b.sortOrder)
      .map((child) => dbItemToTreeItem(child, []));

    return dbItemToTreeItem(parent, children);
  });
}

function dbItemToTreeItem(item: DbNavigationItem, children: NavTreeItem[]): NavTreeItem {
  let linkType: 'none' | 'page' | 'external' | 'pdf' = 'none';
  if (item.pageId) linkType = 'page';
  else if (item.externalUrl?.startsWith('/api/documents/')) linkType = 'pdf';
  else if (item.externalUrl) linkType = 'external';

  return {
    id: item.id,
    label: item.label,
    linkType,
    pageId: item.pageId,
    pageSlug: item.page?.slug || null,
    externalUrl: item.externalUrl,
    openInNewTab: item.openInNewTab,
    isDefault: item.isDefault,
    defaultKey: item.defaultKey,
    defaultSortOrder: item.defaultSortOrder,
    children,
  };
}

function treeItemsToDbItems(items: NavTreeItem[], dealerId: string): DbNavigationItem[] {
  const result: DbNavigationItem[] = [];

  items.forEach((item, index) => {
    // Add parent
    result.push(treeItemToDbItem(item, dealerId, null, index));

    // Add children
    item.children.forEach((child, childIndex) => {
      result.push(treeItemToDbItem(child, dealerId, item.id, childIndex));
    });
  });

  return result;
}

function treeItemToDbItem(
  item: NavTreeItem,
  dealerId: string,
  parentId: string | null,
  sortOrder: number
): DbNavigationItem {
  return {
    id: item.id,
    dealerId,
    label: item.label,
    pageId: item.linkType === 'page' ? item.pageId : null,
    externalUrl: (item.linkType === 'external' || item.linkType === 'pdf') ? item.externalUrl : null,
    parentId,
    sortOrder,
    isDefault: item.isDefault,
    defaultKey: item.defaultKey,
    defaultSortOrder: item.defaultSortOrder,
    openInNewTab: item.openInNewTab,
    isVisible: true,
  };
}

// ==================== EDIT MODAL ====================

interface PdfAsset {
  id: string;
  url: string;
  filename: string;
}

interface CmsPage {
  id: string;
  title: string;
  slug: string;
  type: string;
  status: string;
}

interface EditModalProps {
  item: NavTreeItem | null;
  onSave: (item: NavTreeItem) => void;
  onClose: () => void;
}

function EditModal({ item, onSave, onClose }: EditModalProps) {
  const [label, setLabel] = useState(item?.label || '');
  const [linkType, setLinkType] = useState<'none' | 'page' | 'external' | 'pdf'>(item?.linkType || 'none');
  const [externalUrl, setExternalUrl] = useState(item?.externalUrl || '');
  const [selectedPageId, setSelectedPageId] = useState(item?.pageId || '');
  const [openInNewTab, setOpenInNewTab] = useState(item?.openInNewTab || false);
  const [pages, setPages] = useState<CmsPage[]>([]);
  const [loadingPages, setLoadingPages] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  // Fetch available pages when linkType is 'page'
  useEffect(() => {
    if (linkType !== 'page') return;

    // eslint-disable-next-line react-hooks/set-state-in-effect -- Standard loading state pattern before async operation
    setLoadingPages(true);
    fetch('/api/cms/pages?type=page')
      .then((r) => r.json())
      .then((data) => {
        if (data.pages) {
          setPages(data.pages);
        }
      })
      .catch((err) => console.error('Failed to fetch pages:', err))
      .finally(() => setLoadingPages(false));
  }, [linkType]);

  // PDF assets for 'pdf' link type
  const [pdfAssets, setPdfAssets] = useState<PdfAsset[]>([]);
  const [loadingPdfs, setLoadingPdfs] = useState(false);
  const [selectedPdfUrl, setSelectedPdfUrl] = useState(
    item?.linkType === 'pdf' ? item?.externalUrl || '' : ''
  );

  useEffect(() => {
    if (linkType !== 'pdf') return;
    setLoadingPdfs(true);
    fetch('/api/media')
      .then((r) => {
        if (!r.ok) throw new Error(`Failed to load documents (${r.status})`);
        return r.json();
      })
      .then((data) => {
        const pdfs = (data.myImages || []).filter(
          (asset: { mimeType: string }) => asset.mimeType === 'application/pdf'
        );
        setPdfAssets(pdfs);
      })
      .catch(() => setSubmitError('Could not load PDF documents. Please try again.'))
      .finally(() => setLoadingPdfs(false));
  }, [linkType]);

  const handlePdfChange = (pdfUrl: string) => {
    setSelectedPdfUrl(pdfUrl);
    const selectedPdf = pdfAssets.find((p) => `/api/documents/${p.id}` === pdfUrl);
    if (selectedPdf && (!label || label === 'New Item')) {
      setLabel(selectedPdf.filename.replace(/\.pdf$/i, '').replace(/[-_]/g, ' '));
    }
    setOpenInNewTab(true);
  };

  // Handle page selection - auto-populate label
  const handlePageChange = (pageId: string) => {
    setSelectedPageId(pageId);
    // Auto-populate label from page title if label is empty or default
    const selectedPage = pages.find((p) => p.id === pageId);
    if (selectedPage && (!label || label === 'New Item')) {
      setLabel(selectedPage.title);
    }
  };

  if (!item) return null;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitError(null);
    if (linkType === 'pdf' && !selectedPdfUrl) {
      setSubmitError('Please select a PDF document.');
      return;
    }
    if (linkType === 'page' && !selectedPageId) {
      setSubmitError('Please select a page.');
      return;
    }
    if (linkType === 'external' && !externalUrl.trim()) {
      setSubmitError('Please enter a URL.');
      return;
    }
    // Look up the page slug if a page is selected
    const selectedPage = pages.find((p) => p.id === selectedPageId);
    // Normalize URL even if user submits without blurring the input
    const normalizedUrl = linkType === 'external' ? normalizeUrl(externalUrl) : linkType === 'pdf' ? selectedPdfUrl : null;
    onSave({
      ...item,
      label,
      linkType,
      pageId: linkType === 'page' ? selectedPageId || null : null,
      pageSlug: linkType === 'page' && selectedPage ? selectedPage.slug : null,
      externalUrl: normalizedUrl,
      openInNewTab,
    });
  };

  return (
    <div
      className="fixed inset-0 flex items-center justify-center z-50 p-6"
      style={{
        backgroundColor: 'rgba(0, 0, 0, 0.75)',
        backdropFilter: 'blur(8px)',
        borderRadius: '20px',
      }}
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      {/* Modal Card - matches Card surface variant, fixed width with overflow handling */}
      <Card variant="surface" style={{ width: '540px', maxWidth: '100%', overflow: 'hidden' }}>
        <CardBody style={{ overflow: 'hidden' }}>
          <h3
            style={{ fontSize: '1.25rem', fontWeight: 600, color: '#f8fafc', marginBottom: '28px' }}
          >
            Edit Navigation Item
          </h3>

          <form onSubmit={handleSubmit}>
            {submitError && (
              <p style={{ color: '#f87171', fontSize: '0.85rem', marginBottom: '16px' }}>
                {submitError}
              </p>
            )}
            {/* 1. Link Type */}
            <div style={{ marginBottom: '28px' }}>
              <label
                style={{
                  display: 'block',
                  fontSize: '0.875rem',
                  fontWeight: 500,
                  color: '#e2e8f0',
                  marginBottom: '10px',
                }}
              >
                Link Type
              </label>
              <select
                value={linkType}
                onChange={(e) => setLinkType(e.target.value as 'none' | 'page' | 'external' | 'pdf')}
                style={{
                  width: '100%',
                  padding: '14px 16px',
                  background: 'rgba(15, 23, 42, 0.8)',
                  border: '1px solid rgba(148, 163, 184, 0.3)',
                  borderRadius: '10px',
                  color: '#f8fafc',
                  fontSize: '0.9rem',
                }}
              >
                <option value="none">No Link (dropdown parent)</option>
                <option value="page">Internal Page</option>
                <option value="pdf">Internal PDF</option>
                <option value="external">External URL</option>
              </select>
            </div>

            {/* 2. Page/URL field - fixed height container to prevent resize */}
            <div style={{ minHeight: '100px', marginBottom: '28px' }}>
              {linkType === 'page' && (
                <div>
                  <label
                    style={{
                      display: 'block',
                      fontSize: '0.875rem',
                      fontWeight: 500,
                      color: '#e2e8f0',
                      marginBottom: '10px',
                    }}
                  >
                    Select Page
                  </label>
                  <select
                    value={selectedPageId}
                    onChange={(e) => handlePageChange(e.target.value)}
                    disabled={loadingPages}
                    style={{
                      width: '100%',
                      padding: '14px 16px',
                      background: 'rgba(15, 23, 42, 0.8)',
                      border: '1px solid rgba(148, 163, 184, 0.3)',
                      borderRadius: '10px',
                      color: '#f8fafc',
                      fontSize: '0.9rem',
                      opacity: loadingPages ? 0.5 : 1,
                    }}
                  >
                    <option value="">
                      {loadingPages ? 'Loading pages...' : '-- Choose a page --'}
                    </option>
                    {pages.map((page) => (
                      <option key={page.id} value={page.id}>
                        {page.title} ({page.slug})
                      </option>
                    ))}
                  </select>
                  {pages.length === 0 && !loadingPages && (
                    <p style={{ fontSize: '0.8rem', color: '#94a3b8', marginTop: '10px' }}>
                      No custom pages found. Create pages in the CMS first.
                    </p>
                  )}
                </div>
              )}

              {linkType === 'external' && (
                <div>
                  <label
                    style={{
                      display: 'block',
                      fontSize: '0.875rem',
                      fontWeight: 500,
                      color: '#e2e8f0',
                      marginBottom: '10px',
                    }}
                  >
                    External URL
                  </label>
                  <input
                    type="url"
                    inputMode="url"
                    pattern=".*"
                    value={externalUrl}
                    onChange={(e) => setExternalUrl(e.target.value)}
                    onBlur={(e) => setExternalUrl(normalizeUrl(e.target.value))}
                    placeholder="example.com"
                    style={{
                      width: '100%',
                      padding: '14px 16px',
                      background: 'rgba(15, 23, 42, 0.8)',
                      border: '1px solid rgba(148, 163, 184, 0.3)',
                      borderRadius: '10px',
                      color: '#f8fafc',
                      fontSize: '0.9rem',
                    }}
                  />
                  <p style={{ fontSize: '0.75rem', color: '#94a3b8', marginTop: '8px' }}>
                    Tip: Just enter the domain (e.g., example.com) — we&apos;ll add https://
                    automatically
                  </p>
                </div>
              )}

              {linkType === 'pdf' && (
                <div>
                  <label
                    style={{
                      display: 'block',
                      fontSize: '0.875rem',
                      fontWeight: 500,
                      color: '#e2e8f0',
                      marginBottom: '10px',
                    }}
                  >
                    Select PDF
                  </label>
                  <select
                    value={selectedPdfUrl}
                    onChange={(e) => handlePdfChange(e.target.value)}
                    disabled={loadingPdfs}
                    style={{
                      width: '100%',
                      padding: '14px 16px',
                      background: 'rgba(15, 23, 42, 0.8)',
                      border: '1px solid rgba(148, 163, 184, 0.3)',
                      borderRadius: '10px',
                      color: '#f8fafc',
                      fontSize: '0.9rem',
                      opacity: loadingPdfs ? 0.5 : 1,
                    }}
                  >
                    <option value="">
                      {loadingPdfs ? 'Loading documents...' : '-- Choose a PDF --'}
                    </option>
                    {pdfAssets.map((pdf) => (
                      <option key={pdf.id} value={`/api/documents/${pdf.id}`}>
                        {pdf.filename}
                      </option>
                    ))}
                  </select>
                  {pdfAssets.length === 0 && !loadingPdfs && (
                    <p style={{ fontSize: '0.8rem', color: '#94a3b8', marginTop: '10px' }}>
                      No PDFs found. Upload documents in the Media Library first.
                    </p>
                  )}
                </div>
              )}

              {linkType === 'none' && (
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    height: '100%',
                    padding: '14px 0',
                  }}
                >
                  <p style={{ color: '#94a3b8', fontSize: '0.9rem', fontStyle: 'italic' }}>
                    This item will serve as a dropdown parent with no direct link.
                  </p>
                </div>
              )}
            </div>

            {/* 3. Label */}
            <div style={{ marginBottom: '28px', overflow: 'hidden' }}>
              <label
                style={{
                  display: 'block',
                  fontSize: '0.875rem',
                  fontWeight: 500,
                  color: '#e2e8f0',
                  marginBottom: '10px',
                }}
              >
                Label
              </label>
              <input
                type="text"
                value={label}
                onChange={(e) => setLabel(e.target.value)}
                style={{
                  width: '100%',
                  padding: '14px 16px',
                  background: 'rgba(15, 23, 42, 0.8)',
                  border: '1px solid rgba(148, 163, 184, 0.3)',
                  borderRadius: '10px',
                  color: '#f8fafc',
                  fontSize: '0.9rem',
                  boxSizing: 'border-box',
                  maxWidth: '100%',
                }}
                required
              />
            </div>

            {/* 4. Open in new tab checkbox */}
            {linkType !== 'none' && (
              <div style={{ marginBottom: '28px' }}>
                <label
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '14px',
                    fontSize: '0.9rem',
                    color: '#e2e8f0',
                    cursor: 'pointer',
                  }}
                >
                  <input
                    type="checkbox"
                    checked={openInNewTab}
                    onChange={(e) => setOpenInNewTab(e.target.checked)}
                    style={{ width: '18px', height: '18px' }}
                  />
                  Open in new tab
                </label>
              </div>
            )}

            <div
              style={{
                display: 'flex',
                gap: '14px',
                justifyContent: 'flex-end',
                paddingTop: '20px',
                borderTop: '1px solid rgba(148, 163, 184, 0.15)',
              }}
            >
              <Button variant="secondary" onClick={onClose} type="button">
                Cancel
              </Button>
              <Button
                variant="primary"
                type="submit"
                disabled={linkType === 'page' && loadingPages}
              >
                {linkType === 'page' && loadingPages ? 'Loading...' : 'Save Changes'}
              </Button>
            </div>
          </form>
        </CardBody>
      </Card>
    </div>
  );
}

// ==================== MAIN CONTENT ====================

function NavigationEditorContent() {
  const router = useRouter();
  const { data: session, status: sessionStatus } = useSession();
  const { showToast } = useToast();
  const [items, setItems] = useState<NavTreeItem[]>([]);
  const [dealerId, setDealerId] = useState<string>('');
  const [dealerName, setDealerName] = useState<string>('');
  const [dealerCity, setDealerCity] = useState<string>('');
  const [dealerPhone, setDealerPhone] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [validationError, setValidationError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [resetting, setResetting] = useState(false);
  const [lastSaved, setLastSaved] = useState<Date | null>(null);
  const [editingItem, setEditingItem] = useState<NavTreeItem | null>(null);

  // Validate navigation structure
  const validateItems = useCallback((treeItems: NavTreeItem[]): string | null => {
    try {
      const dbItems = treeItemsToDbItems(treeItems, 'temp');
      const navItems: NavItemData[] = dbItems.map((item) => ({
        id: item.id,
        label: item.label,
        isDefault: item.isDefault,
        defaultKey: item.defaultKey,
        defaultSortOrder: null,
        parentId: item.parentId,
        sortOrder: item.sortOrder,
        externalUrl: item.externalUrl,
        pageId: item.pageId,
      }));

      const result = validateNavigation(navItems);
      return result.valid ? null : result.error || 'Invalid navigation structure';
    } catch (err) {
      return err instanceof Error ? err.message : 'Validation error';
    }
  }, []);

  const fetchData = useCallback(async () => {
    try {
      // Fetch navigation and dealer info in parallel
      const [navResponse, dealerResponse] = await Promise.all([
        fetch('/api/cms/navigation'),
        fetch('/api/dealer'),
      ]);

      if (!navResponse.ok) {
        const data = await navResponse.json();
        // Check for tier restriction (403)
        if (navResponse.status === 403) {
          setError('upgrade_required');
          setLoading(false);
          return;
        }
        throw new Error(data.error || 'Failed to fetch navigation');
      }

      const navData = await navResponse.json();
      const treeItems = dbItemsToTreeItems(navData.items || []);
      setItems(treeItems);
      setDealerId(navData.dealer?.id || '');

      // Get dealer info for preview
      if (dealerResponse.ok) {
        const dealerData = await dealerResponse.json();
        setDealerName(dealerData.displayName || dealerData.businessName || '');
        setDealerCity(
          dealerData.city && dealerData.state ? `${dealerData.city}, ${dealerData.state}` : ''
        );
        setDealerPhone(dealerData.phone || '');
      }

      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load navigation');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (sessionStatus === 'loading') return;

    if (!session?.user?.id) {
      router.push('/api/auth/signin');
      return;
    }

    fetchData();
  }, [session, sessionStatus, router, fetchData]);

  const handleItemsChange = useCallback(
    (newItems: NavTreeItem[]) => {
      setItems(newItems);
      const validationErr = validateItems(newItems);
      setValidationError(validationErr);
    },
    [validateItems]
  );

  const handleAddItem = useCallback(() => {
    const newItem: NavTreeItem = {
      id: `nav-${crypto.randomUUID()}`,
      label: 'New Item',
      linkType: 'none',
      pageId: null,
      pageSlug: null,
      externalUrl: null,
      openInNewTab: false,
      isDefault: false,
      defaultKey: null,
      defaultSortOrder: null,
      children: [],
    };
    setItems((prev) => [...prev, newItem]);
    setEditingItem(newItem);
  }, []);

  const handleEditItem = useCallback((item: NavTreeItem) => {
    setEditingItem(item);
  }, []);

  const handleSaveEdit = useCallback((updatedItem: NavTreeItem) => {
    setItems((prev) => {
      const updateInTree = (treeItems: NavTreeItem[]): NavTreeItem[] => {
        return treeItems.map((item) => {
          if (item.id === updatedItem.id) {
            return { ...updatedItem, children: item.children };
          }
          return { ...item, children: updateInTree(item.children) };
        });
      };
      return updateInTree(prev);
    });
    setEditingItem(null);
  }, []);

  const handlePublish = useCallback(async () => {
    if (saving) return; // Guard against double-clicks

    const validationErr = validateItems(items);
    if (validationErr) {
      setValidationError(validationErr);
      setError('Cannot save: ' + validationErr);
      return;
    }

    setSaving(true);
    setError(null);
    setValidationError(null);

    try {
      // Step 1: Save navigation
      const dbItems = treeItemsToDbItems(items, dealerId);

      const response = await fetch('/api/cms/navigation', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ items: dbItems, publish: true }),
      });

      if (!response.ok) {
        let errorMessage = 'Failed to save navigation';
        try {
          const data = await response.json();
          errorMessage = data.error || errorMessage;
        } catch {
          errorMessage = `Server error (${response.status}). Please try again.`;
        }
        throw new Error(errorMessage);
      }

      // Step 2: Publish the dealer site
      const publishResponse = await fetch(`/api/dealers/${dealerId}/publish`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      });

      if (!publishResponse.ok) {
        let errorMessage = 'Failed to publish site';
        try {
          const publishData = await publishResponse.json();
          errorMessage = publishData.error || errorMessage;
        } catch {
          errorMessage = `Server error (${publishResponse.status}). Please try again.`;
        }
        throw new Error(errorMessage);
      }

      setLastSaved(new Date());
      showToast('Published successfully!', 'success');
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to publish';
      setError(errorMessage);
      showToast(errorMessage, 'error');
    } finally {
      setSaving(false);
    }
  }, [items, dealerId, validateItems, showToast, saving]);

  const handleReset = useCallback(async () => {
    if (resetting) return;
    if (
      !confirm(
        'Reset navigation to defaults? This will remove all custom items and restore the original menu structure.'
      )
    ) {
      return;
    }

    setResetting(true);
    setError(null);

    try {
      const response = await fetch('/api/cms/navigation/reset', {
        method: 'POST',
      });

      if (!response.ok) {
        let errorMessage = 'Failed to reset navigation';
        try {
          const data = await response.json();
          errorMessage = data.error || errorMessage;
        } catch {
          errorMessage = `Server error (${response.status}). Please try again.`;
        }
        throw new Error(errorMessage);
      }

      const data = await response.json();
      if (!data.items || !Array.isArray(data.items) || data.items.length === 0) {
        throw new Error('Reset completed but no default items were returned. Please try again.');
      }
      const treeItems = dbItemsToTreeItems(data.items);
      setItems(treeItems);
      setValidationError(null);
      showToast('Navigation reset to defaults', 'success');
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to reset';
      setError(errorMessage);
      showToast(errorMessage, 'error');
    } finally {
      setResetting(false);
    }
  }, [resetting, showToast]);

  // Handle keyboard shortcut for publish (Ctrl+S)
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        handlePublish();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [handlePublish]);

  if (loading || sessionStatus === 'loading') {
    return (
      <section className={styles.section}>
        <div className={styles.content}>
          <Card variant="surface">
            <CardBody>
              <div className={styles.emptyState}>
                <p>Loading navigation editor...</p>
              </div>
            </CardBody>
          </Card>
        </div>
      </section>
    );
  }

  if (error === 'upgrade_required') {
    return (
      <TierGate
        title="Enhanced Tier Required"
        description="The Navigation Editor lets you customize your dealer site's menu structure with drag-and-drop ease."
        features={[
          'Full control over all menu items',
          'Drag-and-drop menu reordering',
          'Create dropdown menus with nested items',
          'Link to internal pages or external URLs',
          'Live preview while editing',
        ]}
        requiredTier="enhanced"
        backLink={{ href: '/dashboard/cms', text: 'Back to CMS' }}
      />
    );
  }

  if (error && items.length === 0) {
    return (
      <section className={styles.section}>
        <div className={styles.content}>
          <div style={{ marginBottom: '1.5rem' }}>
            <Link
              href="/dashboard"
              style={{ color: '#38bdf8', textDecoration: 'none', fontSize: '0.875rem' }}
            >
              ← Back to Dashboard
            </Link>
          </div>
          <Card variant="surface">
            <CardBody>
              <div
                style={{
                  padding: '2rem',
                  textAlign: 'center',
                  color: '#f87171',
                }}
              >
                <p style={{ marginBottom: '1rem' }}>{error}</p>
                <Button variant="secondary" onClick={fetchData}>
                  Try Again
                </Button>
              </div>
            </CardBody>
          </Card>
        </div>
      </section>
    );
  }

  return (
    <section className={styles.section}>
      <div className={styles.content}>
        {/* Header */}
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'flex-start',
            marginBottom: '1.5rem',
          }}
        >
          <div>
            <Link
              href="/dashboard"
              style={{ color: '#38bdf8', textDecoration: 'none', fontSize: '0.875rem' }}
            >
              ← Back to Dashboard
            </Link>
            <h2
              style={{ fontSize: '1.5rem', fontWeight: 600, marginTop: '0.5rem', color: '#f8fafc' }}
            >
              Navigation Editor
            </h2>
            <p style={{ color: 'rgba(148, 163, 184, 0.85)', marginTop: '0.5rem' }}>
              Fully customize your dealer page navigation. Edit, reorder, or remove any item.
            </p>
          </div>

          <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
            {lastSaved && (
              <span style={{ fontSize: '0.75rem', color: '#64748b' }}>
                Last saved: {lastSaved.toLocaleTimeString()}
              </span>
            )}
            <Button
              variant="secondary"
              size="sm"
              onClick={handleReset}
              disabled={resetting || saving}
            >
              {resetting ? 'Resetting...' : 'Reset to Defaults'}
            </Button>
            <Button
              variant="primary"
              size="sm"
              onClick={handlePublish}
              disabled={saving || !!validationError}
              title={validationError ? 'Fix validation errors before publishing' : undefined}
            >
              {saving ? 'Publishing...' : 'Publish'}
            </Button>
          </div>
        </div>

        {error && (
          <div
            style={{
              padding: '1rem',
              marginBottom: '1rem',
              backgroundColor: 'rgba(248, 113, 113, 0.1)',
              border: '1px solid rgba(248, 113, 113, 0.35)',
              borderLeft: '4px solid #f87171',
              borderRadius: '8px',
              color: '#fee2e2',
            }}
          >
            {error}
          </div>
        )}

        {validationError && !error && (
          <div
            style={{
              padding: '1rem',
              marginBottom: '1rem',
              backgroundColor: 'rgba(251, 191, 36, 0.1)',
              border: '1px solid rgba(251, 191, 36, 0.35)',
              borderLeft: '4px solid #fbbf24',
              borderRadius: '8px',
              color: '#fef3c7',
            }}
          >
            <strong>Warning:</strong> {validationError}
            <br />
            <span style={{ fontSize: '0.875rem', opacity: 0.8 }}>
              Fix this issue before saving.
            </span>
          </div>
        )}

        {/* Tree Editor */}
        <ErrorBoundary
          fallbackTitle="Editor Error"
          fallbackMessage="The navigation editor encountered an error. Please try again."
          onReset={fetchData}
        >
          <NavTreeEditor
            items={items}
            onItemsChange={handleItemsChange}
            onAddItem={handleAddItem}
            onEditItem={handleEditItem}
            dealerName={dealerName}
            dealerCity={dealerCity}
            dealerPhone={dealerPhone}
          />
        </ErrorBoundary>

        {/* Help text */}
        <Card variant="surface" style={{ marginTop: '1.5rem' }}>
          <CardBody>
            <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '0.75rem' }}>
              Navigation Editor Help
            </h3>
            <ul
              style={{
                margin: 0,
                paddingLeft: '1.25rem',
                color: 'rgba(148, 163, 184, 0.85)',
                fontSize: '0.875rem',
                lineHeight: 1.6,
              }}
            >
              <li>
                <strong>Drag items</strong> to reorder them in the navigation bar
              </li>
              <li>
                <strong>Drag into another item</strong> to create a dropdown menu
              </li>
              <li>
                <strong>Click the edit icon</strong> to change any item&apos;s label, link, or
                target
              </li>
              <li>
                <strong>Reset to Defaults</strong> restores the original menu structure
              </li>
              <li>
                <strong>Maximum limits:</strong> 8 top-level items, 6 children per parent
              </li>
            </ul>
          </CardBody>
        </Card>
      </div>

      {/* Edit Modal */}
      <EditModal
        key={editingItem?.id || ''}
        item={editingItem}
        onSave={handleSaveEdit}
        onClose={() => setEditingItem(null)}
      />
    </section>
  );
}

/**
 * Main export - wraps content in ToastProvider
 */
export default function NavigationEditorPage() {
  return (
    <ToastProvider>
      <NavigationEditorContent />
    </ToastProvider>
  );
}
