/**
 * Landing Page Design Engine
 *
 * Generates explicit visual design specifications for every enabled landing page
 * section using AI. The output is a structured `LandingPageSectionDesign` per
 * section that controls layout, image placement, text alignment, background style,
 * visual style, spacing, CTA style, and responsive behaviour.
 *
 * This runs BEFORE the HTML generation step so the AI building the page has
 * authoritative design instructions per section.
 */

import { generateWithAI } from '../utils/aiProvider';
import { parseJsonFromAI } from './aiContext/parseJsonFromAI';
import type { LandingPageSection, LandingPageSectionDesign } from './aiContext/landingPageWebsitePrompts';

export interface DesignEngineInputs {
  pageName: string;
  pageType?: string;
  primaryGoal?: string;
  companyName?: string;
  companyIndustry?: string;
  brandVoice?: string;
  primaryColor?: string;
  accentColor?: string;
  headingFont?: string;
  bodyFont?: string;
  sections: LandingPageSection[];
}

export interface SectionDesignResult {
  sectionId: string;
  sectionType: string;
  design: LandingPageSectionDesign;
}

export interface DesignEngineResult {
  designs: SectionDesignResult[];
  provider: string;
  aiModel: string;
  tokensUsed?: number;
  latencyMs?: number;
}

// ============================================
// PROMPT BUILDERS
// ============================================

function buildDesignSystemPrompt(): string {
  return `You are a senior landing page UI/UX designer. Your job is to produce explicit visual design specifications for each section of a landing page.

You MUST respond with ONLY a valid JSON object. No markdown code fences, no commentary before or after.

JSON structure:
{
  "designs": [
    {
      "sectionId": "string",
      "sectionType": "string",
      "design": {
        "layout": "one of: left-right | right-left | full-width | split | centered | asymmetric",
        "imagePlacement": "one of: left | right | background | top | bottom | inline | none",
        "textAlignment": "one of: left | center | right",
        "backgroundStyle": "one of: default | gradient | solid | image | pattern | glass | dark | light",
        "visualStyle": "one of: cards | minimal | hero | grid | list | testimonial | stats | pricing | timeline | gallery",
        "spacing": "one of: compact | normal | generous",
        "ctaStyle": "one of: button | inline | banner | floating | none",
        "responsiveBehaviour": {
          "desktop": "brief description of desktop layout",
          "tablet": "brief description of tablet layout",
          "mobile": "brief description of mobile layout"
        }
      }
    }
  ]
}

RULES:
- Choose layout based on section TYPE and CONTENT:
  * Hero → full-width or left-right (text left, visual right)
  * Features → grid (3-col cards) or left-right alternating
  * Benefits → left-right alternating (odd left, even right)
  * Testimonials → cards (2-3 column grid) or centered carousel
  * Pricing → cards (3-column grid)
  * Stats/Numbers → stats (4-column grid) or asymmetric split
  * CTA → full-width banner or centered with gradient background
  * How It Works → timeline (numbered steps) or grid
  * Case Studies → cards or left-right split
  * FAQs → list (accordion style) or minimal centered
  * Founder Story → left-right (portrait left, story right) or centered
  * Comparison Table → full-width table or cards
  * Video Block → centered or full-width with background
  * Lead Form → split (text left, form right) or centered
  * Social Proof → logo strip or grid
  * Pain Points → full-width with icon grid
  * Solution Explanation → left-right or centered
  * Product Walkthrough → grid or split
  * Offer Breakdown → cards or grid
  * Bonuses → cards or grid
  * Guarantee → centered banner or full-width
  * Client Logos → logo strip centered
  * Custom → infer from content

- Choose imagePlacement based on whether the section naturally needs imagery:
  * Sections with product visuals → left or right
  * Hero → background (gradient overlay) or right
  * Testimonials → none (use avatar placeholders)
  * Stats → none (use large numbers)
  * CTA → none or background (subtle texture)
  * Pricing → none
  * Features → inline (icon + text) or top (card image)
  * Benefits → left/right alternating
  * Case Studies → left or top
  * Founder Story → left (portrait)

- Choose backgroundStyle to create visual rhythm:
  * Alternate sections: odd = default, even = section-alt (glass or gradient)
  * Hero → gradient or glass
  * CTA → gradient
  * Testimonials → glass
  * Stats → dark or gradient
  * Final sections before footer → gradient

- Choose textAlignment:
  * Hero headlines → center or left (depends on layout)
  * Section headers → center
  * Feature cards → left
  * Testimonials → left
  * Pricing cards → center
  * CTA → center

- Choose visualStyle:
  * Feature-heavy sections → cards
  * Storytelling sections → minimal or timeline
  * Social proof → testimonial
  * Data-heavy → stats
  * Product showcase → grid or gallery
  * Simple text sections → minimal

- Choose spacing:
  * Dense sections (logos, stats) → compact
  * Standard content → normal
  * Hero, CTA, testimonials → generous

- Choose ctaStyle:
  * Primary conversion sections → button (prominent)
  * Embedded in content → inline
  * Final CTA → banner
  * Sticky → floating (only if requested)

- ResponsiveBehaviour MUST describe actual layout changes:
  * Desktop: multi-column grids, side-by-side splits, hover states
  * Tablet: 2-column grids, collapsible sidebars, reduced padding
  * Mobile: single column, stacked content, full-width CTAs, hamburger nav

- Use the brand colours and industry context to inform style choices.
- Keep descriptions in responsiveBehaviour brief but specific (under 20 words each).`;
}

function buildDesignUserPrompt(inputs: DesignEngineInputs): string {
  const enabledSections = inputs.sections.filter(s => s.enabled !== false).slice(0, 8);

  const sectionDescriptions = enabledSections.map((s, i) => {
    const parts: string[] = [`${i + 1}. Section ID: "${s.type}"`];
    parts.push(`   Name: ${s.name}`);
    if (s.headline) parts.push(`   Headline: ${s.headline}`);
    if (s.subheadline) parts.push(`   Subheadline: ${s.subheadline}`);
    if (s.description) {
      const desc = s.description.length > 120 ? s.description.slice(0, 120) + '…' : s.description;
      parts.push(`   Description: ${desc}`);
    }
    if (s.cta) parts.push(`   CTA: ${s.cta}`);
    if (s.bulletPoints?.length) parts.push(`   Bullet Points: ${s.bulletPoints.slice(0, 3).join('; ')}`);
    if (s.media?.length) parts.push(`   Has user images: Yes (${s.media.length})`);
    return parts.join('\n');
  }).join('\n\n');

  return `Generate visual design specifications for each section of this landing page.

PAGE CONTEXT:
- Page Name: ${inputs.pageName || 'Landing Page'}
- Page Type: ${inputs.pageType || 'general'}
- Primary Goal: ${inputs.primaryGoal || 'conversion'}
- Company: ${inputs.companyName || 'Unknown'}
- Industry: ${inputs.companyIndustry || 'General'}
- Brand Voice: ${inputs.brandVoice || 'professional'}
- Primary Colour: ${inputs.primaryColor || '#7C6BF0'}
- Accent Colour: ${inputs.accentColor || '#C8FF2E'}
- Heading Font: ${inputs.headingFont || 'Inter'}
- Body Font: ${inputs.bodyFont || 'Inter'}

SECTIONS (${enabledSections.length}):
${sectionDescriptions}

Generate design specs for ALL sections above. Return ONLY valid JSON.`;
}

// ============================================
// DESIGN ENGINE
// ============================================

export async function generateLandingPageDesigns(
  inputs: DesignEngineInputs
): Promise<DesignEngineResult> {
  const startTime = Date.now();

  const systemPrompt = buildDesignSystemPrompt();
  const userPrompt = buildDesignUserPrompt(inputs);

  const result = await generateWithAI(
    userPrompt,
    systemPrompt,
    8000,
    0.7,
    'json'
  );

  const parsed = parseJsonFromAI(result.content);
  if (!parsed || !Array.isArray(parsed.designs)) {
    console.warn('[LandingPageDesignEngine] Failed to parse design specs, using defaults');
    return {
      designs: inputs.sections.filter(s => s.enabled !== false).map(s => ({
        sectionId: s.type,
        sectionType: s.type,
        design: getDefaultDesign(s.type),
      })),
      provider: result.provider,
      aiModel: result.model,
      tokensUsed: result.tokenUsage?.totalTokens,
      latencyMs: Date.now() - startTime,
    };
  }

  const designs: SectionDesignResult[] = parsed.designs
    .filter((d: any) => d && d.design)
    .map((d: any) => ({
      sectionId: String(d.sectionId || d.sectionType || ''),
      sectionType: String(d.sectionType || d.sectionId || ''),
      design: normaliseDesign(d.design),
    }));

  return {
    designs,
    provider: result.provider,
    aiModel: result.model,
    tokensUsed: result.tokenUsage?.totalTokens,
    latencyMs: Date.now() - startTime,
  };
}

// ============================================
// DEFAULTS & NORMALISATION
// ============================================

function normaliseDesign(raw: any): LandingPageSectionDesign {
  const validLayout = ['left-right', 'right-left', 'full-width', 'split', 'centered', 'asymmetric'];
  const validImage = ['left', 'right', 'background', 'top', 'bottom', 'inline', 'none'];
  const validAlign = ['left', 'center', 'right'];
  const validBg = ['default', 'gradient', 'solid', 'image', 'pattern', 'glass', 'dark', 'light'];
  const validVisual = ['cards', 'minimal', 'hero', 'grid', 'list', 'testimonial', 'stats', 'pricing', 'timeline', 'gallery'];
  const validSpacing = ['compact', 'normal', 'generous'];
  const validCta = ['button', 'inline', 'banner', 'floating', 'none'];

  return {
    layout: validLayout.includes(raw?.layout) ? raw.layout : 'full-width',
    imagePlacement: validImage.includes(raw?.imagePlacement) ? raw.imagePlacement : 'none',
    textAlignment: validAlign.includes(raw?.textAlignment) ? raw.textAlignment : 'left',
    backgroundStyle: validBg.includes(raw?.backgroundStyle) ? raw.backgroundStyle : 'default',
    visualStyle: validVisual.includes(raw?.visualStyle) ? raw.visualStyle : 'minimal',
    spacing: validSpacing.includes(raw?.spacing) ? raw.spacing : 'normal',
    ctaStyle: validCta.includes(raw?.ctaStyle) ? raw.ctaStyle : 'button',
    responsiveBehaviour: {
      desktop: typeof raw?.responsiveBehaviour?.desktop === 'string' ? raw.responsiveBehaviour.desktop : 'Multi-column grid with side-by-side content.',
      tablet: typeof raw?.responsiveBehaviour?.tablet === 'string' ? raw.responsiveBehaviour.tablet : 'Two-column grid, stacked where needed.',
      mobile: typeof raw?.responsiveBehaviour?.mobile === 'string' ? raw.responsiveBehaviour.mobile : 'Single column, full-width, stacked vertically.',
    },
  };
}

function getDefaultDesign(sectionType: string): LandingPageSectionDesign {
  const defaults: Record<string, LandingPageSectionDesign> = {
    hero: {
      layout: 'left-right',
      imagePlacement: 'right',
      textAlignment: 'left',
      backgroundStyle: 'gradient',
      visualStyle: 'hero',
      spacing: 'generous',
      ctaStyle: 'button',
      responsiveBehaviour: {
        desktop: 'Two-column split: text left, visual right.',
        tablet: 'Stacked: text top, visual bottom.',
        mobile: 'Single column, centered text, visual below.',
      },
    },
    features: {
      layout: 'full-width',
      imagePlacement: 'inline',
      textAlignment: 'left',
      backgroundStyle: 'default',
      visualStyle: 'cards',
      spacing: 'normal',
      ctaStyle: 'button',
      responsiveBehaviour: {
        desktop: 'Three-column card grid with icon, heading, description.',
        tablet: 'Two-column card grid.',
        mobile: 'Single column, stacked cards.',
      },
    },
    benefits: {
      layout: 'left-right',
      imagePlacement: 'right',
      textAlignment: 'left',
      backgroundStyle: 'glass',
      visualStyle: 'minimal',
      spacing: 'normal',
      ctaStyle: 'inline',
      responsiveBehaviour: {
        desktop: 'Alternating two-column layout with text and visuals.',
        tablet: 'Stacked two-column.',
        mobile: 'Single column, image above text.',
      },
    },
    testimonials: {
      layout: 'full-width',
      imagePlacement: 'none',
      textAlignment: 'left',
      backgroundStyle: 'glass',
      visualStyle: 'testimonial',
      spacing: 'generous',
      ctaStyle: 'none',
      responsiveBehaviour: {
        desktop: 'Two to three column testimonial card grid.',
        tablet: 'Two column grid.',
        mobile: 'Single column, stacked cards.',
      },
    },
    pricing: {
      layout: 'full-width',
      imagePlacement: 'none',
      textAlignment: 'center',
      backgroundStyle: 'default',
      visualStyle: 'pricing',
      spacing: 'generous',
      ctaStyle: 'button',
      responsiveBehaviour: {
        desktop: 'Three-column pricing card grid.',
        tablet: 'Two-column grid with highlighted plan centred.',
        mobile: 'Single column, stacked pricing cards.',
      },
    },
    'cta-section': {
      layout: 'centered',
      imagePlacement: 'none',
      textAlignment: 'center',
      backgroundStyle: 'gradient',
      visualStyle: 'hero',
      spacing: 'generous',
      ctaStyle: 'banner',
      responsiveBehaviour: {
        desktop: 'Centered banner with large headline and CTA button.',
        tablet: 'Centered, reduced padding.',
        mobile: 'Single column, full-width CTA button.',
      },
    },
  };

  return defaults[sectionType] || {
    layout: 'full-width',
    imagePlacement: 'none',
    textAlignment: 'left',
    backgroundStyle: 'default',
    visualStyle: 'minimal',
    spacing: 'normal',
    ctaStyle: 'button',
    responsiveBehaviour: {
      desktop: 'Full-width content block.',
      tablet: 'Full-width with reduced margins.',
      mobile: 'Single column, full-width.',
    },
  };
}
