/**
 * Page Studio — HTML exporter
 * ----------------------------
 * Turns an editor page (sections + branding + metadata) into a single,
 * self-contained HTML5 document. No JS, no build step — ready to drop
 * into any static host. Shared reset + typography live in a <style>
 * block; per-section flourishes use inline styles so the output stays
 * dependency-free and readable.
 */

import type { Section, Branding } from "./section-registry";

export interface ExportablePage {
  title: string;
  metaTitle?: string;
  metaDescription?: string;
  sections: Section[];
  branding: Branding;
}

function esc(s: unknown): string {
  return String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function str(v: unknown, fallback = ""): string { return typeof v === "string" ? v : fallback; }
function arr<T = Record<string, unknown>>(v: unknown): T[] { return Array.isArray(v) ? (v as T[]) : []; }

// ─── Per-section renderers ────────────────────────────────────────────────────

function hero(c: Record<string, unknown>, b: Branding): string {
  const bg = str(c.backgroundColor, b.primaryColor);
  const fg = str(c.textColor, "#FFFFFF");
  const bgImg = str(c.backgroundImage);
  const style = `background:${bg};color:${fg};${bgImg ? `background-image:linear-gradient(rgba(0,0,0,.45),rgba(0,0,0,.45)),url('${esc(bgImg)}');background-size:cover;background-position:center;` : ""}`;
  return `<section class="ps-hero" style="${style}"><div class="ps-container"><h1>${esc(c.headline)}</h1><p class="ps-sub">${esc(c.subheadline)}</p>${c.ctaText ? `<a class="ps-btn" style="background:${b.accentColor}" href="${esc(c.ctaUrl || "#")}">${esc(c.ctaText)}</a>` : ""}</div></section>`;
}

function trustBar(c: Record<string, unknown>): string {
  const logos = arr<{ name?: string; url?: string }>(c.logos);
  const items = logos.map((l) => l.url ? `<img src="${esc(l.url)}" alt="${esc(l.name)}" />` : `<span>${esc(l.name)}</span>`).join("");
  return `<section class="ps-trust"><div class="ps-container">${c.headline ? `<p class="ps-eyebrow">${esc(c.headline)}</p>` : ""}<div class="ps-logos">${items}</div></div></section>`;
}

function featuresGrid(c: Record<string, unknown>, b: Branding): string {
  const items = arr<{ title?: string; description?: string }>(c.items).map((it) => `
    <div class="ps-feature"><div class="ps-feature-icon" style="background:${b.primaryColor}15;color:${b.primaryColor}">${esc((it.title || "?").charAt(0))}</div><h3>${esc(it.title)}</h3><p>${esc(it.description)}</p></div>
  `).join("");
  return `<section class="ps-features"><div class="ps-container"><div class="ps-heading"><h2>${esc(c.headline)}</h2>${c.subheadline ? `<p>${esc(c.subheadline)}</p>` : ""}</div><div class="ps-grid">${items}</div></div></section>`;
}

function ctaBanner(c: Record<string, unknown>, b: Branding): string {
  const bg = str(c.backgroundColor, b.primaryColor);
  const fg = str(c.textColor, "#FFFFFF");
  return `<section class="ps-cta" style="background:${bg};color:${fg}"><div class="ps-container ps-center"><h2>${esc(c.headline)}</h2>${c.subheadline ? `<p class="ps-sub">${esc(c.subheadline)}</p>` : ""}${c.ctaText ? `<a class="ps-btn" style="background:#fff;color:${bg}" href="${esc(c.ctaUrl || "#")}">${esc(c.ctaText)}</a>` : ""}</div></section>`;
}

function contactForm(c: Record<string, unknown>, b: Branding): string {
  const fields = arr<{ name?: string; label?: string; type?: string; required?: boolean }>(c.fields);
  const fieldHtml = fields.map((f) => {
    const input = f.type === "textarea"
      ? `<textarea name="${esc(f.name)}" rows="4" ${f.required ? "required" : ""}></textarea>`
      : `<input type="${esc(f.type || "text")}" name="${esc(f.name)}" ${f.required ? "required" : ""} />`;
    return `<div class="ps-field"><label>${esc(f.label)}${f.required ? ' <span style="color:#ef4444">*</span>' : ""}</label>${input}</div>`;
  }).join("");
  return `<section class="ps-contact"><div class="ps-container ps-narrow"><div class="ps-heading"><h2>${esc(c.headline)}</h2>${c.subheadline ? `<p>${esc(c.subheadline)}</p>` : ""}</div><form class="ps-form">${fieldHtml}<button type="submit" style="background:${b.primaryColor}">${esc(c.submitText || "Send Message")}</button></form></div></section>`;
}

function faq(c: Record<string, unknown>): string {
  const items = arr<{ question?: string; answer?: string }>(c.items).map((it) => `<details><summary>${esc(it.question)}<span>+</span></summary><p>${esc(it.answer)}</p></details>`).join("");
  return `<section class="ps-faq"><div class="ps-container ps-narrow"><h2>${esc(c.headline)}</h2>${items}</div></section>`;
}

function placeholder(section: Section): string {
  return `<section class="ps-placeholder"><div class="ps-container"><p class="ps-eyebrow">${esc(section.type)}</p><p>This block type is not yet available in HTML export.</p></div></section>`;
}

function renderSectionHtml(section: Section, b: Branding): string {
  switch (section.type) {
    case "hero": return hero(section.content, b);
    case "trust_bar": return trustBar(section.content);
    case "features_grid": return featuresGrid(section.content, b);
    case "cta_banner": return ctaBanner(section.content, b);
    case "contact_form": return contactForm(section.content, b);
    case "faq": return faq(section.content);
    default: return placeholder(section);
  }
}

// ─── Shared stylesheet ────────────────────────────────────────────────────────

function baseCss(b: Branding): string {
  return `*,*::before,*::after{box-sizing:border-box}body{margin:0;font-family:${b.fontFamily};color:${b.textColor || "#0F172A"};background:${b.backgroundColor || "#fff"};line-height:1.55;-webkit-font-smoothing:antialiased}h1,h2,h3,p{margin:0}a{color:inherit;text-decoration:none}img{max-width:100%;height:auto;display:block}.ps-container{max-width:1100px;margin:0 auto;padding:0 24px}.ps-narrow{max-width:680px}.ps-center{text-align:center}.ps-btn{display:inline-block;padding:16px 32px;border-radius:12px;font-weight:700;color:#fff;box-shadow:0 8px 24px rgba(0,0,0,.15);transition:transform .15s}.ps-btn:hover{transform:scale(1.04)}.ps-eyebrow{font-size:12px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:#64748b;margin-bottom:16px;text-align:center}.ps-heading{text-align:center;margin-bottom:48px}.ps-heading h2{font-size:36px;font-weight:800;margin-bottom:12px}.ps-heading p{font-size:18px;color:#475569;max-width:620px;margin:0 auto}.ps-hero{padding:96px 24px;text-align:center}.ps-hero h1{font-size:56px;font-weight:800;line-height:1.1;margin-bottom:20px}.ps-hero .ps-sub{font-size:20px;opacity:.9;max-width:680px;margin:0 auto 32px}@media(max-width:700px){.ps-hero h1{font-size:36px}.ps-hero .ps-sub{font-size:17px}}.ps-trust{padding:48px 24px;background:#f8fafc}.ps-logos{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:40px}.ps-logos img{height:32px;object-fit:contain;opacity:.6}.ps-logos span{font-size:18px;font-weight:700;color:#94a3b8}.ps-features{padding:80px 24px;background:#fff}.ps-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:24px}.ps-feature{padding:28px;border:1px solid #e2e8f0;border-radius:16px;background:#fff}.ps-feature-icon{width:44px;height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-weight:700;margin-bottom:16px}.ps-feature h3{font-size:18px;font-weight:700;margin-bottom:8px}.ps-feature p{font-size:14px;color:#64748b}.ps-cta{padding:64px 24px}.ps-cta h2{font-size:36px;font-weight:800;margin-bottom:12px}.ps-cta .ps-sub{font-size:18px;opacity:.9;margin-bottom:32px}.ps-contact{padding:80px 24px;background:#f8fafc}.ps-form{background:#fff;padding:32px;border:1px solid #e2e8f0;border-radius:16px;box-shadow:0 1px 3px rgba(0,0,0,.04)}.ps-field{margin-bottom:16px}.ps-field label{display:block;font-size:13px;font-weight:600;color:#334155;margin-bottom:6px}.ps-field input,.ps-field textarea{width:100%;padding:10px 14px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;font-family:inherit}.ps-field input:focus,.ps-field textarea:focus{outline:none;border-color:${b.primaryColor};box-shadow:0 0 0 3px ${b.primaryColor}20}.ps-form button{width:100%;padding:12px 24px;border:none;color:#fff;font-weight:700;font-size:14px;border-radius:8px;cursor:pointer;margin-top:8px}.ps-faq{padding:80px 24px;background:#fff}.ps-faq h2{font-size:36px;font-weight:800;text-align:center;margin-bottom:40px}.ps-faq details{border:1px solid #e2e8f0;border-radius:12px;padding:16px 20px;margin-bottom:12px;background:#fff}.ps-faq summary{font-size:16px;font-weight:600;cursor:pointer;list-style:none;display:flex;justify-content:space-between;align-items:center}.ps-faq summary::-webkit-details-marker{display:none}.ps-faq summary span{color:#94a3b8;font-size:22px;transition:transform .2s}.ps-faq details[open] summary span{transform:rotate(45deg)}.ps-faq details p{margin-top:12px;color:#64748b;font-size:14px}.ps-placeholder{padding:48px 24px;background:#f1f5f9;text-align:center;border:2px dashed #cbd5e1}`;
}

// ─── Entry point ──────────────────────────────────────────────────────────────

export function exportPageToHtml(page: ExportablePage): string {
  const title = page.metaTitle || page.title || "Untitled page";
  const desc = page.metaDescription || "";
  const body = page.sections.map((s) => renderSectionHtml(s, page.branding)).join("\n");
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>${esc(title)}</title>
<meta name="description" content="${esc(desc)}">
<meta property="og:title" content="${esc(title)}">
<meta property="og:description" content="${esc(desc)}">
<meta property="og:type" content="website">
<style>${baseCss(page.branding)}</style>
</head>
<body>
${body}
</body>
</html>`;
}
