import { useMemo, type CSSProperties } from "react";
import { SectionRenderer } from "./parent-course-overview/SectionRenderer";
import { interpolateTemplate, parseParentCourseOverviewContent } from "./parent-course-overview/parseContent";
import { pcoHeroToCssVars, pcoRootToCssVars } from "./parent-course-overview/pcoTheme";
import "./parent-course-overview/parent-course-overview.css";

type Content = Record<string, unknown>;

export function ParentCourseOverviewBlock({ content }: { content?: Content }) {
  const contentKey = JSON.stringify(content ?? {});
  const data = useMemo(() => parseParentCourseOverviewContent(content), [contentKey]);
  const { cardColor, cardBorderColor, hero, sections, footer, globalStyle } = data;

  const vars = { course: hero.course, gradeBand: hero.gradeBand };

  const rootStyle = pcoRootToCssVars({ cardColor, cardBorderColor, globalStyle });
  const heroStyle = pcoHeroToCssVars(hero.style);
  const footerStyle = {
    ...pcoRootToCssVars({ globalStyle: footer.style }),
    ...(footer.style?.backgroundColor ? { "--pco-footer-bg": footer.style.backgroundColor } : {}),
    ...(footer.style?.textColor ? { "--pco-footer-text": footer.style.textColor } : {}),
  } as CSSProperties;

  const contentPadding = globalStyle?.padding ? { padding: globalStyle.padding } : undefined;
  const eyebrow = interpolateTemplate(hero.eyebrow, vars);

  return (
    <div className="pco-root w-full min-w-0" style={rootStyle}>
      <article className="pco-doc">
        <header className="pco-hero" style={heroStyle}>
          {hero.style?.icon ? <span className="pco-hero-icon">{hero.style.icon}</span> : null}
          {hero.style?.imageUrl ? (
            <img src={hero.style.imageUrl} alt="" className="pco-hero-image mb-3 max-h-20 object-contain" />
          ) : null}
          <p className="pco-eyebrow">{eyebrow}</p>
          <h2>{hero.course}</h2>
          <p>{hero.promise}</p>
        </header>

        <div className="pco-content" style={contentPadding}>
          {sections.map((section) => (
            <SectionRenderer
              key={section.id}
              section={section}
              vars={vars}
              defaultCardBg={cardColor}
              defaultCardBorder={cardBorderColor}
              globalStyle={globalStyle}
            />
          ))}
        </div>

        <footer className="pco-footer" style={footerStyle}>
          {footer.text}
        </footer>
      </article>
    </div>
  );
}
