"use client";

/**
 * Center preview canvas. Renders the current page via the section
 * renderer, frames each section with click-to-select, and exposes
 * hover controls (duplicate, delete, drag handle placeholder). A
 * desktop/mobile toggle clamps the canvas width for responsive checks.
 */

import { useState } from "react";
import { Monitor, Smartphone, Copy, Trash2, GripVertical } from "lucide-react";
import { renderSection } from "@/lib/page-studio/section-renderer";
import type { Section, Branding } from "@/lib/page-studio/section-registry";

type ViewportMode = "desktop" | "mobile";

interface Props {
  sections: Section[];
  branding: Branding;
  selectedId: string | null;
  onSelect: (id: string | null) => void;
  onDuplicate: (id: string) => void;
  onDelete: (id: string) => void;
}

export default function PreviewCanvas({ sections, branding, selectedId, onSelect, onDuplicate, onDelete }: Props) {
  const [viewport, setViewport] = useState<ViewportMode>("desktop");

  return (
    <div className="flex flex-col h-full bg-slate-100">
      {/* Toolbar */}
      <div className="px-4 py-2.5 border-b border-slate-200 bg-white flex items-center justify-center gap-2">
        <div className="flex bg-slate-100 rounded-lg p-0.5">
          {(["desktop", "mobile"] as const).map((v) => {
            const Icon = v === "desktop" ? Monitor : Smartphone;
            return (
              <button
                key={v}
                onClick={() => setViewport(v)}
                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-semibold capitalize transition-colors ${
                  viewport === v ? "bg-white text-slate-900 shadow-sm" : "text-slate-500 hover:text-slate-700"
                }`}
              >
                <Icon className="w-3.5 h-3.5" /> {v}
              </button>
            );
          })}
        </div>
      </div>

      {/* Canvas */}
      <div className="flex-1 overflow-auto py-6 px-6" onClick={() => onSelect(null)}>
        <div
          className={`mx-auto bg-white shadow-lg rounded-xl overflow-hidden transition-all duration-300 ${
            viewport === "mobile" ? "max-w-sm" : "max-w-5xl"
          }`}
          onClick={(e) => e.stopPropagation()}
        >
          {sections.length === 0 ? (
            <div className="py-24 text-center">
              <p className="text-sm font-semibold text-slate-600 mb-1">Empty page</p>
              <p className="text-xs text-slate-400">Add a section from the left sidebar to get started.</p>
            </div>
          ) : (
            sections.map((section) => (
              <SectionFrame
                key={section.id}
                section={section}
                branding={branding}
                selected={section.id === selectedId}
                onSelect={() => onSelect(section.id)}
                onDuplicate={() => onDuplicate(section.id)}
                onDelete={() => onDelete(section.id)}
              />
            ))
          )}
        </div>
      </div>
    </div>
  );
}

interface FrameProps {
  section: Section;
  branding: Branding;
  selected: boolean;
  onSelect: () => void;
  onDuplicate: () => void;
  onDelete: () => void;
}

function SectionFrame({ section, branding, selected, onSelect, onDuplicate, onDelete }: FrameProps) {
  const [hovered, setHovered] = useState(false);
  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      onClick={(e) => { e.stopPropagation(); onSelect(); }}
      className={`relative ${selected ? "ring-2 ring-brand-500 ring-inset" : hovered ? "ring-1 ring-brand-300 ring-inset" : ""}`}
    >
      {(hovered || selected) && (
        <div className="absolute top-2 right-2 z-10 flex items-center gap-1 bg-white rounded-lg shadow-md border border-slate-200 p-1">
          <button
            className="w-6 h-6 rounded-md flex items-center justify-center text-slate-400 hover:bg-slate-100 hover:text-slate-700"
            title="Drag to reorder (use left sidebar)"
            onClick={(e) => e.stopPropagation()}
          >
            <GripVertical className="w-3.5 h-3.5" />
          </button>
          <button
            className="w-6 h-6 rounded-md flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800"
            title="Duplicate"
            onClick={(e) => { e.stopPropagation(); onDuplicate(); }}
          >
            <Copy className="w-3.5 h-3.5" />
          </button>
          <button
            className="w-6 h-6 rounded-md flex items-center justify-center text-red-500 hover:bg-red-50"
            title="Delete"
            onClick={(e) => { e.stopPropagation(); onDelete(); }}
          >
            <Trash2 className="w-3.5 h-3.5" />
          </button>
        </div>
      )}
      {renderSection(section, branding, "edit")}
    </div>
  );
}
