---
// Real Content Demo Generator - Uses actual content fragments from database
import AdminLayout from '@/layouts/AdminLayout.astro';
import { pool } from '@/lib/db';

// Get site
const { rows: sites } = await pool.query<{id: string; domain: string}>('SELECT id, domain FROM sites LIMIT 1');
const site = sites[0];

if (!site) {
  return Astro.redirect('/admin/sites');
}

// Get ALL content fragments
const { rows: fragments } = await pool.query<{fragment_type: string; content_body: string; word_count: number}>(
  'SELECT fragment_type, content_body, word_count FROM content_fragments ORDER BY date_created'
);

// Get article template
const { rows: templates } = await pool.query<{name: string; structure_json: string[]}>(
  'SELECT name, structure_json FROM article_templates LIMIT 1'
);

const template = templates[0];

// Build complete sales page from fragments
let salesPageHTML = '';

if (template && fragments.length > 0) {
  // Create a map of fragments by type
  const fragmentMap = new Map();
  fragments.forEach(frag => {
    fragmentMap.set(frag.fragment_type, frag.content_body);
  });
  
  // Build page following template structure
  salesPageHTML = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Aesthetic Practice CEO Report - Stop Wasting $50,000 on Google Ads</title>
  <meta name="description" content="Essential report for aesthetic practice CEOs in Alabama. Learn the critical flaw in standard agency funnels and discover the Conversion Architecture system.">
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
      line-height: 1.6;
      color: #1a1a1a;
      background: #ffffff;
    }
    .container {
      max-width: 800px;
      margin: 0 auto;
      padding: 40px 20px;
    }
    h1 {
      font-size: 2.5rem;
      font-weight: 800;
      margin-bottom: 1.5rem;
      line-height: 1.2;
      color: #111;
    }
    h2 {
      font-size: 1.75rem;
      font-weight: 700;
      margin-top: 3rem;
      margin-bottom: 1rem;
      color: #222;
    }
    p {
      margin-bottom: 1.25rem;
      font-size: 1.125rem;
      color: #333;
    }
    ul, ol {
      margin-bottom: 1.5rem;
      margin-left: 2rem;
      font-size: 1.125rem;
    }
    li {
      margin-bottom: 0.75rem;
      color: #333;
    }
    a {
      display: inline-block;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 15px 40px;
      margin: 10px 10px 10px 0;
      text-decoration: none;
      border-radius: 8px;
      font-weight: 600;
      font-size: 1.1rem;
      transition: transform 0.2s, box-shadow 0.2s;
    }
    a:hover {
      transform: translateY(-2px);
      box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
    }
    .section {
      margin-bottom: 3rem;
      padding-bottom: 2rem;
      border-bottom: 1px solid #eee;
    }
    .section:last-child {
      border-bottom: none;
    }
    .cta-section {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 3rem 2rem;
      border-radius: 12px;
      text-align: center;
      margin-top: 4rem;
    }
    .cta-section h1,
    .cta-section h2,
    .cta-section p {
      color: white;
    }
    .cta-section a {
      background: white;
      color: #667eea;
      margin-top: 1rem;
    }
  </style>
</head>
<body>
  <div class="container">
`;

  // Add each section from template
  template.structure_json.forEach((fragmentType: string) => {
    const content = fragmentMap.get(fragmentType);
    if (content) {
      // Wrap offer_stack in special styling
      if (fragmentType === 'offer_stack') {
        salesPageHTML += `<div class="cta-section">${content}</div>`;
      } else {
        salesPageHTML += `<div class="section">${content}</div>`;
      }
    }
  });
  
  salesPageHTML += `
  </div>
  
  <!-- Generated by God Mode from ${fragments.length} content fragments -->
  <div style="text-align: center; padding: 40px 20px; color: #999; font-size: 0.875rem;">
    <p>✨ Auto-generated from database content | ${site.domain}</p>
  </div>
</body>
</html>
`;
}

// Create the page
const pageData = {
  site_id: site.id,
  name: "Aesthetic Practice CEO Sales Letter",
  route: "/aesthetic-practice-report",
  html_content: salesPageHTML,
  meta_title: "Stop Wasting $50,000 on Google Ads | Aesthetic Practice CEO Report",
  meta_description: "Essential report for aesthetic practice CEOs. Discover the critical flaw in standard agency funnels and the Conversion Architecture system that delivers results.",
  status: "published"
};

let createdPage = null;
let error = null;

try {
  const response = await fetch(`${Astro.url.origin}/api/shim/pages/create`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${import.meta.env.GOD_MODE_TOKEN}`
    },
    body: JSON.stringify(pageData)
  });
  
  if (response.ok) {
    createdPage = await response.json();
  } else {
    const err = await response.json();
    error = err.message || 'Failed to create page';
  }
} catch (err: any) {
  error = err.message;
  console.error('Failed to create page:', err);
}
---

<AdminLayout title="Real Content Demo">
  <div class="space-y-6">
    
    <div class="flex justify-between items-center">
      <div>
        <h1 class="text-3xl font-bold text-white">🎯 Real Content Sales Page</h1>
        <p class="text-slate-400 mt-1">Generated from your {fragments.length} content fragments</p>
      </div>
      <a href="/admin/pages" class="px-4 py-2 bg-slate-700 hover:bg-slate-600 text-white rounded-lg">
        ← Back
      </a>
    </div>

    {createdPage ? (
      <div class="bg-green-900/20 border border-green-700 rounded-lg p-6">
        <h2 class="text-green-400 font-semibold text-2xl mb-3">✅ Sales Page Created!</h2>
        <p class="text-green-300 mb-4 text-lg">
          Your {fragments.length}-section sales letter has been generated from real database content.
        </p>
        <div class="flex gap-3 mb-6">
          <a 
            href={`/preview/page/${createdPage.id}`}
            target="_blank"
            class="px-8 py-4 bg-green-600 hover:bg-green-500 text-white rounded-lg font-semibold text-lg"
          >
            👁️ View Full Sales Page
          </a>
          <a 
            href={`/admin/pages`}
            class="px-8 py-4 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-semibold text-lg"
          >
            📄 All Pages
          </a>
        </div>
        
        <div class="grid grid-cols-2 gap-4 mt-6">
          <div class="p-4 bg-slate-800 rounded border border-slate-600">
            <div class="text-sm text-slate-400 mb-1">Page ID</div>
            <div class="font-mono text-xs text-slate-300">{createdPage.id}</div>
          </div>
          <div class="p-4 bg-slate-800 rounded border border-slate-600">
            <div class="text-sm text-slate-400 mb-1">Route</div>
            <div class="font-semibold text-white">{createdPage.route}</div>
          </div>
          <div class="p-4 bg-slate-800 rounded border border-slate-600">
            <div class="text-sm text-slate-400 mb-1">Status</div>
            <div class="font-semibold text-green-400">{createdPage.status}</div>
          </div>
          <div class="p-4 bg-slate-800 rounded border border-slate-600">
            <div class="text-sm text-slate-400 mb-1">Word Count</div>
            <div class="font-semibold text-white">~{fragments.reduce((sum, f) => sum + f.word_count, 0)} words</div>
          </div>
        </div>
      </div>
    ) : error ? (
      <div class="bg-red-900/20 border border-red-700 rounded-lg p-6">
        <h2 class="text-red-400 font-semibold text-xl mb-2">❌ Error</h2>
        <p class="text-red-300">{error}</p>
      </div>
    ) : (
      <div class="bg-yellow-900/20 border border-yellow-700 rounded-lg p-6">
        <h2 class="text-yellow-400 font-semibold text-xl mb-2">⏳ Generating...</h2>
        <p class="text-yellow-300">Creating sales page from fragments...</p>
      </div>
    )}

    <div class="bg-slate-800 rounded-lg border border-slate-700 p-6">
      <h3 class="text-white font-semibold text-lg mb-4">📦 Content Fragments Found:</h3>
      <div class="grid gap-3">
        {fragments.map(frag => (
          <div class="p-4 bg-slate-900 border border-slate-700 rounded">
            <div class="flex justify-between items-center mb-2">
              <span class="font-semibold text-blue-400">{frag.fragment_type}</span>
              <span class="text-xs text-slate-500">{frag.word_count} words</span>
            </div>
            <div class="text-sm text-slate-400 line-clamp-2">
              {frag.content_body.replace(/<[^>]*>/g, '').substring(0, 150)}...
            </div>
          </div>
        ))}
      </div>
    </div>

    {template && (
      <div class="bg-purple-900/20 border border-purple-700 rounded-lg p-6">
        <h3 class="text-purple-300 font-semibold text-lg mb-3">📋 Template Structure: {template.name}</h3>
        <div class="flex flex-wrap gap-2">
          {template.structure_json.map((section: string) => {
            const hasContent = fragments.some(f => f.fragment_type === section);
            return (
              <span class={`px-3 py-1 rounded text-sm font-medium ${
                hasContent 
                  ? 'bg-green-900/30 border border-green-700 text-green-300' 
                  : 'bg-red-900/30 border border-red-700 text-red-300'
              }`}>
                {section} {hasContent ? '✓' : '✗'}
              </span>
            );
          })}
        </div>
        <p class="mt-4 text-sm text-purple-300">
          {fragments.length} of {template.structure_json.length} sections have content
        </p>
      </div>
    )}

  </div>
</AdminLayout>
