import type { CSSProperties } from "react";
import {
  COMPONENT_CATALOG,
  getComponentDisplayName,
  getComponentsInTopicGroup,
} from "../lib/componentCatalog";
import type { ComponentRecord } from "../types";
import ComponentPreviewMini from "./ComponentPreviewMini";

const WHOLE_CHILD_GROUP = "whole-child-portrait";

type SimilarComponentsCompareProps = {
  components: ComponentRecord[];
  topicGroup?: string;
  onSelect?: (component: ComponentRecord) => void;
};

const cardStyle: CSSProperties = {
  flex: "1 1 220px",
  minWidth: 200,
  padding: 12,
  background: "#fff",
  borderRadius: 12,
  border: "1px solid #e2e8f0",
};

export default function SimilarComponentsCompare({
  components,
  topicGroup = WHOLE_CHILD_GROUP,
  onSelect,
}: SimilarComponentsCompareProps) {
  const pair = getComponentsInTopicGroup(components, topicGroup);
  if (pair.length < 2) return null;

  const title =
    topicGroup === WHOLE_CHILD_GROUP
      ? "Compare: Portrait / Whole Child components"
      : "Compare similar components";

  return (
    <div
      style={{
        marginBottom: 16,
        padding: 16,
        background: "#eff6ff",
        border: "1px solid #bfdbfe",
        borderRadius: 14,
      }}
    >
      <p style={{ margin: "0 0 4px", fontSize: 14, fontWeight: 700, color: "#1e40af" }}>{title}</p>
      <p style={{ margin: "0 0 14px", fontSize: 13, color: "#475569", lineHeight: 1.45 }}>
        These components look similar but serve different purposes. Compare previews and descriptions before selecting.
      </p>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 12 }}>
        {pair.map((component) => {
          const entry = COMPONENT_CATALOG[component.slug];
          if (!entry) return null;

          const inner = (
            <>
              <ComponentPreviewMini component={component} scale={0.26} maxHeight={100} eager />
              <p style={{ margin: "10px 0 4px", fontWeight: 600, fontSize: 14, color: "#0f172a", lineHeight: 1.3 }}>
                {getComponentDisplayName(component)}
              </p>
              <p style={{ margin: "0 0 6px", fontSize: 12, color: "#64748b", lineHeight: 1.4 }}>{entry.shortDescription}</p>
              <p style={{ margin: 0, fontSize: 11, color: "#0f766e", fontWeight: 600, lineHeight: 1.4 }}>
                Best for: {entry.recommendedUse}
              </p>
            </>
          );

          if (onSelect) {
            return (
              <button
                key={component.id}
                type="button"
                onClick={() => onSelect(component)}
                style={{ ...cardStyle, cursor: "pointer", textAlign: "left" }}
              >
                {inner}
              </button>
            );
          }

          return (
            <div key={component.id} style={cardStyle}>
              {inner}
            </div>
          );
        })}
      </div>
    </div>
  );
}
