/**
 * Page Studio — React/JSX exporter
 * ---------------------------------
 * Turns an editor page into a single self-contained functional React
 * component. Tailwind classes only (no CSS-in-JS), inline content,
 * default export at bottom. The output is meant to be dropped into
 * any Next.js / Vite / CRA project without additional deps.
 */

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

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

// ─── Utilities ────────────────────────────────────────────────────────────────

function esc(s: unknown): string {
  return String(s ?? "").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
}
/** JSX-safe text: escape braces and backticks inside JSX children */
function jsx(s: unknown): string {
  return String(s ?? "").replace(/[{}]/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
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[]) : []; }

function sanitiseComponentName(title: string): string {
  const base = title.replace(/[^a-zA-Z0-9]+/g, " ").split(" ").filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
  const valid = /^[A-Z]/.test(base) ? base : "Page" + base;
  return valid || "GeneratedPage";
}

// ─── Per-section JSX generators ───────────────────────────────────────────────

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 styleProps = [`backgroundColor: "${bg}"`, `color: "${fg}"`];
  if (bgImg) {
    styleProps.push(`backgroundImage: \`linear-gradient(rgba(0,0,0,.45),rgba(0,0,0,.45)),url('${esc(bgImg)}')\``, `backgroundSize: "cover"`, `backgroundPosition: "center"`);
  }
  return `      <section className="px-6 py-20 md:py-28 text-center" style={{ ${styleProps.join(", ")} }}>
        <div className="max-w-4xl mx-auto">
          <h1 className="text-4xl md:text-6xl font-extrabold tracking-tight mb-5">${jsx(c.headline)}</h1>
          <p className="text-lg md:text-xl opacity-90 max-w-2xl mx-auto mb-8">${jsx(c.subheadline)}</p>
          ${c.ctaText ? `<a href="${esc(c.ctaUrl || "#")}" className="inline-block px-8 py-4 rounded-xl font-semibold shadow-lg" style={{ backgroundColor: "${b.accentColor}", color: "#FFFFFF" }}>${jsx(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, i) => l.url
    ? `<img key={${i}} src="${esc(l.url)}" alt="${esc(l.name)}" className="h-8 object-contain opacity-60" />`
    : `<span key={${i}} className="text-lg font-bold text-slate-400">${jsx(l.name)}</span>`
  ).join("\n          ");
  return `      <section className="px-6 py-12 bg-slate-50">
        <div className="max-w-5xl mx-auto text-center">
          ${c.headline ? `<p className="text-xs font-bold uppercase tracking-widest text-slate-500 mb-6">${jsx(c.headline)}</p>` : ""}
          <div className="flex flex-wrap items-center justify-center gap-x-10 gap-y-4">
          ${items}
          </div>
        </div>
      </section>`;
}

function featuresGrid(c: Record<string, unknown>, b: Branding): string {
  const items = arr<{ title?: string; description?: string }>(c.items).map((it, i) => `            <div key={${i}} className="rounded-2xl border border-slate-200 bg-white p-6">
              <div className="w-11 h-11 rounded-xl flex items-center justify-center mb-4 font-bold" style={{ backgroundColor: "${b.primaryColor}15", color: "${b.primaryColor}" }}>${jsx((it.title || "?").charAt(0))}</div>
              <h3 className="text-lg font-bold mb-2">${jsx(it.title)}</h3>
              <p className="text-sm text-slate-600">${jsx(it.description)}</p>
            </div>`).join("\n");
  return `      <section className="px-6 py-20 bg-white">
        <div className="max-w-6xl mx-auto">
          <div className="text-center mb-12">
            <h2 className="text-3xl md:text-4xl font-bold mb-3">${jsx(c.headline)}</h2>
            ${c.subheadline ? `<p className="text-lg text-slate-600 max-w-2xl mx-auto">${jsx(c.subheadline)}</p>` : ""}
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
${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 className="px-6 py-16" style={{ backgroundColor: "${bg}", color: "${fg}" }}>
        <div className="max-w-4xl mx-auto text-center">
          <h2 className="text-3xl md:text-4xl font-bold mb-3">${jsx(c.headline)}</h2>
          ${c.subheadline ? `<p className="text-lg opacity-90 mb-8">${jsx(c.subheadline)}</p>` : ""}
          ${c.ctaText ? `<a href="${esc(c.ctaUrl || "#")}" className="inline-block px-8 py-4 rounded-xl font-semibold shadow-lg" style={{ backgroundColor: "#FFFFFF", color: "${bg}" }}>${jsx(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 fieldJsx = fields.map((f, i) => {
    const input = f.type === "textarea"
      ? `<textarea name="${esc(f.name)}" rows={4} ${f.required ? "required " : ""}className="w-full px-4 py-2.5 rounded-lg border border-slate-200" />`
      : `<input type="${esc(f.type || "text")}" name="${esc(f.name)}" ${f.required ? "required " : ""}className="w-full px-4 py-2.5 rounded-lg border border-slate-200" />`;
    return `            <div key={${i}}>
              <label className="block text-sm font-semibold text-slate-700 mb-1.5">${jsx(f.label)}${f.required ? ' <span className="text-red-500">*</span>' : ""}</label>
              ${input}
            </div>`;
  }).join("\n");
  return `      <section className="px-6 py-20 bg-slate-50">
        <div className="max-w-xl mx-auto">
          <div className="text-center mb-8">
            <h2 className="text-3xl md:text-4xl font-bold mb-3">${jsx(c.headline)}</h2>
            ${c.subheadline ? `<p className="text-base text-slate-600">${jsx(c.subheadline)}</p>` : ""}
          </div>
          <form className="bg-white rounded-2xl border border-slate-200 p-8 space-y-4 shadow-sm">
${fieldJsx}
            <button type="submit" className="w-full px-6 py-3 rounded-lg font-semibold text-white" style={{ backgroundColor: "${b.primaryColor}" }}>${jsx(c.submitText || "Send Message")}</button>
          </form>
        </div>
      </section>`;
}

function faqSection(c: Record<string, unknown>): string {
  const items = arr<{ question?: string; answer?: string }>(c.items).map((it, i) => `            <details key={${i}} className="rounded-xl border border-slate-200 bg-white px-5 py-4">
              <summary className="text-base font-semibold cursor-pointer">${jsx(it.question)}</summary>
              <p className="mt-3 text-sm text-slate-600">${jsx(it.answer)}</p>
            </details>`).join("\n");
  return `      <section className="px-6 py-20 bg-white">
        <div className="max-w-3xl mx-auto">
          <h2 className="text-3xl md:text-4xl font-bold text-center mb-10">${jsx(c.headline)}</h2>
          <div className="space-y-3">
${items}
          </div>
        </div>
      </section>`;
}

function placeholderJsx(section: Section): string {
  return `      <section className="px-6 py-16 border-2 border-dashed border-slate-300 bg-slate-50 text-center">
        <p className="text-xs font-bold uppercase tracking-widest text-slate-400">${jsx(section.type)}</p>
        <p className="text-sm text-slate-500">Block type not yet supported by React export.</p>
      </section>`;
}

function renderSectionJsx(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 faqSection(section.content);
    default: return placeholderJsx(section);
  }
}

export function exportPageToReact(page: ExportablePage): string {
  const componentName = sanitiseComponentName(page.title);
  const body = page.sections.map((s) => renderSectionJsx(s, page.branding)).join("\n\n");
  return `import React from "react";

// Generated by meSEO Page Studio — Tailwind CSS required.
export default function ${componentName}() {
  return (
    <main style={{ fontFamily: "${page.branding.fontFamily}" }}>
${body}
    </main>
  );
}
`;
}
