import { useState, useEffect, useCallback, useMemo } from 'react';
import { Puck, Render } from "@measured/puck";
import "@measured/puck/puck.css";
import { puckConfig, getEditorConfig, renderConfig } from "../puck/config";
import { usePages, useUpdatePage, useCreatePage, useDeletePage } from "../hooks/useSites";
import { Loader2, Plus, Trash2, FileText, Monitor, Tablet, Smartphone, Settings, Eye, X, ExternalLink, Save, RotateCcw, Maximize2, Minimize2 } from "lucide-react";
import toast from 'react-hot-toast';
import { useEntitlements, FEATURE_CODES } from '../hooks/useEntitlements';

// Draft storage key prefix
const DRAFT_KEY_PREFIX = 'puck_draft_';

type ViewportSize = 'desktop' | 'tablet' | 'mobile';

const VIEWPORT_WIDTHS: Record<ViewportSize, number | null> = {
  desktop: null, // Full width
  tablet: 768,
  mobile: 375,
};

export const PageEditor: React.FC = () => {
  const { data: pages, isLoading } = usePages();
  const { getLimit, isLoading: entitlementsLoading, hasFeature } = useEntitlements();
  const updatePage = useUpdatePage();
  const createPage = useCreatePage();
  const deletePage = useDeletePage();
  const [data, setData] = useState<any>(null);
  const [currentPageId, setCurrentPageId] = useState<string | null>(null);
  const [loadedPageId, setLoadedPageId] = useState<string | null>(null); // Track which page's data is loaded
  const [showNewPageModal, setShowNewPageModal] = useState(false);
  const [newPageTitle, setNewPageTitle] = useState('');
  const [viewport, setViewport] = useState<ViewportSize>('desktop');
  const [showPageSettings, setShowPageSettings] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [previewViewport, setPreviewViewport] = useState<ViewportSize>('desktop');
  const [previewData, setPreviewData] = useState<any>(null);
  const [previewFullWidth, setPreviewFullWidth] = useState(false);
  const [hasDraft, setHasDraft] = useState(false);
  const [publishedData, setPublishedData] = useState<any>(null);

  // Get draft key for current page
  const getDraftKey = useCallback((pageId: string) => {
    return `${DRAFT_KEY_PREFIX}${pageId}`;
  }, []);

  // Check if current data differs from published data
  const hasUnsavedChanges = useMemo(() => {
    if (!data || !publishedData) return false;
    return JSON.stringify(data) !== JSON.stringify(publishedData);
  }, [data, publishedData]);

  // Get max_public_pages from billing entitlements
  // null = unlimited, 0 = no access, >0 = limited pages
  const maxPagesLimit = getLimit(FEATURE_CODES.MAX_PUBLIC_PAGES);
  const canCustomize = maxPagesLimit === null || maxPagesLimit > 0;
  const pageCount = pages?.length || 0;
  const canCreateMore = canCustomize && (maxPagesLimit === null || pageCount < maxPagesLimit);

  // Feature-gated components
  const features = {
    can_use_service_catalog: hasFeature('can_use_service_catalog'),
  };

  // Get editor config with feature gating
  const editorConfig = getEditorConfig(features);

  // Compute current page - prioritize explicit selection, then home page, then first page
  const currentPage = useMemo(() => {
    if (!pages?.length) return null;
    if (currentPageId) {
      const found = pages.find((p: any) => String(p.id) === String(currentPageId));
      if (found) return found;
    }
    return pages.find((p: any) => p.is_home) || pages[0];
  }, [pages, currentPageId]);

  // Load page data when currentPageId changes (use ID, not object reference)
  useEffect(() => {
    if (!pages?.length || !currentPageId) return;

    const page = pages.find((p: any) => String(p.id) === String(currentPageId));
    if (!page) return;

    // Clear data first to prevent stale data being used
    // Only clear if we're loading a different page
    if (loadedPageId !== String(page.id)) {
      setData(null);
    }

    // Ensure data structure is valid for Puck
    const puckData = page.puck_data || { content: [], root: {} };
    if (!puckData.content) puckData.content = [];
    if (!puckData.root) puckData.root = {};

    // Store the published data for comparison
    setPublishedData(puckData);

    // Check for saved draft
    const draftKey = getDraftKey(page.id);
    const savedDraft = localStorage.getItem(draftKey);

    if (savedDraft) {
      try {
        const draftData = JSON.parse(savedDraft);
        setData(draftData);
        setHasDraft(true);
      } catch (e) {
        // Invalid draft data, use published
        setData(puckData);
        setHasDraft(false);
        localStorage.removeItem(draftKey);
      }
    } else {
      setData(puckData);
      setHasDraft(false);
    }

    // Mark which page's data is now loaded
    setLoadedPageId(String(page.id));
  }, [pages, currentPageId, getDraftKey]);

  // Set initial page ID when pages load
  useEffect(() => {
    if (pages?.length && !currentPageId) {
      const homePage = pages.find((p: any) => p.is_home);
      const initialPage = homePage || pages[0];
      if (initialPage) {
        setCurrentPageId(String(initialPage.id));
      }
    }
  }, [pages, currentPageId]);

  // Handle page change - clear data immediately to prevent stale state
  const handlePageChange = useCallback((newPageId: string) => {
    if (newPageId !== currentPageId) {
      // Clear data immediately so Puck doesn't render with wrong data
      setData(null);
      setLoadedPageId(null);
      setCurrentPageId(newPageId);
    }
  }, [currentPageId]);

  const handlePublish = async (newData: any) => {
    if (!currentPage) return;

    // Check if user has permission to customize (based on max_public_pages entitlement)
    if (!canCustomize) {
      toast.error("Your plan does not include site customization. Please upgrade to edit pages.");
      return;
    }

    try {
      await updatePage.mutateAsync({ id: currentPage.id, data: { puck_data: newData } });

      // Clear draft after successful publish
      const draftKey = getDraftKey(currentPage.id);
      localStorage.removeItem(draftKey);
      setHasDraft(false);
      setPublishedData(newData);

      toast.success("Page published successfully!");
    } catch (error: any) {
      const errorMsg = error?.response?.data?.error || "Failed to publish page.";
      toast.error(errorMsg);
      console.error(error);
    }
  };

  // Save draft to localStorage
  const handleSaveDraft = useCallback(() => {
    if (!currentPage || !data) return;

    if (!canCustomize) {
      toast.error("Your plan does not include site customization.");
      return;
    }

    const draftKey = getDraftKey(currentPage.id);
    localStorage.setItem(draftKey, JSON.stringify(data));
    setHasDraft(true);
    toast.success("Draft saved!");
  }, [currentPage, data, canCustomize, getDraftKey]);

  // Discard draft and revert to published version
  const handleDiscardDraft = useCallback(() => {
    if (!currentPage || !publishedData) return;

    if (!confirm("Discard all changes and revert to the published version?")) return;

    const draftKey = getDraftKey(currentPage.id);
    localStorage.removeItem(draftKey);
    setData(publishedData);
    setHasDraft(false);
    toast.success("Draft discarded, reverted to published version.");
  }, [currentPage, publishedData, getDraftKey]);

  const handleCreatePage = async () => {
    if (!newPageTitle.trim()) {
      toast.error("Page title is required");
      return;
    }

    try {
      const newPage = await createPage.mutateAsync({
        title: newPageTitle,
      });
      toast.success(`Page "${newPageTitle}" created!`);
      setNewPageTitle('');
      setShowNewPageModal(false);
      // Set empty data immediately so the new page starts blank
      const emptyData = { content: [], root: {} };
      setData(emptyData);
      setPublishedData(emptyData);
      setHasDraft(false);
      setCurrentPageId(String(newPage.id));
    } catch (error: any) {
      const errorMsg = error?.response?.data?.error || "Failed to create page";
      toast.error(errorMsg);
    }
  };

  const handleDeletePage = async (pageId: string) => {
    if (!confirm("Are you sure you want to delete this page?")) return;

    try {
      await deletePage.mutateAsync(pageId);
      toast.success("Page deleted!");
      setCurrentPageId(null);
    } catch (error) {
      toast.error("Failed to delete page");
    }
  };

  // Handle data changes from Puck editor
  const handleDataChange = useCallback((newData: any) => {
    setData(newData);
  }, []);

  // Open preview with current data
  const handlePreview = () => {
    setPreviewData(data);
    setPreviewViewport('desktop');
    setShowPreview(true);
  };

  // Open preview in new tab
  const handlePreviewNewTab = () => {
    // Store data in sessionStorage for the preview page
    const previewKey = `preview_${currentPage?.id || 'new'}`;
    sessionStorage.setItem(previewKey, JSON.stringify(data));

    // Open the page in a new tab with preview mode
    const baseUrl = window.location.origin;
    const previewUrl = `${baseUrl}/?preview=${previewKey}`;
    window.open(previewUrl, '_blank');
  };

  if (isLoading || entitlementsLoading) {
    return <div className="flex justify-center p-10"><Loader2 className="animate-spin" /></div>;
  }

  if (!currentPage) {
    return <div>No page found. Please contact support.</div>;
  }

  // Wait for data to be loaded for the current page
  const isDataReady = data && loadedPageId === String(currentPage.id);

  // Display max pages as string for UI (null = unlimited shown as ∞)
  const maxPagesDisplay = maxPagesLimit === null ? '∞' : maxPagesLimit;

  // Calculate iframe style for viewport preview
  const viewportWidth = VIEWPORT_WIDTHS[viewport];
  const iframeStyle = viewportWidth ? {
    maxWidth: `${viewportWidth}px`,
    margin: '0 auto',
    boxShadow: '0 0 0 1px rgba(0,0,0,0.1)',
    borderRadius: '8px',
  } : {};

  return (
    <div className="h-screen flex flex-col">
      {/* Permission Notice for Free Tier */}
      {!canCustomize && (
        <div className="bg-amber-50 dark:bg-amber-900/20 border-b border-amber-200 dark:border-amber-800 px-4 py-3">
          <div className="flex items-center gap-2 text-amber-800 dark:text-amber-200 text-sm">
            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
            </svg>
            <span>
              <strong>Read-Only Mode:</strong> Your current plan does not include site customization.
              <a href="#" className="underline ml-1 hover:text-amber-900 dark:hover:text-amber-100">Upgrade to a paid plan</a> to edit your pages.
            </span>
          </div>
        </div>
      )}

      {/* Page Management Header */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3 flex items-center justify-between">
        <div className="flex items-center gap-4">
          <FileText size={20} className="text-indigo-600" />
          <select
            value={currentPageId || currentPage.id}
            onChange={(e) => handlePageChange(e.target.value)}
            className="px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm focus:ring-2 focus:ring-indigo-500"
          >
            {pages?.map((page: any) => (
              <option key={page.id} value={page.id}>
                {page.title} {page.is_home ? '(Home)' : ''}
              </option>
            ))}
          </select>

          <button
            onClick={() => setShowNewPageModal(true)}
            disabled={!canCreateMore}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            title={canCreateMore ? "Create new page" : `Page limit reached (${pageCount}/${maxPagesDisplay})`}
          >
            <Plus size={16} />
            New Page
          </button>

          {currentPage && !currentPage.is_home && (
            <button
              onClick={() => handleDeletePage(currentPage.id)}
              disabled={!canCustomize}
              className="flex items-center gap-1.5 px-3 py-1.5 bg-red-600 text-white rounded-lg hover:bg-red-700 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              title={canCustomize ? "Delete page" : "Upgrade to delete pages"}
            >
              <Trash2 size={16} />
              Delete
            </button>
          )}

          {/* Divider */}
          <div className="h-6 w-px bg-gray-300 dark:bg-gray-600" />

          {/* Viewport Toggles */}
          <div className="flex items-center gap-1 bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
            <button
              onClick={() => setViewport('desktop')}
              className={`p-1.5 rounded ${
                viewport === 'desktop'
                  ? 'bg-white dark:bg-gray-600 shadow-sm'
                  : 'hover:bg-gray-200 dark:hover:bg-gray-600'
              }`}
              title="Desktop view"
            >
              <Monitor size={18} className={viewport === 'desktop' ? 'text-indigo-600' : 'text-gray-500'} />
            </button>
            <button
              onClick={() => setViewport('tablet')}
              className={`p-1.5 rounded ${
                viewport === 'tablet'
                  ? 'bg-white dark:bg-gray-600 shadow-sm'
                  : 'hover:bg-gray-200 dark:hover:bg-gray-600'
              }`}
              title="Tablet view (768px)"
            >
              <Tablet size={18} className={viewport === 'tablet' ? 'text-indigo-600' : 'text-gray-500'} />
            </button>
            <button
              onClick={() => setViewport('mobile')}
              className={`p-1.5 rounded ${
                viewport === 'mobile'
                  ? 'bg-white dark:bg-gray-600 shadow-sm'
                  : 'hover:bg-gray-200 dark:hover:bg-gray-600'
              }`}
              title="Mobile view (375px)"
            >
              <Smartphone size={18} className={viewport === 'mobile' ? 'text-indigo-600' : 'text-gray-500'} />
            </button>
          </div>

          {/* Page Settings Button */}
          <button
            onClick={() => setShowPageSettings(true)}
            className="p-1.5 rounded hover:bg-gray-100 dark:hover:bg-gray-700"
            title="Page Settings"
          >
            <Settings size={18} className="text-gray-500" />
          </button>

          {/* Divider */}
          <div className="h-6 w-px bg-gray-300 dark:bg-gray-600" />

          {/* Preview Button */}
          <button
            onClick={handlePreview}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 text-sm"
            title="Preview page"
          >
            <Eye size={16} />
            Preview
          </button>

          {/* Divider */}
          <div className="h-6 w-px bg-gray-300 dark:bg-gray-600" />

          {/* Save Draft Button */}
          <button
            onClick={handleSaveDraft}
            disabled={!canCustomize || !hasUnsavedChanges}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 rounded-lg hover:bg-amber-200 dark:hover:bg-amber-800/50 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
            title={hasUnsavedChanges ? "Save draft" : "No unsaved changes"}
          >
            <Save size={16} />
            Save Draft
          </button>

          {/* Discard Draft Button - Only show if there's a draft */}
          {hasDraft && (
            <button
              onClick={handleDiscardDraft}
              disabled={!canCustomize}
              className="flex items-center gap-1.5 px-3 py-1.5 bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 rounded-lg hover:bg-red-200 dark:hover:bg-red-800/50 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              title="Discard draft and revert to published version"
            >
              <RotateCcw size={16} />
              Discard Draft
            </button>
          )}
        </div>

        <div className="flex items-center gap-3">
          {/* Draft Status Indicator */}
          {hasDraft && (
            <span className="flex items-center gap-1.5 px-2 py-1 bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 rounded text-xs font-medium">
              <span className="w-2 h-2 bg-amber-500 rounded-full animate-pulse"></span>
              Draft saved
            </span>
          )}
          {hasUnsavedChanges && !hasDraft && (
            <span className="flex items-center gap-1.5 px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded text-xs font-medium">
              <span className="w-2 h-2 bg-gray-400 rounded-full"></span>
              Unsaved changes
            </span>
          )}
          <span className="text-sm text-gray-600 dark:text-gray-400">
            {pageCount} / {maxPagesDisplay} pages
          </span>
        </div>
      </div>

      {/* New Page Modal */}
      {showNewPageModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md mx-4 p-6">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Create New Page
            </h3>
            <input
              type="text"
              value={newPageTitle}
              onChange={(e) => setNewPageTitle(e.target.value)}
              placeholder="Page Title"
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white mb-4"
              onKeyDown={(e) => e.key === 'Enter' && handleCreatePage()}
              autoFocus
            />
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => {
                  setShowNewPageModal(false);
                  setNewPageTitle('');
                }}
                className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200"
              >
                Cancel
              </button>
              <button
                onClick={handleCreatePage}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
              >
                Create
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Page Settings Modal */}
      {showPageSettings && currentPage && (
        <PageSettingsModal
          page={currentPage}
          onClose={() => setShowPageSettings(false)}
          onSave={async (updates) => {
            try {
              await updatePage.mutateAsync({ id: currentPage.id, data: updates });
              toast.success("Page settings saved!");
              setShowPageSettings(false);
            } catch (error: any) {
              toast.error(error?.response?.data?.error || "Failed to save settings");
            }
          }}
          canEdit={canCustomize}
        />
      )}

      {/* Preview Modal */}
      {showPreview && previewData && (
        <div className="fixed inset-0 bg-black/80 flex flex-col z-50">
          {/* Preview Header */}
          <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3 flex items-center justify-between">
            <div className="flex items-center gap-4">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                Preview: {currentPage?.title}
              </h3>

              {/* Viewport Toggles */}
              <div className="flex items-center gap-1 bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
                <button
                  onClick={() => setPreviewViewport('desktop')}
                  className={`p-1.5 rounded ${
                    previewViewport === 'desktop'
                      ? 'bg-white dark:bg-gray-600 shadow-sm'
                      : 'hover:bg-gray-200 dark:hover:bg-gray-600'
                  }`}
                  title="Desktop view"
                >
                  <Monitor size={18} className={previewViewport === 'desktop' ? 'text-indigo-600' : 'text-gray-500'} />
                </button>
                <button
                  onClick={() => setPreviewViewport('tablet')}
                  className={`p-1.5 rounded ${
                    previewViewport === 'tablet'
                      ? 'bg-white dark:bg-gray-600 shadow-sm'
                      : 'hover:bg-gray-200 dark:hover:bg-gray-600'
                  }`}
                  title="Tablet view (768px)"
                >
                  <Tablet size={18} className={previewViewport === 'tablet' ? 'text-indigo-600' : 'text-gray-500'} />
                </button>
                <button
                  onClick={() => setPreviewViewport('mobile')}
                  className={`p-1.5 rounded ${
                    previewViewport === 'mobile'
                      ? 'bg-white dark:bg-gray-600 shadow-sm'
                      : 'hover:bg-gray-200 dark:hover:bg-gray-600'
                  }`}
                  title="Mobile view (375px)"
                >
                  <Smartphone size={18} className={previewViewport === 'mobile' ? 'text-indigo-600' : 'text-gray-500'} />
                </button>
              </div>
            </div>

            <div className="flex items-center gap-3">
              <button
                onClick={() => setPreviewFullWidth(!previewFullWidth)}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm ${
                  previewFullWidth
                    ? 'bg-indigo-600 text-white hover:bg-indigo-700'
                    : 'text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600'
                }`}
                title={previewFullWidth ? "Show framed preview" : "Show full-width preview"}
              >
                {previewFullWidth ? <Minimize2 size={16} /> : <Maximize2 size={16} />}
                {previewFullWidth ? "Framed" : "Full Width"}
              </button>
              <button
                onClick={handlePreviewNewTab}
                className="flex items-center gap-1.5 px-3 py-1.5 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 text-sm"
                title="Open preview in new tab"
              >
                <ExternalLink size={16} />
                Open in new tab
              </button>
              <button
                onClick={() => setShowPreview(false)}
                className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
                title="Close preview"
              >
                <X size={20} />
              </button>
            </div>
          </div>

          {/* Preview Content */}
          <div className={`flex-1 overflow-auto ${previewFullWidth ? 'bg-white dark:bg-gray-800' : 'bg-gray-100 dark:bg-gray-900 p-4'}`}>
            <div
              className={previewFullWidth
                ? 'min-h-full'
                : 'mx-auto bg-white dark:bg-gray-800 min-h-full shadow-xl rounded-lg overflow-hidden'
              }
              style={{
                width: previewFullWidth ? '100%' : (VIEWPORT_WIDTHS[previewViewport] || '100%'),
                maxWidth: '100%',
                transition: 'width 0.3s ease-in-out',
              }}
            >
              <Render config={renderConfig} data={previewData} />
            </div>
          </div>
        </div>
      )}

      {/* Puck Editor with viewport width */}
      <div className="flex-1 overflow-hidden" style={iframeStyle}>
        {isDataReady ? (
          <Puck
            key={`puck-${loadedPageId}`}
            config={editorConfig}
            data={data}
            onPublish={handlePublish}
            onChange={handleDataChange}
          />
        ) : (
          <div className="flex items-center justify-center h-full bg-gray-50 dark:bg-gray-900">
            <div className="text-center">
              <Loader2 className="w-8 h-8 animate-spin text-indigo-600 mx-auto mb-2" />
              <p className="text-gray-600 dark:text-gray-400">Loading page...</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Page Settings Modal Component
interface PageSettingsModalProps {
  page: any;
  onClose: () => void;
  onSave: (updates: any) => Promise<void>;
  canEdit: boolean;
}

function PageSettingsModal({ page, onClose, onSave, canEdit }: PageSettingsModalProps) {
  const [settings, setSettings] = useState({
    title: page.title || '',
    meta_title: page.meta_title || '',
    meta_description: page.meta_description || '',
    og_image: page.og_image || '',
    canonical_url: page.canonical_url || '',
    noindex: page.noindex || false,
    include_in_nav: page.include_in_nav ?? true,
    hide_chrome: page.hide_chrome || false,
  });
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    setSaving(true);
    try {
      await onSave(settings);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 overflow-y-auto">
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-lg mx-4 my-8 max-h-[90vh] overflow-y-auto">
        <div className="sticky top-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
            Page Settings
          </h3>
        </div>

        <div className="p-6 space-y-6">
          {/* Basic Settings */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Page Title
            </label>
            <input
              type="text"
              value={settings.title}
              onChange={(e) => setSettings({ ...settings, title: e.target.value })}
              disabled={!canEdit}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50"
            />
          </div>

          {/* SEO Settings */}
          <div className="border-t border-gray-200 dark:border-gray-700 pt-6">
            <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 uppercase tracking-wide">
              SEO Settings
            </h4>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Meta Title
                </label>
                <input
                  type="text"
                  value={settings.meta_title}
                  onChange={(e) => setSettings({ ...settings, meta_title: e.target.value })}
                  disabled={!canEdit}
                  placeholder="Defaults to page title"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Meta Description
                </label>
                <textarea
                  value={settings.meta_description}
                  onChange={(e) => setSettings({ ...settings, meta_description: e.target.value })}
                  disabled={!canEdit}
                  rows={3}
                  placeholder="Brief description for search engines"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  OG Image URL
                </label>
                <input
                  type="url"
                  value={settings.og_image}
                  onChange={(e) => setSettings({ ...settings, og_image: e.target.value })}
                  disabled={!canEdit}
                  placeholder="https://..."
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Canonical URL
                </label>
                <input
                  type="url"
                  value={settings.canonical_url}
                  onChange={(e) => setSettings({ ...settings, canonical_url: e.target.value })}
                  disabled={!canEdit}
                  placeholder="https://..."
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50"
                />
              </div>

              <label className="flex items-center gap-3">
                <input
                  type="checkbox"
                  checked={settings.noindex}
                  onChange={(e) => setSettings({ ...settings, noindex: e.target.checked })}
                  disabled={!canEdit}
                  className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">
                  Hide from search engines (noindex)
                </span>
              </label>
            </div>
          </div>

          {/* Navigation & Display */}
          <div className="border-t border-gray-200 dark:border-gray-700 pt-6">
            <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-4 uppercase tracking-wide">
              Navigation & Display
            </h4>

            <div className="space-y-4">
              <label className="flex items-center gap-3">
                <input
                  type="checkbox"
                  checked={settings.include_in_nav}
                  onChange={(e) => setSettings({ ...settings, include_in_nav: e.target.checked })}
                  disabled={!canEdit}
                  className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">
                  Include in site navigation
                </span>
              </label>

              <label className="flex items-center gap-3">
                <input
                  type="checkbox"
                  checked={settings.hide_chrome}
                  onChange={(e) => setSettings({ ...settings, hide_chrome: e.target.checked })}
                  disabled={!canEdit}
                  className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">
                  Hide header/footer (landing page mode)
                </span>
              </label>
            </div>
          </div>
        </div>

        <div className="sticky bottom-0 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-6 py-4 flex gap-3 justify-end">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={!canEdit || saving}
            className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
          >
            {saving ? 'Saving...' : 'Save Settings'}
          </button>
        </div>
      </div>
    </div>
  );
}

export default PageEditor;
