import { useState } from "react";
import { ChevronDown, ChevronUp, Plus, Trash2 } from "lucide-react";
import { Input } from "@/components/ui/input";
import { CardEditGroup, CardEditPanel } from "./CardEditLayout";
import { EmojiPickerField } from "./EmojiPickerField";
import type { BlockContent } from "../pages/BlockEditForm";

import { normalizeHowEachCourseSeesContent } from "@/components/page-blocks/how-each-course-sees/normalizeContent";

export { normalizeHowEachCourseSeesContent };

type Props = {
  content: BlockContent;
  onChange: (c: BlockContent) => void;
};

type EditorTab = "general" | "lenses" | "core" | "dna" | "assessment" | "evidence" | "inquiry" | "growth";

type LensItem = { name: string; emoji: string; type: string; lens: string };
type AssessmentItem = { title: string; icon: string; content: string };
type InquiryItem = { question: string; why: string };
type PortraitDim = { dimension: string; emoji: string; pct: number; description: string };
type FinkItem = { category: string; emoji: string; description: string };
type CourseItem = {
  name: string;
  emoji: string;
  type: "core" | "dna";
  whatLearning: string;
  howBuilds: string;
  keySkills: string[];
  standards: string[];
  portfolio: string[];
  questionsAtHome: string[];
  gapSkills: string;
  bigIdea: string;
  courseEssentialQuestion: string;
  courseNarrative: string;
  lens: string;
  progress: number;
  progress_color: string;
};

const formRow = "mb-4";
const labelCls = "block text-sm font-medium text-slate-700 mb-1";
const textareaCls = "flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm";
const selectCls = "flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm";

/** Midpoint of the previous decorative 40–85 random progress range. */
const DEFAULT_COURSE_PROGRESS = 60;
const DEFAULT_PROGRESS_COLOR = "#9E9A14";

const ACCENT_COLOR_HEX: Record<string, string> = {
  moss: "#9E9A14",
  "deep-sea": "#008A8F",
  valencia: "#F5A05A",
  sunflower: "#DDB308",
};

const EDITOR_TABS: { id: EditorTab; label: string }[] = [
  { id: "general", label: "General" },
  { id: "lenses", label: "Lenses" },
  { id: "core", label: "Core" },
  { id: "dna", label: "DNA" },
  { id: "assessment", label: "Assessment" },
  { id: "evidence", label: "Evidence" },
  { id: "inquiry", label: "Inquiry" },
  { id: "growth", label: "Growth" },
];

function parseLines(text: string): string[] {
  return text.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
}

function linesValue(items: string[]): string {
  return items.join("\n");
}

function toLines(v: unknown): string[] {
  return Array.isArray(v) ? v.map((i) => String(i)).filter(Boolean) : [];
}

function ensureLens(o: unknown): LensItem {
  const x = o && typeof o === "object" && !Array.isArray(o) ? (o as Record<string, unknown>) : {};
  return {
    name: String(x.name ?? ""),
    emoji: String(x.emoji ?? "📚"),
    type: String(x.type ?? "core") === "dna" ? "dna" : "core",
    lens: String(x.lens ?? ""),
  };
}

function ensureAssessment(o: unknown): AssessmentItem {
  const x = o && typeof o === "object" && !Array.isArray(o) ? (o as Record<string, unknown>) : {};
  return {
    title: String(x.title ?? ""),
    icon: String(x.icon ?? "📋"),
    content: String(x.content ?? ""),
  };
}

function ensureInquiry(o: unknown): InquiryItem {
  const x = o && typeof o === "object" && !Array.isArray(o) ? (o as Record<string, unknown>) : {};
  return { question: String(x.question ?? ""), why: String(x.why ?? "") };
}

function ensurePortrait(o: unknown): PortraitDim {
  const x = o && typeof o === "object" && !Array.isArray(o) ? (o as Record<string, unknown>) : {};
  const pct = typeof x.pct === "number" ? x.pct : parseInt(String(x.pct ?? 0), 10) || 0;
  return {
    dimension: String(x.dimension ?? ""),
    emoji: String(x.emoji ?? "✨"),
    pct: Math.min(100, Math.max(0, pct)),
    description: String(x.description ?? ""),
  };
}

function ensureFink(o: unknown): FinkItem {
  const x = o && typeof o === "object" && !Array.isArray(o) ? (o as Record<string, unknown>) : {};
  return {
    category: String(x.category ?? ""),
    emoji: String(x.emoji ?? "📚"),
    description: String(x.description ?? ""),
  };
}

function clampProgress(raw: unknown, fallback = DEFAULT_COURSE_PROGRESS): number {
  const n = typeof raw === "number" ? raw : parseInt(String(raw ?? ""), 10);
  if (!Number.isFinite(n)) return fallback;
  return Math.min(100, Math.max(0, n));
}

function ensureCourse(o: unknown, defaultType: "core" | "dna", defaultColor = DEFAULT_PROGRESS_COLOR): CourseItem {
  const x = o && typeof o === "object" && !Array.isArray(o) ? (o as Record<string, unknown>) : {};
  const colorRaw =
    (typeof x.progress_color === "string" && x.progress_color.trim()) ||
    (typeof x.progressColor === "string" && x.progressColor.trim()) ||
    "";
  return {
    name: String(x.name ?? ""),
    emoji: String(x.emoji ?? "📚"),
    type: String(x.type ?? defaultType) === "dna" ? "dna" : "core",
    whatLearning: String(x.whatLearning ?? ""),
    howBuilds: String(x.howBuilds ?? ""),
    keySkills: toLines(x.keySkills),
    standards: toLines(x.standards),
    portfolio: toLines(x.portfolio),
    questionsAtHome: toLines(x.questionsAtHome),
    gapSkills: String(x.gapSkills ?? ""),
    bigIdea: String(x.bigIdea ?? ""),
    courseEssentialQuestion: String(x.courseEssentialQuestion ?? ""),
    courseNarrative: String(x.courseNarrative ?? ""),
    lens: String(x.lens ?? ""),
    progress: clampProgress(x.progress),
    progress_color: colorRaw || defaultColor,
  };
}

function emptyCourse(type: "core" | "dna", defaultColor = DEFAULT_PROGRESS_COLOR): CourseItem {
  return {
    name: "",
    emoji: "📚",
    type,
    whatLearning: "",
    howBuilds: "",
    keySkills: [],
    standards: [],
    portfolio: [],
    questionsAtHome: [],
    gapSkills: "",
    bigIdea: "",
    courseEssentialQuestion: "",
    courseNarrative: "",
    lens: "",
    progress: DEFAULT_COURSE_PROGRESS,
    progress_color: defaultColor,
  };
}

/**
 * Tabbed editor for "How Each Course Sees This Quarter" / Courses (13) combined component.
 * Only the active editor tab is mounted for performance; content state is preserved in the parent.
 */
export function HowEachCourseSeesForm({ content, onChange }: Props) {
  const [editorTab, setEditorTab] = useState<EditorTab>("core");

  const coursesTabLabel = (content.coursesTabLabel as string) ?? "Courses (13)";
  const assessmentTabLabel = (content.assessmentTabLabel as string) ?? "Assessment";
  const evidenceTabLabel = (content.evidenceTabLabel as string) ?? "Evidence";
  const inquiryTabLabel = (content.inquiryTabLabel as string) ?? "Inquiry Questions";
  const growthTabLabel = (content.growthTabLabel as string) ?? "Growth Portrait";
  const color = (content.color as string) ?? "moss";
  const defaultProgressColor = ACCENT_COLOR_HEX[color] ?? DEFAULT_PROGRESS_COLOR;

  const lensesTitle =
    (content.lensesTitle as string) ??
    (content.title as string) ??
    "How Each Course Sees This Quarter";
  const lensesSubtitle =
    (content.lensesSubtitle as string) ??
    (content.subtitle as string) ??
    "Every subject views the quarter's driving question through its own disciplinary lens.";
  const lensesItems: LensItem[] = Array.isArray(content.lensesItems)
    ? content.lensesItems.map(ensureLens)
    : Array.isArray(content.items)
      ? content.items.map(ensureLens)
      : [];

  const coreHeading = (content.coreHeading as string) ?? "Core Courses";
  const coreSubtitle =
    (content.coreSubtitle as string) ??
    "9 courses · year-long — taught through the lens of this quarter's driving question";
  const coreCourses: CourseItem[] = Array.isArray(content.coreCourses)
    ? content.coreCourses.map((c) => ensureCourse(c, "core", defaultProgressColor))
    : [];

  const dnaHeading = (content.dnaHeading as string) ?? "DNA Strand Courses";
  const dnaSubtitle = (content.dnaSubtitle as string) ?? "4 courses · 9 weeks — rotating specialty courses";
  const dnaCourses: CourseItem[] = Array.isArray(content.dnaCourses)
    ? content.dnaCourses.map((c) => ensureCourse(c, "dna", defaultProgressColor))
    : [];

  const assessmentItems: AssessmentItem[] =
    Array.isArray(content.assessmentItems) && content.assessmentItems.length > 0
      ? content.assessmentItems.map(ensureAssessment)
      : [
          { title: "Week 1 · Entry Event", icon: "🎬", content: "" },
          { title: "Week 1 · Diagnostic Check", icon: "🔍", content: "" },
          { title: "Weeks 2–8 · Formative Assessment", icon: "📋", content: "" },
          { title: "Weeks 8–9 · Summative Performance", icon: "🎯", content: "" },
          { title: "How We Score: The 5P Rubric", icon: "📊", content: "" },
        ];
  const assessmentSummaryTitle = (content.assessmentSummaryTitle as string) ?? "How the Quarter Assessment Works";
  const assessmentSummary = (content.assessmentSummary as string) ?? "";
  const rubricLabels: string[] = Array.isArray(content.rubricLabels)
    ? (content.rubricLabels as unknown[]).map((x) => String(x)).filter(Boolean)
    : ["🏗 Product", "🎤 Performance", "📊 Progress", "🤝 People", "🔥 Passion"];

  const evidenceTitle = (content.evidenceTitle as string) ?? "Evidence Portfolio";
  const evidenceSubtitle =
    (content.evidenceSubtitle as string) ??
    "These work products go into your child's portfolio. Together, they tell the story of what your child learned.";

  const inquiryTitle = (content.inquiryTitle as string) ?? "Deep Inquiry Questions";
  const inquirySubtitle =
    (content.inquirySubtitle as string) ??
    "These go beyond individual subjects — use them at dinner, on car rides, or before bed.";
  const inquiryWhyPrefix = (content.inquiryWhyPrefix as string) ?? "Why this matters:";
  const deepInquiry: InquiryItem[] = Array.isArray(content.deepInquiry)
    ? content.deepInquiry.map(ensureInquiry)
    : [];

  const quarterId = content.quarterId != null ? String(content.quarterId) : "1";
  const portraitTitle =
    (content.portraitTitle as string) ?? `Portrait of the Learner — Quarter ${quarterId}`;
  const portraitOfLearner: PortraitDim[] = Array.isArray(content.portraitOfLearner)
    ? content.portraitOfLearner.map(ensurePortrait)
    : [];
  const finksTitle = (content.finksTitle as string) ?? "Fink's Taxonomy of Significant Learning";
  const finksTaxonomy: FinkItem[] = Array.isArray(content.finksTaxonomy)
    ? content.finksTaxonomy.map(ensureFink)
    : [];

  const patch = (partial: BlockContent) => onChange({ ...content, ...partial });

  const evidenceItems: string[] = Array.isArray(content.evidenceItems)
    ? (content.evidenceItems as unknown[]).map((x) => String(x))
    : typeof content.evidenceItems === "string"
      ? parseLines(content.evidenceItems)
      : [];

  const setEvidenceItems = (next: string[]) => patch({ evidenceItems: next });
  const updateEvidenceItem = (index: number, value: string) => {
    setEvidenceItems(evidenceItems.map((item, i) => (i === index ? value : item)));
  };
  const addEvidenceItem = () => setEvidenceItems([...evidenceItems, ""]);
  const removeEvidenceItem = (index: number) =>
    setEvidenceItems(evidenceItems.filter((_, i) => i !== index));
  const moveEvidenceItem = (index: number, dir: -1 | 1) => {
    const target = index + dir;
    if (target < 0 || target >= evidenceItems.length) return;
    const next = [...evidenceItems];
    const [item] = next.splice(index, 1);
    next.splice(target, 0, item);
    setEvidenceItems(next);
  };

  const renderCourseList = (
    courses: CourseItem[],
    key: "coreCourses" | "dnaCourses",
    defaultType: "core" | "dna",
    label: string
  ) => (
    <CardEditGroup
      label={label}
      layout="vertical"
      onAdd={() => patch({ [key]: [...courses, emptyCourse(defaultType, defaultProgressColor)] })}
      addLabel={`Add ${defaultType} course`}
      hint="All CourseCard fields are editable. Lens also feeds the Lenses grid when Lenses list is empty."
      isEmpty={courses.length === 0}
      emptyMessage="No courses yet. Click Add to create one."
    >
      {courses.map((course, index) => (
        <CardEditPanel
          key={`${defaultType}-${index}`}
          index={index}
          total={courses.length}
          layout="vertical"
          label={course.name}
          preview={{ emoji: course.emoji, title: course.name, subtitle: course.lens || course.whatLearning }}
          onRemove={() => patch({ [key]: courses.filter((_, i) => i !== index) })}
        >
          <div className="flex gap-2 flex-wrap items-end">
            <div>
              <label className={labelCls}>Emoji</label>
              <EmojiPickerField
                compact
                value={course.emoji}
                onChange={(v) => {
                  const next = courses.map((c, i) => (i === index ? { ...c, emoji: v } : c));
                  patch({ [key]: next });
                }}
              />
            </div>
            <div className="flex-1 min-w-[140px]">
              <label className={labelCls}>Course name</label>
              <Input
                value={course.name}
                onChange={(e) => {
                  const next = courses.map((c, i) => (i === index ? { ...c, name: e.target.value } : c));
                  patch({ [key]: next });
                }}
                placeholder="Course name"
              />
            </div>
            <div>
              <label className={labelCls}>Type</label>
              <select
                value={course.type}
                onChange={(e) => {
                  const next = courses.map((c, i) =>
                    i === index ? { ...c, type: e.target.value === "dna" ? "dna" : "core" } : c
                  );
                  patch({ [key]: next });
                }}
                className="rounded-md border border-input bg-background px-2 py-1.5 text-sm w-24 h-10"
              >
                <option value="core">core</option>
                <option value="dna">dna</option>
              </select>
            </div>
          </div>
          <div>
            <label className={labelCls}>Lens</label>
            <textarea
              value={course.lens}
              onChange={(e) => {
                const next = courses.map((c, i) => (i === index ? { ...c, lens: e.target.value } : c));
                patch({ [key]: next });
              }}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div>
            <label className={labelCls}>What your child is learning</label>
            <textarea
              value={course.whatLearning}
              onChange={(e) => {
                const next = courses.map((c, i) => (i === index ? { ...c, whatLearning: e.target.value } : c));
                patch({ [key]: next });
              }}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div className="grid sm:grid-cols-2 gap-3">
            <div>
              <label className={labelCls}>Progress (%)</label>
              <Input
                type="number"
                min={0}
                max={100}
                value={course.progress}
                onChange={(e) => {
                  const progress = clampProgress(e.target.value);
                  const next = courses.map((c, i) => (i === index ? { ...c, progress } : c));
                  patch({ [key]: next });
                }}
                placeholder="0–100"
              />
              <p className="text-[10px] text-slate-500 mt-1">Controls the progress bar width and percentage label (0–100).</p>
            </div>
            <div>
              <label className={labelCls}>Progress Color</label>
              <div className="flex gap-2 items-center">
                <input
                  type="color"
                  value={
                    course.progress_color?.startsWith("#")
                      ? course.progress_color
                      : ACCENT_COLOR_HEX[color] ?? DEFAULT_PROGRESS_COLOR
                  }
                  onChange={(e) => {
                    const next = courses.map((c, i) =>
                      i === index ? { ...c, progress_color: e.target.value } : c
                    );
                    patch({ [key]: next });
                  }}
                  className="h-10 w-12 rounded border border-slate-200 cursor-pointer shrink-0"
                  title="Pick progress bar color"
                />
                <Input
                  value={course.progress_color}
                  onChange={(e) => {
                    const next = courses.map((c, i) =>
                      i === index ? { ...c, progress_color: e.target.value } : c
                    );
                    patch({ [key]: next });
                  }}
                  placeholder="#9E9A14"
                  className="font-mono text-sm"
                />
              </div>
              <p className="text-[10px] text-slate-500 mt-1">Independent per course and per quarter.</p>
            </div>
          </div>
          <div>
            <label className={labelCls}>How this builds toward assessment</label>
            <textarea
              value={course.howBuilds}
              onChange={(e) => {
                const next = courses.map((c, i) => (i === index ? { ...c, howBuilds: e.target.value } : c));
                patch({ [key]: next });
              }}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div>
            <label className={labelCls}>Big idea</label>
            <Input
              value={course.bigIdea}
              onChange={(e) => {
                const next = courses.map((c, i) => (i === index ? { ...c, bigIdea: e.target.value } : c));
                patch({ [key]: next });
              }}
            />
          </div>
          <div>
            <label className={labelCls}>Essential question</label>
            <Input
              value={course.courseEssentialQuestion}
              onChange={(e) => {
                const next = courses.map((c, i) =>
                  i === index ? { ...c, courseEssentialQuestion: e.target.value } : c
                );
                patch({ [key]: next });
              }}
            />
          </div>
          <div>
            <label className={labelCls}>Course narrative</label>
            <textarea
              value={course.courseNarrative}
              onChange={(e) => {
                const next = courses.map((c, i) => (i === index ? { ...c, courseNarrative: e.target.value } : c));
                patch({ [key]: next });
              }}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div>
            <label className={labelCls}>Key skills (one per line)</label>
            <textarea
              value={linesValue(course.keySkills)}
              onChange={(e) => {
                const next = courses.map((c, i) =>
                  i === index ? { ...c, keySkills: parseLines(e.target.value) } : c
                );
                patch({ [key]: next });
              }}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div>
            <label className={labelCls}>Standards (one per line)</label>
            <textarea
              value={linesValue(course.standards)}
              onChange={(e) => {
                const next = courses.map((c, i) =>
                  i === index ? { ...c, standards: parseLines(e.target.value) } : c
                );
                patch({ [key]: next });
              }}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div>
            <label className={labelCls}>Portfolio evidence (one per line)</label>
            <textarea
              value={linesValue(course.portfolio)}
              onChange={(e) => {
                const next = courses.map((c, i) =>
                  i === index ? { ...c, portfolio: parseLines(e.target.value) } : c
                );
                patch({ [key]: next });
              }}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div>
            <label className={labelCls}>Questions at home (one per line)</label>
            <textarea
              value={linesValue(course.questionsAtHome)}
              onChange={(e) => {
                const next = courses.map((c, i) =>
                  i === index ? { ...c, questionsAtHome: parseLines(e.target.value) } : c
                );
                patch({ [key]: next });
              }}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div>
            <label className={labelCls}>Gap skills</label>
            <Input
              value={course.gapSkills}
              onChange={(e) => {
                const next = courses.map((c, i) => (i === index ? { ...c, gapSkills: e.target.value } : c));
                patch({ [key]: next });
              }}
            />
          </div>
        </CardEditPanel>
      ))}
    </CardEditGroup>
  );

  return (
    <div>
      <div className="sticky top-0 z-10 -mx-1 mb-4 bg-white pb-3 border-b border-slate-200">
        <p className="text-xs text-slate-500 mb-2">
          Current tab: <span className="font-semibold text-slate-700">{EDITOR_TABS.find((t) => t.id === editorTab)?.label}</span>
          {" — "}unsaved changes are kept while switching tabs; click Save to apply.
        </p>
        <div className="flex flex-wrap gap-1.5">
          {EDITOR_TABS.map((tab) => (
            <button
              key={tab.id}
              type="button"
              onClick={() => setEditorTab(tab.id)}
              className={`px-3 py-1.5 rounded-md border text-sm font-medium whitespace-nowrap ${
                editorTab === tab.id
                  ? "bg-slate-900 text-white border-slate-900"
                  : "bg-white text-slate-700 border-slate-300 hover:bg-slate-50"
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {editorTab === "general" && (
        <div>
          <p className="text-sm font-semibold text-slate-700 mb-3">Tab labels & theme</p>
          <div className={formRow}>
            <label className={labelCls}>Courses tab label</label>
            <Input value={coursesTabLabel} onChange={(e) => patch({ coursesTabLabel: e.target.value })} />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Assessment tab label</label>
            <Input value={assessmentTabLabel} onChange={(e) => patch({ assessmentTabLabel: e.target.value })} />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Evidence tab label</label>
            <Input value={evidenceTabLabel} onChange={(e) => patch({ evidenceTabLabel: e.target.value })} />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Inquiry tab label</label>
            <Input value={inquiryTabLabel} onChange={(e) => patch({ inquiryTabLabel: e.target.value })} />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Growth tab label</label>
            <Input value={growthTabLabel} onChange={(e) => patch({ growthTabLabel: e.target.value })} />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Accent color</label>
            <select value={color} onChange={(e) => patch({ color: e.target.value })} className={selectCls}>
              <option value="moss">Moss</option>
              <option value="deep-sea">Deep Sea</option>
              <option value="valencia">Valencia</option>
              <option value="sunflower">Sunflower</option>
            </select>
          </div>

          <p className="text-sm font-semibold text-slate-700 mb-3 mt-6">Bottom navigation</p>
          <p className="text-[10px] text-slate-500 mb-3">
            Matches the reference quarter page footer: previous (left), Overview (center), next (right). Leave a side empty to hide that link.
          </p>
          <div className={formRow}>
            <label className="flex items-center gap-2 text-sm font-medium text-slate-700">
              <input
                type="checkbox"
                checked={content.showNav !== false && content.showNav !== "false"}
                onChange={(e) => patch({ showNav: e.target.checked })}
              />
              Show bottom navigation
            </label>
          </div>
          <div className="grid sm:grid-cols-2 gap-3">
            <div className={formRow}>
              <label className={labelCls}>Previous label</label>
              <Input
                value={(content.navPrevLabel as string) ?? ""}
                onChange={(e) => patch({ navPrevLabel: e.target.value })}
                placeholder="e.g. Q1: The Nature Investigator"
              />
            </div>
            <div className={formRow}>
              <label className={labelCls}>Previous URL</label>
              <Input
                value={(content.navPrevHref as string) ?? ""}
                onChange={(e) => patch({ navPrevHref: e.target.value })}
                placeholder="e.g. /quarter/1"
              />
            </div>
            <div className={formRow}>
              <label className={labelCls}>Center label</label>
              <Input
                value={(content.navCenterLabel as string) ?? "Overview"}
                onChange={(e) => patch({ navCenterLabel: e.target.value })}
                placeholder="Overview"
              />
            </div>
            <div className={formRow}>
              <label className={labelCls}>Center URL</label>
              <Input
                value={(content.navCenterHref as string) ?? "/"}
                onChange={(e) => patch({ navCenterHref: e.target.value })}
                placeholder="/"
              />
            </div>
            <div className={formRow}>
              <label className={labelCls}>Next label</label>
              <Input
                value={(content.navNextLabel as string) ?? ""}
                onChange={(e) => patch({ navNextLabel: e.target.value })}
                placeholder="e.g. Q2: The Data Scientist"
              />
            </div>
            <div className={formRow}>
              <label className={labelCls}>Next URL</label>
              <Input
                value={(content.navNextHref as string) ?? ""}
                onChange={(e) => patch({ navNextHref: e.target.value })}
                placeholder="e.g. /quarter/2"
              />
            </div>
          </div>
        </div>
      )}

      {editorTab === "lenses" && (
        <div>
          <p className="text-sm font-semibold text-slate-700 mb-3">How Each Course Sees This Quarter</p>
          <div className={formRow}>
            <label className={labelCls}>Main heading</label>
            <Input
              value={lensesTitle}
              onChange={(e) => patch({ lensesTitle: e.target.value, title: e.target.value })}
            />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Description</label>
            <textarea
              value={lensesSubtitle}
              onChange={(e) => patch({ lensesSubtitle: e.target.value, subtitle: e.target.value })}
              rows={2}
              className={textareaCls}
            />
          </div>
          <CardEditGroup
            label="Lens cards"
            layout="grid-3"
            onAdd={() =>
              patch({
                lensesItems: [...lensesItems, { name: "", emoji: "📚", type: "core", lens: "" }],
                items: [...lensesItems, { name: "", emoji: "📚", type: "core", lens: "" }],
              })
            }
            addLabel="Add lens card"
            hint="Optional override. Leave empty to auto-build from Core/DNA course lens fields."
            isEmpty={lensesItems.length === 0}
            emptyMessage="No override cards. Frontend will use course.lens from Core + DNA."
          >
            {lensesItems.map((item, index) => (
              <CardEditPanel
                key={index}
                index={index}
                total={lensesItems.length}
                layout="grid-3"
                label={item.name}
                preview={{ emoji: item.emoji, title: item.name, subtitle: item.lens }}
                onRemove={() => {
                  const next = lensesItems.filter((_, i) => i !== index);
                  patch({ lensesItems: next, items: next });
                }}
              >
                <div className="flex gap-2 flex-wrap items-end">
                  <EmojiPickerField
                    compact
                    value={item.emoji}
                    onChange={(v) => {
                      const next = lensesItems.map((c, i) => (i === index ? { ...c, emoji: v } : c));
                      patch({ lensesItems: next, items: next });
                    }}
                  />
                  <Input
                    className="flex-1 min-w-[100px]"
                    value={item.name}
                    onChange={(e) => {
                      const next = lensesItems.map((c, i) => (i === index ? { ...c, name: e.target.value } : c));
                      patch({ lensesItems: next, items: next });
                    }}
                    placeholder="Course name"
                  />
                  <select
                    value={item.type}
                    onChange={(e) => {
                      const next = lensesItems.map((c, i) => (i === index ? { ...c, type: e.target.value } : c));
                      patch({ lensesItems: next, items: next });
                    }}
                    className="rounded-md border border-input bg-background px-2 py-1.5 text-sm w-20 h-10"
                  >
                    <option value="core">core</option>
                    <option value="dna">dna</option>
                  </select>
                </div>
                <textarea
                  value={item.lens}
                  onChange={(e) => {
                    const next = lensesItems.map((c, i) => (i === index ? { ...c, lens: e.target.value } : c));
                    patch({ lensesItems: next, items: next });
                  }}
                  rows={2}
                  className={textareaCls}
                  placeholder="Lens description"
                />
              </CardEditPanel>
            ))}
          </CardEditGroup>
        </div>
      )}

      {editorTab === "core" && (
        <div>
          <p className="text-sm font-semibold text-slate-700 mb-3">Core Courses</p>
          <div className={formRow}>
            <label className={labelCls}>Heading</label>
            <Input value={coreHeading} onChange={(e) => patch({ coreHeading: e.target.value })} />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Subtitle</label>
            <Input value={coreSubtitle} onChange={(e) => patch({ coreSubtitle: e.target.value })} />
          </div>
          {renderCourseList(coreCourses, "coreCourses", "core", "Core course cards")}
        </div>
      )}

      {editorTab === "dna" && (
        <div>
          <p className="text-sm font-semibold text-slate-700 mb-3">DNA Strand Courses</p>
          <div className={formRow}>
            <label className={labelCls}>Heading</label>
            <Input value={dnaHeading} onChange={(e) => patch({ dnaHeading: e.target.value })} />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Subtitle</label>
            <Input value={dnaSubtitle} onChange={(e) => patch({ dnaSubtitle: e.target.value })} />
          </div>
          {renderCourseList(dnaCourses, "dnaCourses", "dna", "DNA course cards")}
        </div>
      )}

      {editorTab === "assessment" && (
        <div>
          <p className="text-sm font-semibold text-slate-700 mb-3">Assessment</p>
          <div className="space-y-3">
            {assessmentItems.map((item, index) => (
              <div key={index} className="p-3 border border-slate-200 rounded-lg space-y-2">
                <div className="flex gap-2 items-center">
                  <EmojiPickerField
                    compact
                    value={item.icon}
                    onChange={(v) => {
                      const next = assessmentItems.map((c, i) => (i === index ? { ...c, icon: v } : c));
                      patch({ assessmentItems: next });
                    }}
                  />
                  <Input
                    className="flex-1"
                    value={item.title}
                    onChange={(e) => {
                      const next = assessmentItems.map((c, i) =>
                        i === index ? { ...c, title: e.target.value } : c
                      );
                      patch({ assessmentItems: next });
                    }}
                    placeholder="Title"
                  />
                  <button
                    type="button"
                    onClick={() => patch({ assessmentItems: assessmentItems.filter((_, i) => i !== index) })}
                    className="p-1.5 text-red-600 hover:bg-red-50 rounded"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
                <textarea
                  value={item.content}
                  onChange={(e) => {
                    const next = assessmentItems.map((c, i) =>
                      i === index ? { ...c, content: e.target.value } : c
                    );
                    patch({ assessmentItems: next });
                  }}
                  rows={2}
                  className={textareaCls}
                />
              </div>
            ))}
          </div>
          <button
            type="button"
            onClick={() =>
              patch({ assessmentItems: [...assessmentItems, { title: "", icon: "📋", content: "" }] })
            }
            className="mt-2 inline-flex items-center gap-1.5 px-2.5 py-1.5 text-sm font-medium rounded-md border border-slate-300 bg-white hover:bg-slate-50"
          >
            <Plus size={14} /> Add assessment item
          </button>
          <div className={`${formRow} mt-4`}>
            <label className={labelCls}>5P rubric labels (one per line)</label>
            <textarea
              value={rubricLabels.join("\n")}
              onChange={(e) => patch({ rubricLabels: parseLines(e.target.value) })}
              rows={3}
              className={textareaCls}
            />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Summary title</label>
            <Input
              value={assessmentSummaryTitle}
              onChange={(e) => patch({ assessmentSummaryTitle: e.target.value })}
            />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Summary body</label>
            <textarea
              value={assessmentSummary}
              onChange={(e) => patch({ assessmentSummary: e.target.value })}
              rows={3}
              className={textareaCls}
            />
          </div>
        </div>
      )}

      {editorTab === "evidence" && (
        <div>
          <p className="text-sm font-semibold text-slate-700 mb-3">Evidence</p>
          <div className={formRow}>
            <label className={labelCls}>Title</label>
            <Input value={evidenceTitle} onChange={(e) => patch({ evidenceTitle: e.target.value })} />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Subtitle</label>
            <textarea
              value={evidenceSubtitle}
              onChange={(e) => patch({ evidenceSubtitle: e.target.value })}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div className={formRow}>
            <div className="flex items-center justify-between gap-2 mb-2">
              <label className={labelCls} style={{ marginBottom: 0 }}>
                Evidence items
              </label>
              <button
                type="button"
                onClick={addEvidenceItem}
                className="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-sm font-medium rounded-md border border-slate-300 bg-white hover:bg-slate-50"
              >
                <Plus size={14} /> Add Evidence Item
              </button>
            </div>
            <p className="text-[10px] text-slate-500 mb-2">
              Each item appears as a numbered card on the frontend. Stored as an array in component JSON.
            </p>
            {evidenceItems.length === 0 ? (
              <p className="text-sm text-slate-500 p-3 border border-dashed border-slate-300 rounded-lg bg-slate-50/50">
                No evidence items yet. Click &quot;Add Evidence Item&quot; to create one.
              </p>
            ) : (
              <div className="space-y-2">
                {evidenceItems.map((item, index) => (
                  <div
                    key={index}
                    className="flex gap-2 items-start p-3 border border-slate-200 rounded-lg bg-white"
                  >
                    <span className="text-xs font-semibold text-slate-500 mt-2.5 w-12 shrink-0">
                      Item {index + 1}
                    </span>
                    <Input
                      value={item}
                      onChange={(e) => updateEvidenceItem(index, e.target.value)}
                      placeholder="e.g. Observation journal (3+ entries with drawings, labels, and dictation)"
                      className="flex-1"
                    />
                    <div className="flex items-center gap-0.5 shrink-0 pt-0.5">
                      <button
                        type="button"
                        onClick={() => moveEvidenceItem(index, -1)}
                        disabled={index === 0}
                        className="p-1.5 rounded hover:bg-slate-100 disabled:opacity-30"
                        title="Move up"
                      >
                        <ChevronUp size={16} />
                      </button>
                      <button
                        type="button"
                        onClick={() => moveEvidenceItem(index, 1)}
                        disabled={index === evidenceItems.length - 1}
                        className="p-1.5 rounded hover:bg-slate-100 disabled:opacity-30"
                        title="Move down"
                      >
                        <ChevronDown size={16} />
                      </button>
                      <button
                        type="button"
                        onClick={() => removeEvidenceItem(index)}
                        className="p-1.5 text-red-600 hover:bg-red-50 rounded"
                        title="Delete"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {editorTab === "inquiry" && (
        <div>
          <p className="text-sm font-semibold text-slate-700 mb-3">Inquiry Questions</p>
          <div className={formRow}>
            <label className={labelCls}>Title</label>
            <Input value={inquiryTitle} onChange={(e) => patch({ inquiryTitle: e.target.value })} />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Subtitle</label>
            <textarea
              value={inquirySubtitle}
              onChange={(e) => patch({ inquirySubtitle: e.target.value })}
              rows={2}
              className={textareaCls}
            />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Why-prefix label</label>
            <Input value={inquiryWhyPrefix} onChange={(e) => patch({ inquiryWhyPrefix: e.target.value })} />
          </div>
          <div className="space-y-3">
            {deepInquiry.map((item, index) => (
              <div key={index} className="p-3 border border-slate-200 rounded-lg space-y-2">
                <Input
                  value={item.question}
                  onChange={(e) => {
                    const next = deepInquiry.map((c, i) =>
                      i === index ? { ...c, question: e.target.value } : c
                    );
                    patch({ deepInquiry: next });
                  }}
                  placeholder="Question"
                />
                <Input
                  value={item.why}
                  onChange={(e) => {
                    const next = deepInquiry.map((c, i) => (i === index ? { ...c, why: e.target.value } : c));
                    patch({ deepInquiry: next });
                  }}
                  placeholder="Why this matters"
                />
                <button
                  type="button"
                  onClick={() => patch({ deepInquiry: deepInquiry.filter((_, i) => i !== index) })}
                  className="p-1.5 text-red-600 hover:bg-red-50 rounded text-sm inline-flex items-center gap-1"
                >
                  <Trash2 size={14} /> Remove
                </button>
              </div>
            ))}
          </div>
          <button
            type="button"
            onClick={() => patch({ deepInquiry: [...deepInquiry, { question: "", why: "" }] })}
            className="mt-2 inline-flex items-center gap-1.5 px-2.5 py-1.5 text-sm font-medium rounded-md border border-slate-300 bg-white hover:bg-slate-50"
          >
            <Plus size={14} /> Add inquiry question
          </button>
        </div>
      )}

      {editorTab === "growth" && (
        <div>
          <p className="text-sm font-semibold text-slate-700 mb-3">Growth Portrait</p>
          <div className={formRow}>
            <label className={labelCls}>Quarter ID</label>
            <Input
              type="number"
              min={1}
              value={quarterId}
              onChange={(e) => patch({ quarterId: e.target.value ? parseInt(e.target.value, 10) : 1 })}
              className="w-24"
            />
          </div>
          <div className={formRow}>
            <label className={labelCls}>Portrait title</label>
            <Input value={portraitTitle} onChange={(e) => patch({ portraitTitle: e.target.value })} />
          </div>
          <div className="space-y-3 mb-4">
            {portraitOfLearner.map((item, index) => (
              <div key={index} className="p-3 border border-slate-200 rounded-lg space-y-2">
                <div className="flex gap-2 flex-wrap items-center">
                  <EmojiPickerField
                    compact
                    value={item.emoji}
                    onChange={(v) => {
                      const next = portraitOfLearner.map((c, i) => (i === index ? { ...c, emoji: v } : c));
                      patch({ portraitOfLearner: next });
                    }}
                  />
                  <Input
                    className="flex-1 min-w-[120px]"
                    value={item.dimension}
                    onChange={(e) => {
                      const next = portraitOfLearner.map((c, i) =>
                        i === index ? { ...c, dimension: e.target.value } : c
                      );
                      patch({ portraitOfLearner: next });
                    }}
                    placeholder="Dimension"
                  />
                  <Input
                    type="number"
                    min={0}
                    max={100}
                    className="w-16"
                    value={item.pct}
                    onChange={(e) => {
                      const pct = Math.min(100, Math.max(0, parseInt(e.target.value, 10) || 0));
                      const next = portraitOfLearner.map((c, i) => (i === index ? { ...c, pct } : c));
                      patch({ portraitOfLearner: next });
                    }}
                  />
                  <button
                    type="button"
                    onClick={() =>
                      patch({ portraitOfLearner: portraitOfLearner.filter((_, i) => i !== index) })
                    }
                    className="p-1.5 text-red-600 hover:bg-red-50 rounded"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
                <Input
                  value={item.description}
                  onChange={(e) => {
                    const next = portraitOfLearner.map((c, i) =>
                      i === index ? { ...c, description: e.target.value } : c
                    );
                    patch({ portraitOfLearner: next });
                  }}
                  placeholder="Description"
                />
              </div>
            ))}
          </div>
          <button
            type="button"
            onClick={() =>
              patch({
                portraitOfLearner: [
                  ...portraitOfLearner,
                  { dimension: "", emoji: "✨", pct: 50, description: "" },
                ],
              })
            }
            className="mb-4 inline-flex items-center gap-1.5 px-2.5 py-1.5 text-sm font-medium rounded-md border border-slate-300 bg-white hover:bg-slate-50"
          >
            <Plus size={14} /> Add dimension
          </button>
          <div className={formRow}>
            <label className={labelCls}>Fink&apos;s Taxonomy title</label>
            <Input value={finksTitle} onChange={(e) => patch({ finksTitle: e.target.value })} />
          </div>
          <div className="space-y-3">
            {finksTaxonomy.map((item, index) => (
              <div key={index} className="p-3 border border-slate-200 rounded-lg space-y-2">
                <div className="flex gap-2 items-center">
                  <EmojiPickerField
                    compact
                    value={item.emoji}
                    onChange={(v) => {
                      const next = finksTaxonomy.map((c, i) => (i === index ? { ...c, emoji: v } : c));
                      patch({ finksTaxonomy: next });
                    }}
                  />
                  <Input
                    className="flex-1"
                    value={item.category}
                    onChange={(e) => {
                      const next = finksTaxonomy.map((c, i) =>
                        i === index ? { ...c, category: e.target.value } : c
                      );
                      patch({ finksTaxonomy: next });
                    }}
                    placeholder="Category"
                  />
                  <button
                    type="button"
                    onClick={() => patch({ finksTaxonomy: finksTaxonomy.filter((_, i) => i !== index) })}
                    className="p-1.5 text-red-600 hover:bg-red-50 rounded"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
                <Input
                  value={item.description}
                  onChange={(e) => {
                    const next = finksTaxonomy.map((c, i) =>
                      i === index ? { ...c, description: e.target.value } : c
                    );
                    patch({ finksTaxonomy: next });
                  }}
                  placeholder="Description"
                />
              </div>
            ))}
          </div>
          <button
            type="button"
            onClick={() =>
              patch({ finksTaxonomy: [...finksTaxonomy, { category: "", emoji: "📚", description: "" }] })
            }
            className="mt-2 inline-flex items-center gap-1.5 px-2.5 py-1.5 text-sm font-medium rounded-md border border-slate-300 bg-white hover:bg-slate-50"
          >
            <Plus size={14} /> Add Fink category
          </button>
        </div>
      )}
    </div>
  );
}
