/**
 * Page Studio — Section Block Registry
 * -------------------------------------
 * Single source of truth for every block type the editor supports.
 * The editor uses this to render the "add block" picker, the AI uses
 * it to pick + populate blocks, and the renderer uses `defaultContent`
 * as a safe fallback when an AI-generated section is missing a field.
 *
 * Adding a new block type:
 *   1. Add an entry to BLOCKS below with a stable id, category, and
 *      a defaultContent shape.
 *   2. Implement a renderer in section-renderer.tsx (or let it fall
 *      through to the placeholder stub).
 *   3. Optionally extend the AI's prompt templates to emit it.
 */

export type SectionCategory = "layout" | "trust" | "content" | "conversion" | "media";

export interface SectionBlockDefinition {
  id: string;
  name: string;
  category: SectionCategory;
  description: string;
  /** lucide-react icon name — resolved in the UI layer so this module stays dep-free */
  icon: string;
  defaultContent: Record<string, unknown>;
}

export interface Section {
  /** Stable unique id per section instance (separate from the block type id) */
  id: string;
  /** Block type id — must match an entry in BLOCKS */
  type: string;
  /** Arbitrary, block-specific content — the shape matches defaultContent */
  content: Record<string, unknown>;
}

export interface Branding {
  primaryColor: string;
  secondaryColor: string;
  accentColor: string;
  fontFamily: string;
  logoUrl?: string | null;
  textColor?: string;
  backgroundColor?: string;
}

export const DEFAULT_BRANDING: Branding = {
  primaryColor: "#0F172A",
  secondaryColor: "#7C3AED",
  accentColor: "#10B981",
  fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif",
  textColor: "#0F172A",
  backgroundColor: "#FFFFFF",
};

// ─── Block definitions ────────────────────────────────────────────────────────

export const BLOCKS: SectionBlockDefinition[] = [

  // ── Layout ──
  {
    id: "hero",
    name: "Hero",
    category: "layout",
    description: "Full-bleed headline with supporting copy and a single call to action.",
    icon: "LayoutTemplate",
    defaultContent: {
      headline: "Your Headline Here",
      subheadline: "Supporting text that explains what you offer and why it matters.",
      ctaText: "Get Started",
      ctaUrl: "#contact",
      backgroundColor: "#1E293B",
      textColor: "#FFFFFF",
      backgroundImage: null,
    },
  },
  {
    id: "hero_with_form",
    name: "Hero with Form",
    category: "layout",
    description: "Hero paired with an inline lead-capture form.",
    icon: "FormInput",
    defaultContent: {
      headline: "Start Your Free Trial",
      subheadline: "No credit card required. Cancel anytime.",
      formTitle: "Create your account",
      fields: [
        { name: "name", label: "Full name", type: "text", required: true },
        { name: "email", label: "Work email", type: "email", required: true },
      ],
      submitText: "Get Started",
      backgroundColor: "#0F172A",
      textColor: "#FFFFFF",
    },
  },
  {
    id: "hero_with_video",
    name: "Hero with Video",
    category: "layout",
    description: "Hero with a background or featured video.",
    icon: "Video",
    defaultContent: {
      headline: "See It In Action",
      subheadline: "A 60-second walkthrough of the product.",
      videoUrl: "",
      posterUrl: "",
      ctaText: "Watch Demo",
      ctaUrl: "#demo",
    },
  },

  // ── Trust ──
  {
    id: "trust_bar",
    name: "Trust Bar",
    category: "trust",
    description: "Row of customer logos or trust badges.",
    icon: "ShieldCheck",
    defaultContent: {
      headline: "Trusted by leading teams",
      logos: [
        { name: "Acme", url: "" },
        { name: "Globex", url: "" },
        { name: "Initech", url: "" },
        { name: "Umbrella", url: "" },
        { name: "Wayne", url: "" },
      ],
    },
  },
  {
    id: "testimonials",
    name: "Testimonials",
    category: "trust",
    description: "Customer quotes with name, role, and optional photo.",
    icon: "MessageSquareQuote",
    defaultContent: {
      headline: "What our customers say",
      items: [
        { quote: "Game-changing. We saw results in the first week.", name: "Jane Smith", role: "CEO, Acme Inc.", avatarUrl: "" },
        { quote: "The only tool our team actually sticks with.", name: "John Doe", role: "Marketing Lead, Globex", avatarUrl: "" },
      ],
    },
  },
  {
    id: "logo_bar",
    name: "Logo Bar",
    category: "trust",
    description: "Simple horizontal strip of partner or client logos.",
    icon: "Images",
    defaultContent: {
      headline: "As featured in",
      logos: [{ name: "Forbes", url: "" }, { name: "TechCrunch", url: "" }, { name: "WSJ", url: "" }],
    },
  },
  {
    id: "reviews",
    name: "Reviews",
    category: "trust",
    description: "Star-rated customer reviews with source attribution.",
    icon: "Star",
    defaultContent: {
      headline: "Rated 4.9/5 by customers",
      averageRating: 4.9,
      totalReviews: 1247,
      items: [
        { rating: 5, text: "Best decision we made this year.", name: "Sarah L.", source: "Google" },
        { rating: 5, text: "Responsive team and amazing results.", name: "Mike R.", source: "G2" },
      ],
    },
  },
  {
    id: "stats_row",
    name: "Stats Row",
    category: "trust",
    description: "Big-number stats that demonstrate traction or results.",
    icon: "BarChart3",
    defaultContent: {
      headline: "Numbers that matter",
      items: [
        { value: "10k+", label: "Happy customers" },
        { value: "99.9%", label: "Uptime" },
        { value: "24/7", label: "Support" },
        { value: "50+", label: "Countries" },
      ],
    },
  },

  // ── Content ──
  {
    id: "features_grid",
    name: "Features Grid",
    category: "content",
    description: "Grid of feature cards with icon, title, and description.",
    icon: "LayoutGrid",
    defaultContent: {
      headline: "Our Features",
      subheadline: "Everything you need to grow faster.",
      items: [
        { title: "Feature One", description: "Short description of what this feature does.", icon: "Star" },
        { title: "Feature Two", description: "Short description of what this feature does.", icon: "Zap" },
        { title: "Feature Three", description: "Short description of what this feature does.", icon: "Target" },
        { title: "Feature Four", description: "Short description of what this feature does.", icon: "Shield" },
      ],
    },
  },
  {
    id: "benefits_list",
    name: "Benefits List",
    category: "content",
    description: "Alternating image + text benefit rows.",
    icon: "ListChecks",
    defaultContent: {
      headline: "Why choose us",
      items: [
        { title: "Save time", description: "Automate the repetitive work so your team can focus.", icon: "Clock" },
        { title: "Scale safely", description: "Enterprise-grade security from day one.", icon: "Shield" },
        { title: "Prove ROI", description: "Clear metrics on what's working and what isn't.", icon: "TrendingUp" },
      ],
    },
  },
  {
    id: "services_list",
    name: "Services List",
    category: "content",
    description: "List of services offered with short descriptions.",
    icon: "Briefcase",
    defaultContent: {
      headline: "What we do",
      items: [
        { title: "Strategy", description: "Positioning, messaging, and go-to-market." },
        { title: "Design", description: "Brand, web, and product design that converts." },
        { title: "Growth", description: "Paid, organic, and lifecycle marketing." },
      ],
    },
  },
  {
    id: "about_section",
    name: "About",
    category: "content",
    description: "About-us block with headline, body copy, and optional image.",
    icon: "Info",
    defaultContent: {
      headline: "About Us",
      body: "A short paragraph about your company, mission, and what makes you different.",
      imageUrl: "",
    },
  },
  {
    id: "team_section",
    name: "Team",
    category: "content",
    description: "Grid of team members with photo, name, and role.",
    icon: "Users",
    defaultContent: {
      headline: "Meet the team",
      items: [
        { name: "Alex Morgan", role: "Founder & CEO", photoUrl: "" },
        { name: "Sam Patel", role: "Head of Product", photoUrl: "" },
        { name: "Jordan Lee", role: "Head of Design", photoUrl: "" },
      ],
    },
  },
  {
    id: "process_steps",
    name: "Process Steps",
    category: "content",
    description: "Numbered step-by-step process with short descriptions.",
    icon: "ListOrdered",
    defaultContent: {
      headline: "How it works",
      items: [
        { step: 1, title: "Sign up", description: "Create your free account in under a minute." },
        { step: 2, title: "Connect your data", description: "One-click integrations with the tools you already use." },
        { step: 3, title: "See results", description: "Insights and recommendations within 24 hours." },
      ],
    },
  },

  // ── Conversion ──
  {
    id: "cta_banner",
    name: "CTA Banner",
    category: "conversion",
    description: "Full-width call-to-action strip with button.",
    icon: "Megaphone",
    defaultContent: {
      headline: "Ready to get started?",
      subheadline: "Join thousands of teams already using us to grow faster.",
      ctaText: "Start Free Trial",
      ctaUrl: "#signup",
      backgroundColor: "#0F172A",
      textColor: "#FFFFFF",
    },
  },
  {
    id: "contact_form",
    name: "Contact Form",
    category: "conversion",
    description: "Standard contact form with configurable fields.",
    icon: "Mail",
    defaultContent: {
      headline: "Get In Touch",
      subheadline: "We'll respond within one business day.",
      fields: [
        { name: "name", label: "Name", type: "text", required: true },
        { name: "email", label: "Email", type: "email", required: true },
        { name: "phone", label: "Phone", type: "tel", required: false },
        { name: "message", label: "Message", type: "textarea", required: true },
      ],
      submitText: "Send Message",
    },
  },
  {
    id: "phone_cta",
    name: "Phone CTA",
    category: "conversion",
    description: "Big click-to-call phone number block.",
    icon: "Phone",
    defaultContent: {
      headline: "Call us now",
      subheadline: "Speak with a real person, Monday–Friday 9–5.",
      phoneNumber: "+1 (555) 123-4567",
      backgroundColor: "#10B981",
      textColor: "#FFFFFF",
    },
  },
  {
    id: "faq",
    name: "FAQ",
    category: "conversion",
    description: "Collapsible list of frequently asked questions.",
    icon: "HelpCircle",
    defaultContent: {
      headline: "Frequently Asked Questions",
      items: [
        { question: "How does it work?", answer: "A short answer that explains the core product flow." },
        { question: "How much does it cost?", answer: "Pricing starts at $49/mo. See our pricing page for details." },
        { question: "Do you offer a free trial?", answer: "Yes — 14 days, no credit card required." },
      ],
    },
  },
  {
    id: "pricing_table",
    name: "Pricing Table",
    category: "conversion",
    description: "Side-by-side pricing tiers with features and CTAs.",
    icon: "Tag",
    defaultContent: {
      headline: "Simple, honest pricing",
      tiers: [
        { name: "Starter", price: "$49", period: "/mo", features: ["Up to 5 users", "Email support", "Basic analytics"], ctaText: "Start Free Trial", ctaUrl: "#signup", featured: false },
        { name: "Pro", price: "$149", period: "/mo", features: ["Up to 25 users", "Priority support", "Advanced analytics", "Custom integrations"], ctaText: "Start Free Trial", ctaUrl: "#signup", featured: true },
        { name: "Enterprise", price: "Custom", period: "", features: ["Unlimited users", "Dedicated success manager", "SLA & SSO"], ctaText: "Contact Sales", ctaUrl: "#contact", featured: false },
      ],
    },
  },

  // ── Media ──
  {
    id: "image_gallery",
    name: "Image Gallery",
    category: "media",
    description: "Grid of images with optional captions.",
    icon: "Image",
    defaultContent: {
      headline: "Gallery",
      images: [
        { url: "", caption: "" },
        { url: "", caption: "" },
        { url: "", caption: "" },
      ],
    },
  },
  {
    id: "video_section",
    name: "Video Section",
    category: "media",
    description: "Embedded video with optional heading.",
    icon: "PlaySquare",
    defaultContent: {
      headline: "Watch the demo",
      videoUrl: "",
      posterUrl: "",
    },
  },
];

// ─── Lookup helpers ───────────────────────────────────────────────────────────

const BLOCKS_BY_ID: Record<string, SectionBlockDefinition> = Object.fromEntries(
  BLOCKS.map((b) => [b.id, b]),
);

export function getBlockDefinition(type: string): SectionBlockDefinition | undefined {
  return BLOCKS_BY_ID[type];
}

export function getBlocksByCategory(category: SectionCategory): SectionBlockDefinition[] {
  return BLOCKS.filter((b) => b.category === category);
}

/**
 * Create a new Section instance for the editor — fills in the block's
 * defaultContent and assigns a stable unique id.
 */
export function createSection(type: string, idOverride?: string): Section {
  const def = BLOCKS_BY_ID[type];
  if (!def) throw new Error(`Unknown section block type: ${type}`);
  return {
    id: idOverride ?? `sec_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
    type,
    content: JSON.parse(JSON.stringify(def.defaultContent)) as Record<string, unknown>,
  };
}
