/**
 * Page Studio — Section Renderer
 * -------------------------------
 * Turns a Section from the editor state into styled HTML for both the
 * live preview and the published page. Each section has a dedicated
 * render function that knows its content shape and applies branding.
 *
 * Modes:
 *   edit    — used inside the Page Studio editor. Wraps editable text
 *             with a subtle dashed border so users can tell what's
 *             clickable. Individual editors mount behaviour — this
 *             layer only signals intent.
 *   preview — used for the clean preview tab and the final render.
 *             No edit affordances.
 */

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

type Mode = "edit" | "preview";

interface SectionProps {
  content: Record<string, unknown>;
  branding: Branding;
  mode: Mode;
}

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

function str(v: unknown, fallback = ""): string {
  return typeof v === "string" ? v : fallback;
}
function arr<T = unknown>(v: unknown): T[] {
  return Array.isArray(v) ? (v as T[]) : [];
}

/** Wraps editable text with a subtle dashed outline in edit mode. */
function editable(mode: Mode, className: string): string {
  const base = className;
  return mode === "edit"
    ? `${base} outline-dashed outline-1 outline-transparent hover:outline-brand-400/60 rounded-sm transition-colors cursor-text`
    : base;
}

// ═══════════════════════════════════════════════════════════════════════════
// HERO
// ═══════════════════════════════════════════════════════════════════════════
function HeroSection({ content, branding, mode }: SectionProps) {
  const bg = str(content.backgroundColor, branding.primaryColor);
  const fg = str(content.textColor, "#FFFFFF");
  const bgImage = str(content.backgroundImage);
  return (
    <section
      className="relative px-6 py-20 md:py-28 text-center"
      style={{
        backgroundColor: bg,
        color: fg,
        backgroundImage: bgImage ? `linear-gradient(rgba(0,0,0,0.45),rgba(0,0,0,0.45)),url(${bgImage})` : undefined,
        backgroundSize: "cover",
        backgroundPosition: "center",
        fontFamily: branding.fontFamily,
      }}
    >
      <div className="max-w-4xl mx-auto">
        <h1 className={editable(mode, "text-4xl md:text-6xl font-extrabold tracking-tight leading-tight mb-5")}>
          {str(content.headline, "Your Headline Here")}
        </h1>
        <p className={editable(mode, "text-lg md:text-xl opacity-90 leading-relaxed max-w-2xl mx-auto mb-8")}>
          {str(content.subheadline)}
        </p>
        {content.ctaText ? (
          <a
            href={str(content.ctaUrl, "#")}
            className="inline-flex items-center px-8 py-4 rounded-xl font-semibold text-base shadow-lg transition-transform hover:scale-105"
            style={{ backgroundColor: branding.accentColor, color: "#FFFFFF" }}
          >
            {str(content.ctaText)}
          </a>
        ) : null}
      </div>
    </section>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// TRUST BAR
// ═══════════════════════════════════════════════════════════════════════════
function TrustBarSection({ content, branding, mode }: SectionProps) {
  const logos = arr<{ name: string; url?: string }>(content.logos);
  return (
    <section className="px-6 py-12 bg-slate-50" style={{ fontFamily: branding.fontFamily }}>
      <div className="max-w-5xl mx-auto text-center">
        {content.headline ? (
          <p className={editable(mode, "text-xs font-bold uppercase tracking-widest text-slate-500 mb-6")}>
            {str(content.headline)}
          </p>
        ) : null}
        <div className="flex flex-wrap items-center justify-center gap-x-10 gap-y-4">
          {logos.map((logo, i) => (
            <div key={i} className="opacity-60 hover:opacity-100 transition-opacity">
              {logo.url ? (
                <img src={logo.url} alt={logo.name} className="h-8 object-contain" />
              ) : (
                <span className="text-lg font-bold text-slate-400">{logo.name}</span>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// FEATURES GRID
// ═══════════════════════════════════════════════════════════════════════════
function FeaturesGridSection({ content, branding, mode }: SectionProps) {
  const items = arr<{ title: string; description: string; icon?: string }>(content.items);
  return (
    <section className="px-6 py-20 bg-white" style={{ fontFamily: branding.fontFamily, color: branding.textColor }}>
      <div className="max-w-6xl mx-auto">
        <div className="text-center mb-12">
          <h2 className={editable(mode, "text-3xl md:text-4xl font-bold mb-3")}>{str(content.headline, "Our Features")}</h2>
          {content.subheadline ? (
            <p className={editable(mode, "text-lg text-slate-600 max-w-2xl mx-auto")}>{str(content.subheadline)}</p>
          ) : null}
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
          {items.map((item, i) => (
            <div key={i} className="rounded-2xl border border-slate-200 bg-white p-6 hover:shadow-md transition-shadow">
              <div
                className="w-11 h-11 rounded-xl flex items-center justify-center mb-4 text-lg font-bold"
                style={{ backgroundColor: `${branding.primaryColor}15`, color: branding.primaryColor }}
                aria-hidden
              >
                {(item.title || "?").charAt(0).toUpperCase()}
              </div>
              <h3 className={editable(mode, "text-lg font-bold mb-2")}>{item.title}</h3>
              <p className={editable(mode, "text-sm text-slate-600 leading-relaxed")}>{item.description}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// CTA BANNER
// ═══════════════════════════════════════════════════════════════════════════
function CtaBannerSection({ content, branding, mode }: SectionProps) {
  const bg = str(content.backgroundColor, branding.primaryColor);
  const fg = str(content.textColor, "#FFFFFF");
  return (
    <section className="px-6 py-16" style={{ backgroundColor: bg, color: fg, fontFamily: branding.fontFamily }}>
      <div className="max-w-4xl mx-auto text-center">
        <h2 className={editable(mode, "text-3xl md:text-4xl font-bold mb-3")}>{str(content.headline, "Ready to get started?")}</h2>
        {content.subheadline ? (
          <p className={editable(mode, "text-lg opacity-90 mb-8")}>{str(content.subheadline)}</p>
        ) : null}
        {content.ctaText ? (
          <a
            href={str(content.ctaUrl, "#")}
            className="inline-flex items-center px-8 py-4 rounded-xl font-semibold text-base shadow-lg transition-transform hover:scale-105"
            style={{ backgroundColor: "#FFFFFF", color: bg }}
          >
            {str(content.ctaText)}
          </a>
        ) : null}
      </div>
    </section>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// CONTACT FORM
// ═══════════════════════════════════════════════════════════════════════════
interface FormField { name: string; label: string; type: string; required?: boolean }
function ContactFormSection({ content, branding, mode }: SectionProps) {
  const fields = arr<FormField>(content.fields);
  return (
    <section className="px-6 py-20 bg-slate-50" style={{ fontFamily: branding.fontFamily, color: branding.textColor }}>
      <div className="max-w-xl mx-auto">
        <div className="text-center mb-8">
          <h2 className={editable(mode, "text-3xl md:text-4xl font-bold mb-3")}>{str(content.headline, "Get In Touch")}</h2>
          {content.subheadline ? (
            <p className={editable(mode, "text-base text-slate-600")}>{str(content.subheadline)}</p>
          ) : null}
        </div>
        <form className="bg-white rounded-2xl border border-slate-200 p-8 space-y-4 shadow-sm">
          {fields.map((f) => (
            <div key={f.name}>
              <label className="block text-sm font-semibold text-slate-700 mb-1.5">
                {f.label}{f.required ? <span className="text-red-500 ml-0.5">*</span> : null}
              </label>
              {f.type === "textarea" ? (
                <textarea
                  name={f.name}
                  rows={4}
                  required={f.required}
                  className="w-full px-4 py-2.5 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500"
                />
              ) : (
                <input
                  type={f.type}
                  name={f.name}
                  required={f.required}
                  className="w-full px-4 py-2.5 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500"
                />
              )}
            </div>
          ))}
          <button
            type="submit"
            className="w-full px-6 py-3 rounded-lg font-semibold text-white shadow-sm transition-transform hover:scale-[1.01]"
            style={{ backgroundColor: branding.primaryColor }}
          >
            {str(content.submitText, "Send Message")}
          </button>
        </form>
      </div>
    </section>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// FAQ
// ═══════════════════════════════════════════════════════════════════════════
function FaqSection({ content, branding, mode }: SectionProps) {
  const items = arr<{ question: string; answer: string }>(content.items);
  return (
    <section className="px-6 py-20 bg-white" style={{ fontFamily: branding.fontFamily, color: branding.textColor }}>
      <div className="max-w-3xl mx-auto">
        <h2 className={editable(mode, "text-3xl md:text-4xl font-bold text-center mb-10")}>
          {str(content.headline, "Frequently Asked Questions")}
        </h2>
        <div className="space-y-3">
          {items.map((item, i) => (
            <details key={i} className="group rounded-xl border border-slate-200 bg-white px-5 py-4 open:shadow-sm">
              <summary className="flex items-center justify-between cursor-pointer list-none">
                <span className={editable(mode, "text-base font-semibold text-slate-900")}>{item.question}</span>
                <span className="ml-4 text-slate-400 group-open:rotate-45 transition-transform text-xl leading-none">+</span>
              </summary>
              <p className={editable(mode, "mt-3 text-sm text-slate-600 leading-relaxed")}>{item.answer}</p>
            </details>
          ))}
        </div>
      </div>
    </section>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// PLACEHOLDER — used for block types that don't have a dedicated renderer
// yet. Shows the block name + description from the registry so the
// editor still lays out usefully.
// ═══════════════════════════════════════════════════════════════════════════
function PlaceholderSection({ type, branding, mode }: { type: string; branding: Branding; mode: Mode }) {
  const def = getBlockDefinition(type);
  return (
    <section
      className="px-6 py-16 border-2 border-dashed border-slate-300 bg-slate-50 text-center"
      style={{ fontFamily: branding.fontFamily }}
    >
      <div className="max-w-2xl mx-auto">
        <p className="text-xs font-bold uppercase tracking-widest text-slate-400 mb-2">
          {mode === "edit" ? "Block preview" : "Coming soon"}
        </p>
        <h3 className="text-2xl font-bold text-slate-700 mb-2">{def?.name ?? type}</h3>
        <p className="text-sm text-slate-500">{def?.description ?? "Renderer not implemented yet."}</p>
      </div>
    </section>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// Dispatcher
// ═══════════════════════════════════════════════════════════════════════════

export function renderSection(section: Section, branding: Branding, mode: Mode = "preview"): React.ReactElement {
  const props: SectionProps = { content: section.content, branding, mode };
  switch (section.type) {
    case "hero":         return <HeroSection {...props} />;
    case "trust_bar":    return <TrustBarSection {...props} />;
    case "features_grid":return <FeaturesGridSection {...props} />;
    case "cta_banner":   return <CtaBannerSection {...props} />;
    case "contact_form": return <ContactFormSection {...props} />;
    case "faq":          return <FaqSection {...props} />;
    default:             return <PlaceholderSection type={section.type} branding={branding} mode={mode} />;
  }
}

/** Convenience: render an entire page of sections in order. */
export function SectionList({ sections, branding, mode = "preview" }: {
  sections: Section[];
  branding: Branding;
  mode?: Mode;
}): React.ReactElement {
  return (
    <>
      {sections.map((s) => (
        <div key={s.id}>{renderSection(s, branding, mode)}</div>
      ))}
    </>
  );
}
