"use client";
import React, { useState, useRef, useEffect } from "react";
import { useMasterDataStore } from "../store/masterDataStore";
import { useTemplateStore } from "../store/templateStore";
import { usePrescriptionStore } from "../store/prescriptionStore";
import { useSymptomStore } from "../store/symptomStore";
import { useDiagnosisStore } from "../store/diagnosisStore";
import { useInvestigationStore } from "../store/investigationStore";
import { useMedicineStore } from "../store/medicineStore";
import Sidebar, { Icon } from "@/components/modals/ui/Sidebar";
import { useUserStore } from "@/app/store/userStore";
import NextLink from "next/link";
import { Printer, Plus, Heart, Search, TrendingUp, ScanLine } from "lucide-react";
import { loc, buildLabels, getDoseSuffix, formatMealMethod } from "../lib/localization";

import {
  Pill,
  Syringe,
  FlaskConical,
  Droplets,
  Package,
  Bandage,
  Users,
  Baby,
  User,
  PersonStanding,
  Trash2,
} from "lucide-react";
import { DEFAULT_PREFERENCES } from "../lib/defaultPreferences";

/* ═══════════════════════════════════════════════════════
   TYPES
═══════════════════════════════════════════════════════ */
interface PatientData {
  name: string; age: string; ageUnit: "Y" | "M";
  gender: number; // -1 Default, 0 Male, 1 Female, 2 Rather not to say
  weight: string; bp: string; pulse: string; spo2: string; temp: string;
}
interface Medicine {
  name: string; type: string; dosage: string; duration: string; note: string;
  id?: string;
  // Granular fields used by the Confirmation-of-Medicines screen so each
  // value (dose / frequency / qty) can be edited independently. `dosage`
  // and `duration` above are kept in sync from these whenever they change,
  // so anything else in the file that still reads `dosage`/`duration`
  // keeps working unmodified.
  dose?: string;
  frequency?: string;
  qty?: string;
}

interface ApiMedicine {
  id: string; name: string; type: string;
  dose: string; dose_frequency: string; meal_time: string; qty: string;
  patient_type: string; used: number;
}
interface ApiSymptom { id: string; drLang: string; ptLang: string; }
interface ApiDiagnosis { id: string; diagnosisDrLang: string; diagnosisPtLang: string; }
interface ApiInvestigation { id: string; investigationDrLang: string; investigationPtLang: string; }
interface ApiInstruction {
  id: string; symptomName: string;
  shouldDo: string; shouldNotDo: string; extra: string;
}
interface ApiDoseFrequency { id: string; drLang: string; ptLang: string; }
interface UserPreferences {
  page_size?: string;
  page_height_mm?: number;
  page_width_mm?: number;
  [key: string]: any;
}


/* ═══════════════════════════════════════════════════════
   PAPER SIZE — mirrors the Swift PaperSize enum
   Used to derive the correct width/height ratio for the
   prescription preview, driven by user_preferences.page_size
═══════════════════════════════════════════════════════ */
const PAPER_SIZES: Record<string, { widthMm: number; heightMm: number }> = {
  A4: { widthMm: 210.0, heightMm: 297.0 },
  A5: { widthMm: 148.0, heightMm: 210.0 },
  A6: { widthMm: 105.0, heightMm: 148.0 },
  Letter: { widthMm: 215.9, heightMm: 279.4 },
  B4: { widthMm: 250.0, heightMm: 353.0 },
  B5: { widthMm: 176.0, heightMm: 250.0 },
};
const DEFAULT_PAPER_SIZE = "A4";

function getPaperDimensions(userPreferences: UserPreferences | undefined | null) {
  // Source of truth is ALWAYS the named page_size (A4/A5/A6/Letter/B4/B5),
  // matched against the known paper size table. Custom page_width_mm /
  // page_height_mm values are intentionally ignored — they're often stale  
  // generic defaults in the API response and do not reflect the real size.
  const rawSize = userPreferences?.page_size;
  if (rawSize) {
    const normalized = Object.keys(PAPER_SIZES).find(
      key => key.toLowerCase() === String(rawSize).toLowerCase()
    );
    if (normalized) return PAPER_SIZES[normalized];
  }

  // Fallback when page_size is missing or unrecognized
  return PAPER_SIZES[DEFAULT_PAPER_SIZE];
}

/* ═══════════════════════════════════════════════════════
   CONSTANTS
═══════════════════════════════════════════════════════ */
const MED_TABS = ["Tablet", "Capsule", "Syrup", "Drops", "Oint", "Powder", "Injection", "Surg. Items"];

const MED_TYPE_PILLS = [
  { label: "Tablet", icon: Pill },
  { label: "Capsule", icon: Pill },
  { label: "Syrup", icon: FlaskConical },
  { label: "Drops", icon: Droplets },
  { label: "Oint", icon: Bandage },
  { label: "Powder", icon: Package },
  { label: "Injection", icon: Syringe },
  { label: "Surg. Items", icon: Bandage },
];

const FOR_WHOM = [
  { label: "All", icon: Users },
  { label: "Pediatric", icon: Baby },
  { label: "Adult", icon: User },
  { label: "Geriatric", icon: PersonStanding },
];

const QUICK_FU = ["3 days", "5 days", "10 days", "1 week", "2 weeks", "1 month", "1 month 15 days", "2 months", "3 months"];
const FU_DAYS: Record<string, number> = {
  "3 days": 3, "5 days": 5, "10 days": 10, "1 week": 7, "2 weeks": 14,
  "1 month": 30, "1 month 15 days": 45, "2 months": 60, "3 months": 90,
};

const STEPS = [
  { label: "Patient Info" },
  { label: "Symptoms" },
  { label: "Diagnoses" },
  { label: "Investigations" },
  { label: "Medicines" },
  { label: "Instructions" },
  { label: "Follow-up" },
];

/* ═══════════════════════════════════════════════════════
   PER-TYPE DOSE / QUANTITY OPTION TABLES
   — hoisted to module scope, mirroring the iOS
   MedicineType.defaultDose / defaultQuantity source of
   truth (see MedicineType.swift), so both the "Add
   medicine to catalog" modal and the new "Confirmation of
   Medicines" screen read from the exact same data instead
   of keeping separate, slightly-different copies.
═══════════════════════════════════════════════════════ */
const DOSE_OPTIONS_BY_TYPE: Record<string, string[]> = {
  Tablet: ["½", "1", "1½", "2", "2½", "3", "3½", "4", "4½", "5"],
  Capsule: ["½", "1", "1½", "2", "2½", "3", "3½", "4", "4½", "5"],
  Powder: ["½", "1", "1½", "2", "2½", "3", "3½", "4", "4½", "5"],
  Injection: ["½", "1", "1½", "2", "2½", "3", "3½", "4", "4½", "5"],
  Syrup: ["½", "1", "1½", "2", "2½", "3", "5", "7½", "10", "15", "20"],
  Drops: ["1", "2", "5", "7", "10", "12", "15"],
  Oint: [], // iOS: MedicineType.oint.defaultDose == []
};

const QTY_OPTIONS_BY_TYPE: Record<string, string[]> = {
  // iOS: Array(1...10)
  Tablet: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
  Capsule: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
  Powder: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
  // iOS: Array(1...2)
  Syrup: ["1", "2"],
  Drops: ["1", "2"],
  Oint: ["1", "2"],
  Injection: ["1", "2"],
  // iOS: Array(1...5)
  "Surg. Items": ["1", "2", "3", "4", "5"],
};

const SIZE_OPTS = ["S", "M", "L", "XL", "XXL"];
const MEAL_OPTS = ["Before Meal", "After Meal"];
const METHOD_OPTS = ["IM", "IV"];
const ALL_FREQ = ["0-0-1", "0-1-0", "1-0-0", "1-0-1", "1-1-1", "1-1-1Inv", "HS"];

/** Which fields a medicine type shows, and which option list each one uses.
 *  Mirrors the branching in MedicineType.options (Swift). */
function getMedicineFieldConfig(type: string) {
  const showSize = type === "Surg. Items";
  const showDose = showSize || (DOSE_OPTIONS_BY_TYPE[type]?.length ?? 0) > 0;
  const showFreq = ["Tablet", "Capsule", "Syrup", "Drops", "Oint", "Powder", "Injection"].includes(type);
  const showMeal = ["Tablet", "Capsule", "Syrup", "Drops", "Oint", "Powder"].includes(type);
  const showMethod = type === "Injection";

  const doseLabel = showSize
    ? "Size"
    : type === "Syrup" || type === "Injection"
      ? "Dose (in ml)"
      : type === "Drops"
        ? "Dose (in Drops)"
        : "Dose";

  const doseOptions = showSize ? SIZE_OPTS : (DOSE_OPTIONS_BY_TYPE[type] ?? []);
  const qtyOptions = QTY_OPTIONS_BY_TYPE[type] ?? QTY_OPTIONS_BY_TYPE.Tablet;

  return { showDose, doseLabel, doseOptions, showFreq, showMeal, showMethod, qtyOptions };
}

/* ═══════════════════════════════════════════════════════
   DESIGN TOKENS
═══════════════════════════════════════════════════════ */
const C = {
  pink: "#f06292",
  pinkHover: "#e8579a",
  pinkLight: "#fce4ef",
  pinkBorder: "#f48fb1",
  purple: "#3a1280",
  purpleMid: "#5b2fc9",
  purpleLight: "#f0ecfb",
  bg: "#f5f5f7",
  white: "#ffffff",
  cardBorder: "#e8e2f0",
  textMain: "#1a1a2e",
  textSub: "#6b6b8a",
  textHint: "#b0adc8",
  fieldBg: "#f0ecf8",
  chipBorder: "#ddd8ee",
};

/* ═══════════════════════════════════════════════════════
   BUILD PAYLOAD
═══════════════════════════════════════════════════════ */
function buildPayload(
  patient: PatientData,
  symptoms: string[],
  diagnosis: string,
  investigation: string,
  medicines: Medicine[],
  followup: string,
  selected: { lang: string; groupIndex: number } | null,
  apiInstructions: ApiInstruction[],
  userPreferences: UserPreferences,
) {
  const language = userPreferences?.prescription_language;

  let shouldDo = "", shouldNotDo = "", extra = "";
  if (selected !== null) {
    const inst = apiInstructions[selected.groupIndex];
    if (inst) { shouldDo = inst.shouldDo; shouldNotDo = inst.shouldNotDo; extra = inst.extra; }
  }

  const patient_gender_text =
    (patient.gender === 0 || patient.gender === 1)
      ? (patient.gender === 0 ? "Male" : "Female")
      : "";

  return {
    patient_info: {
      patient_name: patient.name,
      patient_age_text: patient.age ? `${patient.age} ${patient.ageUnit}` : "",
      patient_gender_text,
      patient_weight: patient.weight
        ? `${patient.weight} ${loc("patient_weight_text", language)}`
        : "",

      patient_weight_text: patient.weight
        ? `${patient.weight} ${loc("patient_weight_text", language)}`
        : "",
      patient_bp: patient.bp, patient_pulse: patient.pulse,
      patient_spo2: patient.spo2, patient_temp: patient.temp,
      patient_visit_date: new Date().toLocaleDateString("en-IN", { dateStyle: "medium" }),
    },
    labels: buildLabels(language, followup),
    list_symptoms: symptoms.map(s => ({ ptLang: s, drLang: s })),
    list_medicines: medicines.map(m => ({
      medicineData: {
        name: m.name,
        type: m.type,
        dose: m.dose ?? "",
        doseSuffix: getDoseSuffix(m.type, language),
        meal_time: formatMealMethod(m.note ?? "", language),
        dose_frequency: m.frequency ?? m.dosage,
      },
      doseFrequencyData: { ptLang: m.dosage, drLang: m.dosage },
    })),
    patient_diagnosis: diagnosis,
    patient_investigation: investigation,
    instruction: { shouldDo, shouldNotDo, extra },
    is_signature_required: userPreferences?.is_signature_required ?? false,
    is_doctor_info_required: userPreferences?.is_doctor_info_required ?? false,
  };
}

function buildCreatePrescriptionPayload(
  patient: PatientData, symptoms: string[], diagnosis: string,
  investigation: string, medicines: Medicine[]
) {
  const today = new Date().toISOString().split("T")[0];
  return {
    visit_date_local: today,
    patient_diagnosis: diagnosis,
    patient_investigation: investigation,
    list_symptoms: symptoms,
    medicineIds: medicines.filter(m => m.id).map(m => m.id as string),
    patient_info: {
      patient_visit_date: today,
      patient_name: patient.name,
      patient_age: patient.age,
      patient_age_in_years: patient.ageUnit === "Y" ? "1" : "0",
      patient_gender: patient.gender,             // ← NEW: -1, 0, 1, or 2
      patient_weight: patient.weight,
      patient_bp: patient.bp,
      patient_pulse: patient.pulse,
      patient_spo2: patient.spo2,
      patient_temp: patient.temp,
      patient_age_text: patient.age ? `${patient.age} ${patient.ageUnit}` : "",
      patient_weight_text: patient.weight ? `${patient.weight} kg` : "",
      patient_mobile: "",
      hospitalId: "",
    },
  };
}
/* ═══════════════════════════════════════════════════════
   MAIN COMPONENT
═══════════════════════════════════════════════════════ */
export default function PrescriptionWizard() {
  const { createPrescription } = usePrescriptionStore();
  const today = new Date().toISOString().split("T")[0];

  const [step, setStep] = useState(0);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const { addMedicine } = useMedicineStore();
  const { addSymptom } = useSymptomStore();
  const { addDiagnosis } = useDiagnosisStore();
  const { addInvestigation } = useInvestigationStore();

  const [patient, setPatient] = useState<PatientData>({
    name: "", age: "", ageUnit: "Y", gender: -1,
    weight: "", bp: "", pulse: "", spo2: "", temp: "",
  });

  const { masterData, fetchMasterData } = useMasterDataStore();

  const { user, loadUserFromStorage } = useUserStore();
  useEffect(() => {
    loadUserFromStorage();
  }, []);
  const { fetchTemplates } = useTemplateStore();
  const PAPER_ASPECT_RATIOS: Record<string, string> = {
    A4: "1 / 1.414",
    A5: "1 / 1.419",
    A6: "1 / 1.410",
    Letter: "1 / 1.294",
    B4: "1 / 1.412",
    B5: "1 / 1.420",
  };

  const apiSymptoms: ApiSymptom[] = (masterData as any)?.symptoms ?? [];
  const apiMedicines: ApiMedicine[] = (masterData as any)?.medicines ?? [];
  const apiDiagnoses: ApiDiagnosis[] = (masterData as any)?.diagnoses ?? [];
  const apiInvestigations: ApiInvestigation[] = (masterData as any)?.investigations ?? [];
  const apiInstructions: ApiInstruction[] = (masterData as any)?.instructions ?? [];
  // ── Saved dose-frequencies from the backend (e.g. "1-1-1" → "સવાર - બપોર - સાંજ") ──
  // Used to seed the Frequency pill list on the Confirmation-of-Medicines screen.
  const apiFrequencies: ApiDoseFrequency[] = (masterData as any)?.dose_frequencies ?? [];
  const userPreferences: UserPreferences = {
    ...DEFAULT_PREFERENCES,
    ...((masterData as any)?.user_preferences ?? {}),
  };
  const hospital = (masterData as any)?.hospitals?.[0];
  const fullHospitalAddress = [
    hospital?.address,
    hospital?.city,
    hospital?.state,
    hospital?.country,
    hospital?.pincode,
  ]
    .filter(Boolean)

  const paperAspectRatio =
    PAPER_ASPECT_RATIOS[userPreferences.page_size as keyof typeof PAPER_ASPECT_RATIOS];
  // ── Paper size → aspect ratio for the preview panel (height / width) ──
  const paperDimensions = getPaperDimensions(userPreferences);
  console.log("[PaperSize Debug]", {
    raw_page_size: userPreferences?.page_size,
    resolved_widthMm: paperDimensions.widthMm,
    resolved_heightMm: paperDimensions.heightMm,
    aspectRatio_height_over_width: paperAspectRatio,
  });
  console.log("user", user);
  console.log("hospital", hospital);
  // DEBUG: open DevTools → Console tab to see this on every render.
  // Only page_size drives the resolved dimensions now — page_width_mm/
  // page_height_mm are logged for reference only, not used in resolution.
  // Remove this useEffect once you've confirmed the ratio is correct.

  const [symptoms, setSymptoms] = useState<string[]>([]);
  const [selectedDiagnoses, setSelectedDiagnoses] = useState<string[]>([]);
  const [diagnosisText, setDiagnosisText] = useState("");
  const [selectedInvestigations, setSelectedInvestigations] = useState<string[]>([]);
  const [investigationText, setInvestigationText] = useState("");
  const [medicines, setMedicines] = useState<Medicine[]>([]);
  const [selectedInstruction, setSelectedInstruction] = useState<{ lang: string; groupIndex: number } | null>(null);
  const [followup, setFollowup] = useState("");

  // ── Confirmation-of-Medicines screen (new) ──
  // Shown after Step 4 (Medicines) before moving on to Instructions, so the
  // doctor can fine-tune dose / frequency / qty / meal-time per selected
  // medicine — mirrors the iOS "Confirmation of Medicines" screen.
  // NOTE: this now renders INLINE inside the left panel's own scrollable
  // area (instead of as a full-screen bottom-sheet overlay), so it sits on
  // the left side next to the live preview and scrolls with the same
  // scrollbar as every other step.
  const [showMedConfirm, setShowMedConfirm] = useState(false);
  // Custom dose/qty values added via the "+" popups, kept per medicine type,
  // for this session (merged on top of the DOSE/QTY_OPTIONS_BY_TYPE tables).
  const [customDoses, setCustomDoses] = useState<Record<string, string[]>>({});
  const [customQtys, setCustomQtys] = useState<Record<string, string[]>>({});
  // Custom frequency values added via the "+" popup — not type-specific.
  const [customFreqs, setCustomFreqs] = useState<string[]>([]);

  const [drSymptom, setDrSymptom] = useState("");
  const [ptSymptom, setPtSymptom] = useState("");
  const [drDiagnosis, setDrDiagnosis] = useState("");
  const [ptDiagnosis, setPtDiagnosis] = useState("");
  const [drInvestigation, setDrInvestigation] = useState("");
  const [ptInvestigation, setPtInvestigation] = useState("");

  const [showAddSymptom, setShowAddSymptom] = useState(false);
  const [showAddDiagnosis, setShowAddDiagnosis] = useState(false);
  const [showAddInvestigation, setShowAddInvestigation] = useState(false);



  const MIN_FONT_SIZE = 8;
  const MAX_FONT_SIZE = 16;

  const [fontSize, setFontSize] = useState<number>(
    userPreferences.font_size ?? DEFAULT_PREFERENCES.font_size
  );
  const [isFontBusy, setIsFontBusy] = useState(false);

  useEffect(() => {
    if (userPreferences?.font_size) {
      setFontSize(userPreferences.font_size);
    }
  }, [userPreferences?.font_size]);

  function adjustFont(increase: boolean) {

    console.group("========== FONT SIZE ==========");

    console.log("Current Font Size :", fontSize);
    console.log("Increase :", increase);
    console.log("Busy :", isFontBusy);

    if (isFontBusy) {
      console.warn("Skipped because font update is already in progress");
      console.groupEnd();
      return;
    }

    const currentSize = fontSize;
    let newSize: number;

    if (increase) {
      if (currentSize >= MAX_FONT_SIZE) {
        console.warn("Maximum font size reached :", MAX_FONT_SIZE);
        console.groupEnd();
        return;
      }
      newSize = currentSize + 1;
    } else {
      if (currentSize <= MIN_FONT_SIZE) {
        console.warn("Minimum font size reached :", MIN_FONT_SIZE);
        console.groupEnd();
        return;
      }
      newSize = currentSize - 1;
    }

    console.log("New Font Size :", newSize);

    setFontSize(newSize);

    setIsFontBusy(true);

    const win = iframeRef.current?.contentWindow as any;

    console.log("Iframe Window :", win);
    console.log("setFontSize exists :", typeof win?.setFontSize);

    if (win && typeof win.setFontSize === "function") {

      console.log("Calling iframe setFontSize...");
      console.log("Passing Value :", `${newSize}pt`);

      win.setFontSize(`${newSize}pt`);

      console.log("iframe setFontSize completed");

      setIsFontBusy(false);

    } else {

      console.error("iframe setFontSize() not available");

      setIsFontBusy(false);
    }

    console.groupEnd();
  }

  useEffect(() => { fetchMasterData(); fetchTemplates(); }, []);


  async function handleNext() {
    if (step === STEPS.length - 1) {
      try {
        const payload = buildCreatePrescriptionPayload(
          patient, symptoms, diagnosisText, investigationText, medicines
        );
        console.log("Final payload:", payload); // ← debug line

        await createPrescription(payload);
      } catch (error) { console.error(error); }
      return;
    }

    // ── Leaving the Medicines step: show the Confirmation-of-Medicines
    // screen first (if there's anything to confirm) instead of jumping
    // straight to Instructions. ──
    if (step === 4 && medicines.length > 0) {
      setShowMedConfirm(true);
      return;
    }

    setStep(s => s + 1);
  }
  const { templates } = useTemplateStore();

  const selectedTemplateId =
    (masterData as any)?.user_preferences?.selected_template_id;

  const selectedTemplate = templates.find(
    (t) => t.id === selectedTemplateId
  );

  const iframeSrc = selectedTemplate?.path_new
    ? `/api/template?path=${encodeURIComponent(selectedTemplate.path_new)}`
    : "/api/template";

  console.log("masterData", masterData);
  console.log("userPreferences", userPreferences);


  function handleIframeLoaded() {
    const win = iframeRef.current?.contentWindow as any;
    if (!win) return;

    // ── Step 1: configurePage
    // iOS: window.configurePage(paperSize, headerMM, footerMM, contentPadding, fontSize)
    if (typeof win.configurePage === "function") {

      const paperSize = userPreferences.page_size ?? "A4";
      const headerMM = `${userPreferences.page_header_size_mm}mm`;
      const footerMM = `${userPreferences.page_footer_size_mm}mm`;
      const leftMM = userPreferences.page_left_side_spacing;
      const rightMM = userPreferences.page_right_side_spacing;
      const bottomMM = userPreferences.page_footer_size_mm;

      console.log("configurePage called", {
        paperSize,
        headerMM,
        footerMM,
      });

      // iOS: "top:\(leftMM)mm;right:\(rightMM)mm;bottom:\(rightMM)mm;left:\(leftMM)mm"
      const contentPadding = `top:${leftMM}mm;right:${rightMM}mm;bottom:${bottomMM}mm;left:${leftMM}mm`;

      const fontSizePt = `${fontSize}pt`;

      win.configurePage(
        paperSize,
        headerMM,
        footerMM,
        contentPadding,
        fontSizePt
      );

    } else {
      console.warn("configurePage not found in iframe");
    }

    // ── Step 2: setPrescriptionData
    // iOS: window.setPrescriptionData(jsonData)
    if (typeof win.setPrescriptionData === "function") {

      const payload = buildPayload(
        patient,
        symptoms,
        diagnosisText,
        investigationText,
        medicines,
        followup,
        selectedInstruction,
        apiInstructions,
        userPreferences
      );

      console.log("Payload:", payload);
      console.log("Weight before template:", payload.patient_info.patient_weight);
      win.setPrescriptionData(payload);

    } else {
      console.warn("setPrescriptionData not found in iframe");
    }
    console.log("Address:", hospital?.address);
    // ── Step 3: setDoctorInfo or setHTML (header/footer)
    // iOS: if let info = doctorInfo { setDoctorInfo(...) } else { setHTML('header',''); setHTML('footer','') }
    if (typeof win.setDoctorInfo === "function") {

      if (userPreferences?.is_doctor_info_required) {

        win.setDoctorInfo(
          user?.fullname ?? "",
          "",
          user?.degree ?? "",
          user?.specialisation ?? "",
          hospital?.licenseNo ?? "",
          hospital?.phone ?? "",
          fullHospitalAddress,
          hospital?.clinicTimings ?? "",
          user?.email ?? "",
          hospital?.clinicSlogan ?? "",
          hospital?.name ?? "",
          true
        );

      } else if (typeof win.setHTML === "function") {

        win.setHTML("header", "");
        win.setHTML("footer", "");

      }

    }
    else if (typeof win.setHTML === "function") {

      // iOS: isLetterpadExport → setHTML('header', ''); setHTML('footer', '')
      // Web: printed_letterhead = true → header already on paper, clear JS header/footer
      if (userPreferences.printed_letterhead === true) {
        win.setHTML("header", "");
        win.setHTML("footer", "");
      }

    }
  }
  function handlePrint() {
    handleIframeLoaded();

    setTimeout(() => {
      const iframe = iframeRef.current;
      if (!iframe) return;

      const doc = iframe.contentDocument;
      const win = iframe.contentWindow;
      const paperSize = userPreferences.page_size ?? "A4";

      if (!doc || !win) return;

      // Inject temporary print style
      const style = doc.createElement("style");
      style.id = "print-margin-none";

      style.innerHTML = `
      @media print {
        @page {
          margin: 0 !important;
        }

        html,
        body {
          margin: 0 !important;
          padding: 0 !important;
        }
      }
    `;

      doc.head.appendChild(style);
      const leftMM = userPreferences.page_left_side_spacing;
      const rightMM = userPreferences.page_right_side_spacing;
      const bottomMM = userPreferences.page_footer_size_mm;

      const contentPadding = `top:${leftMM}mm;right:${rightMM}mm;bottom:${bottomMM}mm;left:${leftMM}mm`;

      if (typeof (win as any).configurePage === "function") {
        (win as any).configurePage(
          paperSize,
          `${userPreferences.page_header_size_mm}mm`,
          `${userPreferences.page_footer_size_mm}mm`,
          contentPadding,
          `${fontSize}pt`
        );
      }
      win.focus();
      win.print();

      // Remove style after print
      setTimeout(() => {
        style.remove();
      }, 1000);

    }, 200);
  }

  useEffect(() => {
    handleIframeLoaded();
  }, [
    patient,
    symptoms,
    medicines,
    diagnosisText,
    investigationText,
    followup,
    selectedInstruction
  ]);

  function handleBack() { if (step > 0) setStep(s => s - 1); }


  function handleClear() {
    if (step === 1) setSymptoms([]);
    if (step === 2) { setSelectedDiagnoses([]); setDiagnosisText(""); }
    if (step === 3) { setSelectedInvestigations([]); setInvestigationText(""); }
    if (step === 5) setSelectedInstruction(null);
    if (step === 6) setFollowup("");
  }

  const showClear = [1, 2, 3, 5, 6].includes(step);
  const isLastStep = step === STEPS.length - 1;
  const now = new Date().toLocaleString("en-IN", { month: "short", day: "numeric", year: "numeric" });

  const handleAddSymptom = async () => {
    const success = await addSymptom({ drLang: drSymptom, ptLang: ptSymptom });
    if (success) { setShowAddSymptom(false); setDrSymptom(""); setPtSymptom(""); }
  };
  const handleAddDiagnosis = async () => {
    const success = await addDiagnosis({ diagnosisDrLang: drDiagnosis, diagnosisPtLang: ptDiagnosis });
    if (success) { setShowAddDiagnosis(false); setDrDiagnosis(""); setPtDiagnosis(""); }
  };
  const handleAddInvestigation = async () => {
    const success = await addInvestigation({ investigationDrLang: drInvestigation, investigationPtLang: ptInvestigation });
    if (success) { setShowAddInvestigation(false); setDrInvestigation(""); setPtInvestigation(""); }
  };
  const BRAND = "#d4537e";

  const Icon = {
    Settings: () => (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="3" />
        <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
      </svg>
    ),
    Plus: () => (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <line x1="12" y1="5" x2="12" y2="19" />
        <line x1="5" y1="12" x2="19" y2="12" />
      </svg>
    ),
    History: () => (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="4" width="18" height="18" rx="2" />
        <line x1="16" y1="2" x2="16" y2="6" />
        <line x1="8" y1="2" x2="8" y2="6" />
        <line x1="3" y1="10" x2="21" y2="10" />
      </svg>
    ),
    Hospital: () => (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="7" width="20" height="14" rx="2" />
        <path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" />
      </svg>
    ),
    ChevronRight: () => (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="9 18 15 12 9 6" />
      </svg>
    ),
    Pill: () => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z" />
        <path d="m8.5 8.5 7 7" />
      </svg>
    ),
    Users: () => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
        <circle cx="9" cy="7" r="4" />
        <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
        <path d="M16 3.13a4 4 0 0 1 0 7.75" />
      </svg>
    ),
    FileCheck: () => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />
        <polyline points="14 2 14 8 20 8" />
        <polyline points="9 15 11 17 15 13" />
      </svg>
    ),
    Stethoscope: () => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4.8 2.3A.3.3 0 1 0 5 2H4a2 2 0 0 0-2 2v5a6 6 0 0 0 6 6v0a6 6 0 0 0 6-6V4a2 2 0 0 0-2-2h-1a.2.2 0 1 0 .3.3" />
        <path d="M8 15v1a6 6 0 0 0 6 6v0a6 6 0 0 0 6-6v-4" />
        <circle cx="20" cy="10" r="2" />
      </svg>
    ),
    Prescription: () => (
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18" />
      </svg>
    ),
    TrendUp: () => (
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="23 6 13.5 15.5 8.5 10.5 1 18" />
        <polyline points="17 6 23 6 23 12" />
      </svg>
    ),
    Lock: () => (
      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
        <path d="M7 11V7a5 5 0 0 1 10 0v4" />
      </svg>
    ),
    Star: () => (
      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
        <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
      </svg>
    ),
    Menu: () => (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <line x1="3" y1="6" x2="21" y2="6" />
        <line x1="3" y1="12" x2="21" y2="12" />
        <line x1="3" y1="18" x2="21" y2="18" />
      </svg>
    ),
  };

  const stepTitles = [
    "What is the patient's information?",
    "Select the patient's symptoms.",
    "Enter diagnosis.",
    "Enter investigations.",
    "Select medicines",
    "Instructions & advice.",
    "Set next follow-up date.",
  ];

  const stepSubs = [
    "Fill in the basic patient details below.",
    "Choose all that apply — you can add custom ones too.",
    "Type or pick from saved diagnoses.",
    "Type or pick from saved investigations.",
    "Add medicines with dosage and frequency.",
    "Choose dietary and care instructions.",
    "Quick-select or pick a specific date.",
  ];


  return (
    <div style={{
      display: "flex",
      width: "100%",
      height: "100vh",
      fontFamily: "'Inter', 'Segoe UI', sans-serif",
      overflow: "hidden",
      background: C.bg,
      flexDirection: "row",
    }}>
      <aside className="hidden md:block w-64 shrink-0 bg-white border-r border-[#e5e7eb] sticky top-0 h-screen">
        <Sidebar user={user} />
      </aside>

      {/* ════════════════════════════════════════
          LEFT PANEL
      ════════════════════════════════════════ */}
      <div style={{
        width: "50%",
        height: "100%",
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
        position: "relative",
        background: C.bg,
      }}>

        {/* Progress lines */}
        <div style={{ display: "flex", gap: 6, padding: "18px 24px 0", flexShrink: 0 }}>
          {STEPS.map((_, i) => (
            <div key={i} style={{
              flex: 1, height: 4, borderRadius: 2,
              background: i <= step ? C.pink : "#ddd8ee",
              transition: "background 0.3s ease",
            }} />
          ))}
        </div>

        {/* Step pill */}
        <div style={{ padding: "16px 24px 0", flexShrink: 0 }}>
          <div style={{
            display: "inline-flex", alignItems: "center",
            border: `1.5px solid ${C.pinkBorder}`,
            borderRadius: 24, padding: "5px 16px",
            fontSize: 11, fontWeight: 700, color: C.pink,
            letterSpacing: "0.07em", textTransform: "uppercase" as const,
          }}>
            {showMedConfirm ? "Confirm Medicines" : `Step ${step + 1} · ${STEPS[step].label}`}
          </div>
        </div>

        {/* Title */}
        <div style={{ padding: "10px 24px 0", flexShrink: 0 }}>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 800, color: C.textMain, lineHeight: 1.25 }}>
            {showMedConfirm ? "Confirmation of Medicines" : stepTitles[step]}
          </h2>
          <p style={{ margin: "6px 0 0", fontSize: 13, color: C.textSub, lineHeight: 1.5 }}>
            {showMedConfirm
              ? "Review and fine-tune dose, frequency & quantity for each medicine."
              : stepSubs[step]}
          </p>
        </div>

        {/* Scrollable content */}
        <div style={{
          flex: 1, overflowY: "auto",
          padding: "14px 24px",
          paddingBottom: showMedConfirm ? 84 : (step === 0 ? 14 : 84),
        }}>

          {showMedConfirm ? (
            /* ── Confirmation of Medicines — inline on the left, scrolls
               with this same container ── */
            <MedicineConfirmationList
              medicines={medicines}
              setMedicines={setMedicines}
              apiFrequencies={apiFrequencies}
              customDoses={customDoses}
              setCustomDoses={setCustomDoses}
              customQtys={customQtys}
              setCustomQtys={setCustomQtys}
              customFreqs={customFreqs}
              setCustomFreqs={setCustomFreqs}
            />
          ) : (
            <>
              {/* ════ STEP 0: Patient Info ════ */}

              {step === 0 && (
                <div style={S.card}>
                  <FieldLabel>Patient name</FieldLabel>
                  <input style={S.field} placeholder="Full name"
                    value={patient.name} onChange={e => setPatient(p => ({ ...p, name: e.target.value }))} />

                  <div style={{ display: "flex", gap: 10 }}>
                  
                    <div style={{ flex: 1 }}>
                      <FieldLabel>Weight (kg)</FieldLabel>
                      <input style={S.field} placeholder="e.g. 65"
                        value={patient.weight} onChange={e => setPatient(p => ({ ...p, weight: e.target.value }))} />
                    </div>
                      <div style={{ flex: 1 }}>
                      <FieldLabel>Age</FieldLabel>
                      <div style={{ display: "flex", gap: 6 }}>
                        <input style={{ ...S.field, flex: 1 }} placeholder="e.g. 32"
                          value={patient.age} onChange={e => setPatient(p => ({ ...p, age: e.target.value }))} />
                        <div style={{ display: "flex", borderRadius: 9, overflow: "hidden", border: `1.5px solid ${C.chipBorder}`, flexShrink: 0 }}>
                          {(["Y", "M"] as const).map(u => (
                            <button key={u} onClick={() => setPatient(p => ({ ...p, ageUnit: u }))} style={{
                              padding: "0 12px", border: "none", cursor: "pointer",
                              fontWeight: 700, fontSize: 13,
                              background: patient.ageUnit === u ? C.pink : C.white,
                              color: patient.ageUnit === u ? "#fff" : C.textSub,
                              transition: "all .15s",
                            }}>{u}</button>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* ── Gender ── */}
                  <div>
                    <FieldLabel>Gender</FieldLabel>
                    <div style={{ display: "flex", gap: 8 }}>
                      {([
                        { label: "Male", value: 0 },
                        { label: "Female", value: 1 },
                        { label: "Rather not to say", value: 2 },
                      ] as const).map(({ label, value }) => {
                        const sel = patient.gender === value;
                        return (
                          <button
                            key={value}
                            onClick={() => setPatient(p => ({ ...p, gender: sel ? -1 : value }))}
                            style={{
                              flex: 1,
                              padding: "10px 6px",
                              borderRadius: 9,
                              border: `1.5px solid ${sel ? C.pink : C.chipBorder}`,
                              background: sel ? C.pink : C.white,
                              color: sel ? "#fff" : C.textMain,
                              fontWeight: 600,
                              fontSize: 12,
                              cursor: "pointer",
                              transition: "all .15s",
                            }}
                          >
                            {label}
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  <div style={{ borderTop: `1px solid ${C.cardBorder}`, paddingTop: 10, marginTop: 2 }}>
                    <FieldLabel>Vitals</FieldLabel>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                      {[
                        { label: "BP (mmHg)", key: "bp", val: patient.bp, ph: "120/80" },
                        { label: "Pulse (bpm)", key: "pulse", val: patient.pulse, ph: "72" },
                        { label: "SpO₂ (%)", key: "spo2", val: patient.spo2, ph: "98" },
                        { label: "Temperature", key: "temp", val: patient.temp, ph: "98.6°F" },
                      ].map(({ label, key, val, ph }) => (
                        <div key={key}>
                          <div style={{ fontSize: 11, fontWeight: 600, color: C.textSub, marginBottom: 5 }}>{label}</div>
                          <input style={S.field} placeholder={ph}
                            value={val} onChange={e => setPatient(p => ({ ...p, [key]: e.target.value }))} />
                        </div>
                      ))}
                    </div>
                  </div>

                  <button onClick={handleNext} style={{ ...S.pinkBtn, marginTop: 4 }}>Next</button>
                </div>
              )}

              {/* ════ STEP 1: Symptoms ════ */}
              {step === 1 && (
                <div style={S.card}>
                  {symptoms.length > 0 && (
                    <div style={{
                      background: C.pinkLight, borderRadius: 9, padding: "8px 13px",
                      fontSize: 13, color: C.pink, fontWeight: 600,
                    }}>
                      ✓ {symptoms.length} symptom{symptoms.length > 1 ? "s" : ""} selected
                    </div>
                  )}
                  {apiSymptoms.length === 0 && (
                    <EmptyState
                      icon={<Heart size={30} />}
                      title="No symptoms saved yet."
                      subtitle="Tap below to add your own symptom."
                    />
                  )}
                  <div style={{ display: "flex", flexWrap: "wrap" as const, gap: 7 }}>
                    {apiSymptoms.map(s => {
                      const sel = symptoms.includes(s.drLang);
                      return (
                        <button key={s.id}
                          onClick={() => setSymptoms(p => sel ? p.filter(x => x !== s.drLang) : [...p, s.drLang])}
                          style={{
                            padding: "7px 14px", borderRadius: 20,
                            border: `1.5px solid ${sel ? C.pink : C.chipBorder}`,
                            background: sel ? C.pink : C.white,
                            color: sel ? "#fff" : C.textMain,
                            fontSize: 12, fontWeight: 500, cursor: "pointer",
                            transition: "all .15s",
                          }}>{s.drLang}
                        </button>
                      );
                    })}
                  </div>
                  <button onClick={() => setShowAddSymptom(true)} style={S.addDashedBtn}>
                    <span style={S.plusCircle}>＋</span>
                    <div style={{ textAlign: "left" as const }}>
                      <div style={{ fontWeight: 600, fontSize: 13, color: C.textMain }}>Add custom symptom</div>
                      <div style={{ fontSize: 11, color: C.textSub }}>Not listed above? Add your own</div>
                    </div>
                  </button>
                </div>
              )}

              {/* ════ STEP 2: Diagnosis ════ */}
              {step === 2 && (
                <>
                  <div style={S.card}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{
                        width: 36, height: 36, borderRadius: 10, background: C.purpleLight,
                        display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18,
                      }}>🖊️</div>
                      <span style={{ fontWeight: 700, fontSize: 15, color: C.textMain }}>Enter Diagnosis</span>
                    </div>
                    <textarea
                      style={{ ...S.field, minHeight: 72, resize: "none" as const, lineHeight: 1.5 }}
                      placeholder="Enter Diagnosis"
                      value={diagnosisText}
                      onChange={e => setDiagnosisText(e.target.value)}
                    />
                    <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: C.textSub }}>
                      <span>ⓘ</span>
                      <span>Tap chips below to auto-fill, or type freely above</span>
                    </div>
                  </div>

                  <div style={S.card}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <div style={{ width: 32, height: 32, borderRadius: 8, background: C.pinkLight, display: "flex", alignItems: "center", justifyContent: "center" }}>
                          <span style={{ color: C.pink, fontSize: 16 }}>🔎</span>
                        </div>
                        <span style={{ fontWeight: 700, fontSize: 14, color: C.textMain }}>Saved Diagnoses</span>
                      </div>
                      {selectedDiagnoses.length > 0 && (
                        <div style={{ border: `1.5px solid ${C.pinkBorder}`, borderRadius: 20, padding: "3px 12px", fontSize: 12, fontWeight: 700, color: C.pink }}>
                          {selectedDiagnoses.length} selected
                        </div>
                      )}
                    </div>

                    {apiDiagnoses.length === 0 ? (
                      <EmptyState
                        icon={<Search size={30} />}
                        title="No saved diagnoses"
                        subtitle="Add one below to reuse later"
                      />
                    ) : (
                      <div style={{ display: "flex", flexWrap: "wrap" as const, gap: 8 }}>
                        {apiDiagnoses.map(d => {
                          const isSel = selectedDiagnoses.includes(d.diagnosisDrLang);
                          return (
                            <button key={d.id}
                              onClick={() => {
                                const next = isSel ? selectedDiagnoses.filter(x => x !== d.diagnosisDrLang) : [...selectedDiagnoses, d.diagnosisDrLang];
                                setSelectedDiagnoses(next);
                                setDiagnosisText(next.join(", "));
                              }}
                              style={{
                                padding: "8px 16px", borderRadius: 20,
                                border: `1.5px solid ${isSel ? C.pink : C.chipBorder}`,
                                background: isSel ? C.pink : C.white,
                                color: isSel ? "#fff" : C.textMain,
                                fontSize: 13, fontWeight: 600, cursor: "pointer", transition: "all .15s",
                              }}>{d.diagnosisDrLang}
                            </button>
                          );
                        })}
                      </div>
                    )}

                    <div style={{ borderTop: `1px solid ${C.cardBorder}` }} />

                    <button onClick={() => setShowAddDiagnosis(true)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "8px 4px", background: "none", border: "none", cursor: "pointer", width: "100%" }}>
                      <span style={{ width: 34, height: 34, borderRadius: "50%", background: C.pinkLight, color: C.pink, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20, flexShrink: 0 }}>+</span>
                      <div style={{ textAlign: "left" as const }}>
                        <div style={{ fontWeight: 600, fontSize: 13, color: C.textMain }}>Add new diagnosis</div>
                        <div style={{ fontSize: 11, color: C.textSub }}>Save it for reuse in future prescriptions</div>
                      </div>
                      <span style={{ marginLeft: "auto", color: C.textHint, fontSize: 18 }}>›</span>
                    </button>
                  </div>
                </>
              )}

              {/* ════ STEP 3: Investigation ════ */}
              {step === 3 && (
                <>
                  <div style={S.card}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{ width: 36, height: 36, borderRadius: 10, background: C.purpleLight, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18 }}>🖊️</div>
                      <span style={{ fontWeight: 700, fontSize: 15, color: C.textMain }}>Enter Investigation</span>
                    </div>
                    <textarea
                      style={{ ...S.field, minHeight: 72, resize: "none" as const, lineHeight: 1.5 }}
                      placeholder="Enter Investigation"
                      value={investigationText}
                      onChange={e => setInvestigationText(e.target.value)}
                    />
                    <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: C.textSub }}>
                      <span>ⓘ</span>
                      <span>Tap chips below to auto-fill, or type freely above</span>
                    </div>
                  </div>

                  <div style={S.card}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <div style={{ width: 32, height: 32, borderRadius: 8, background: C.pinkLight, display: "flex", alignItems: "center", justifyContent: "center" }}>
                          <span style={{ color: C.pink, fontSize: 16 }}>📈</span>
                        </div>
                        <span style={{ fontWeight: 700, fontSize: 14, color: C.textMain }}>Saved Investigations</span>
                      </div>
                      {selectedInvestigations.length > 0 && (
                        <div style={{ border: `1.5px solid ${C.pinkBorder}`, borderRadius: 20, padding: "3px 12px", fontSize: 12, fontWeight: 700, color: C.pink }}>
                          {selectedInvestigations.length} selected
                        </div>
                      )}
                    </div>

                    {apiInvestigations.length === 0 ? (
                      <EmptyState
                        icon={<TrendingUp size={30} />}
                        title="No saved investigations"
                        subtitle="Add one below to reuse later"
                      />
                    ) : (
                      <div style={{ display: "flex", flexWrap: "wrap" as const, gap: 8 }}>
                        {apiInvestigations.map(inv => {
                          const isSel = selectedInvestigations.includes(inv.investigationDrLang);
                          return (
                            <button key={inv.id}
                              onClick={() => {
                                const next = isSel ? selectedInvestigations.filter(x => x !== inv.investigationDrLang) : [...selectedInvestigations, inv.investigationDrLang];
                                setSelectedInvestigations(next);
                                setInvestigationText(next.join(", "));
                              }}
                              style={{
                                padding: "8px 16px", borderRadius: 20,
                                border: `1.5px solid ${isSel ? C.pink : C.chipBorder}`,
                                background: isSel ? C.pink : C.white,
                                color: isSel ? "#fff" : C.textMain,
                                fontSize: 13, fontWeight: 600, cursor: "pointer", transition: "all .15s",
                              }}>{inv.investigationDrLang}
                            </button>
                          );
                        })}
                      </div>
                    )}

                    <div style={{ borderTop: `1px solid ${C.cardBorder}` }} />

                    <button onClick={() => setShowAddInvestigation(true)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "8px 4px", background: "none", border: "none", cursor: "pointer", width: "100%" }}>
                      <span style={{ width: 34, height: 34, borderRadius: "50%", background: C.pinkLight, color: C.pink, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20, flexShrink: 0 }}>+</span>
                      <div style={{ textAlign: "left" as const }}>
                        <div style={{ fontWeight: 600, fontSize: 13, color: C.textMain }}>Add new investigation</div>
                        <div style={{ fontSize: 11, color: C.textSub }}>Save it for reuse in future prescriptions</div>
                      </div>
                      <span style={{ marginLeft: "auto", color: C.textHint, fontSize: 18 }}>›</span>
                    </button>
                  </div>
                </>
              )}

              {/* ════ STEP 4: Medicines ════ */}
              {step === 4 && (
                <MedicineStep
                  medicines={medicines}
                  setMedicines={setMedicines}
                  apiMedicines={apiMedicines}
                />
              )}

              {/* ════ STEP 5: Instructions ════ */}
              {step === 5 && (
                <InstructionStep
                  selected={selectedInstruction}
                  apiInstructions={apiInstructions}
                  onSelect={(lang, gi) =>
                    setSelectedInstruction(prev =>
                      prev && prev.lang === lang && prev.groupIndex === gi ? null : { lang, groupIndex: gi }
                    )
                  }
                />
              )}

              {/* ════ STEP 6: Follow-up ════ */}

              {step === 6 && (
                <>
                  {followup && (
                    <div style={{
                      display: "flex", alignItems: "center", gap: 10,
                      background: C.pinkLight, borderRadius: 12,
                      padding: "12px 16px", marginBottom: 12,
                      border: `1.5px solid ${C.pinkBorder}`,
                    }}>
                      <span style={{ fontSize: 18 }}>📅</span>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 11, color: C.pink, fontWeight: 700, textTransform: "uppercase" as const, letterSpacing: "0.05em" }}>Follow-up set</div>
                        <div style={{ fontSize: 14, color: C.textMain, fontWeight: 700 }}>{followup}</div>
                      </div>
                      <button onClick={() => setFollowup("")} style={{ background: "none", border: "none", color: C.textHint, fontSize: 20, cursor: "pointer" }}>×</button>
                    </div>
                  )}
                  <div style={S.card}>
                    <div style={S.cardSectionLabel}>Quick select</div>
                    <div style={{ display: "flex", flexWrap: "wrap" as const, gap: 7 }}>
                      {QUICK_FU.map(q => {
                        const d = new Date();
                        d.setDate(d.getDate() + (FU_DAYS[q] || 0));
                        const formatted = d.toLocaleDateString("en-IN", { dateStyle: "long" });
                        const isSelected = followup === formatted;
                        return (
                          <button key={q} onClick={() => setFollowup(formatted)} style={{
                            padding: "7px 14px", borderRadius: 20,
                            border: `1.5px solid ${isSelected ? C.pink : C.chipBorder}`,
                            background: isSelected ? C.pink : C.white,
                            color: isSelected ? "#fff" : C.textMain,
                            fontSize: 12, fontWeight: 500, cursor: "pointer", transition: "all .15s",
                          }}>{q}</button>
                        );
                      })}
                    </div>
                  </div>
                  <div style={S.card}>
                    <div style={S.cardSectionLabel}>Pick a specific date</div>
                    <div
                      style={{
                        position: "relative",
                        borderRadius: 10,
                        overflow: "hidden",
                      }}
                    >
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: 12,
                          padding: "12px 14px",
                          borderRadius: 10,
                          background: C.fieldBg,
                          cursor: "pointer",
                        }}
                      >
                        <span style={{ fontSize: 20 }}>📅</span>

                        <div>
                          <div
                            style={{
                              fontWeight: 600,
                              fontSize: 13,
                              color: C.textMain,
                            }}
                          >
                            Open calendar
                          </div>

                          <div
                            style={{
                              fontSize: 11,
                              color: C.textSub,
                            }}
                          >
                            Choose any future date
                          </div>
                        </div>

                        <span
                          style={{
                            marginLeft: "auto",
                            color: C.textHint,
                            fontSize: 18,
                          }}
                        >
                          ›
                        </span>
                      </div>

                      <input
                        type="date"
                        min={today}
                        style={{
                          position: "absolute",
                          top: 0,
                          left: 0,
                          width: "100%",
                          height: "100%",
                          opacity: 0,
                          cursor: "pointer",
                          zIndex: 10,
                        }}
                        onChange={(e) => {
                          if (!e.target.value) return;

                          const d = new Date(e.target.value);

                          setFollowup(d.toISOString().split("T")[0]);
                        }}
                      />
                    </div>
                  </div>
                </>
              )}
            </>
          )}
        </div>

        {/* Bottom nav */}
        {(step > 0 || showMedConfirm) && (
          <div style={{
            position: "absolute" as const, bottom: 0, left: 0, right: 0,
            padding: "12px 24px 16px",
            background: C.white,
            borderTop: `1px solid ${C.cardBorder}`,
            display: "flex", gap: 8,
            boxShadow: "0 -2px 12px rgba(0,0,0,0.05)",
          }}>
            <button
              onClick={() => {
                if (showMedConfirm) {
                  setShowMedConfirm(false);
                } else {
                  handleBack();
                }
              }}
              style={{
                padding: "13px 18px",
                background: C.white, color: C.textSub,
                border: `1.5px solid ${C.chipBorder}`, borderRadius: 12,
                fontSize: 14, fontWeight: 600, cursor: "pointer",
              }}>← Back</button>
            {!showMedConfirm && showClear && (
              <button onClick={handleClear} style={{
                padding: "13px 16px",
                background: C.white, color: C.textSub,
                border: `1.5px solid ${C.chipBorder}`, borderRadius: 12,
                fontSize: 13, fontWeight: 600, cursor: "pointer",
              }}>Clear</button>
            )}
            <button
              onClick={() => {
                if (showMedConfirm) {
                  setShowMedConfirm(false);
                  setStep(s => s + 1);
                } else {
                  handleNext();
                }
              }}
              style={{ ...S.pinkBtn, flex: 1, padding: "13px 22px" }}
            >
              {showMedConfirm ? "Next" : (isLastStep ? "Finish & Save" : "Next")}
            </button>
          </div>
        )}
      </div>

      {/* ════════════════════════════════════════
          RIGHT PANEL — preview, sized using the
          real paper aspect ratio derived from
          user_preferences
      ════════════════════════════════════════ */}
      <div style={{
        width: "50%",
        height: "100%",
        display: "flex",
        flexDirection: "column",
        borderLeft: `1px solid ${C.cardBorder}`,
        background: "#f3f1fa",
      }}>
        <div style={{
          padding: "0 18px", height: 52,
          display: "flex", alignItems: "center",
          borderBottom: `1px solid ${C.cardBorder}`,
          background: "#fff", flexShrink: 0,
        }}>
          <span style={{ color: C.pink }}>📄</span>
          <span style={{ marginLeft: 8, color: "#000000" }}>Prescription Preview</span>
          <NextLink
            href="/dashboard"
            style={{
              marginLeft: "auto",
              background: "#d4537e",
              color: "#fff",
              padding: "6px 10px",
              borderRadius: "10px",
              display: "inline-flex",
              alignItems: "center",
              gap: "8px",
              textDecoration: "none",
              whiteSpace: "nowrap",
            }}
          >
            <Plus size={18} />
            {/* <span>New Prescription</span> */}
          </NextLink>

        </div>

        <div
          style={{
            ...S.previewContainer,
            position: "relative",
          }}
        >
          <div
            style={{
              position: "relative",
              width: "100%",
              height: "100%",
              display: "grid",
              placeItems: "center",
              overflow: "hidden",
            }}
          >
            {/* Print Button + Font Controls */}
            <div style={{
              position: "absolute",
              top: 0,
              right: 16,
              zIndex: 1000,
              display: "flex",
              alignItems: "center",
              gap: 8,
            }}>

              {/* Aa A- and Aa A+ pill container - exactly like iOS */}
              <div style={{
                display: "flex",
                alignItems: "center",
                background: "#eeecf4",
                borderRadius: 20,
                padding: "4px",
                gap: 2,
                boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
              }}>

                {/* Aa A- */}
                <button
                  onClick={() => adjustFont(false)}
                  disabled={fontSize <= MIN_FONT_SIZE || isFontBusy}
                  title="Decrease font size"
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 3,
                    padding: "8px 14px",
                    borderRadius: 16,
                    border: "none",
                    background: fontSize <= MIN_FONT_SIZE ? "transparent" : "#fff",
                    cursor: fontSize <= MIN_FONT_SIZE || isFontBusy ? "not-allowed" : "pointer",
                    opacity: fontSize <= MIN_FONT_SIZE ? 0.4 : 1,
                    boxShadow: fontSize <= MIN_FONT_SIZE ? "none" : "0 1px 4px rgba(0,0,0,0.1)",
                    transition: "all .15s",
                  }}
                >
                  <span style={{ fontSize: 9, fontWeight: 800, color: "#555", lineHeight: 1 }}>Aa</span>
                  <span style={{ fontSize: 14, fontWeight: 600, color: "#555", lineHeight: 1 }}>A−</span>
                </button>

                {/* Aa A+ */}
                <button
                  onClick={() => adjustFont(true)}
                  disabled={fontSize >= MAX_FONT_SIZE || isFontBusy}
                  title="Increase font size"
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 3,
                    padding: "8px 14px",
                    borderRadius: 16,
                    border: "none",
                    background: fontSize >= MAX_FONT_SIZE ? "transparent" : "#fff",
                    cursor: fontSize >= MAX_FONT_SIZE || isFontBusy ? "not-allowed" : "pointer",
                    opacity: fontSize >= MAX_FONT_SIZE ? 0.4 : 1,
                    boxShadow: fontSize >= MAX_FONT_SIZE ? "none" : "0 1px 4px rgba(0,0,0,0.1)",
                    transition: "all .15s",
                  }}
                >
                  <span style={{ fontSize: 9, fontWeight: 800, color: C.pink, lineHeight: 1 }}>Aa</span>
                  <span style={{ fontSize: 14, fontWeight: 600, color: C.pink, lineHeight: 1 }}>A+</span>
                </button>

              </div>

              {/* Print Button - same as before */}
              <button
                onClick={handlePrint}
                title="Print Prescription"
                style={{
                  width: 40,
                  height: 40,
                  border: "none",
                  borderRadius: 50,
                  background: C.pinkLight,
                  color: C.pink,
                  cursor: "pointer",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  boxShadow: "0 4px 12px rgba(0,0,0,0.2)",
                  fontSize: 20,
                }}
              >
                <Printer size={20} />
              </button>

            </div>


            {/* Prescription Preview */}
            <div
              style={{
                height: "100%",
                aspectRatio: paperAspectRatio,
                // background: "#000",
                maxWidth: "100%",
                maxHeight: "100%",
                overflow: "hidden",
                paddingTop: 50,
              }}
            >
              <iframe
                ref={iframeRef}
                src={iframeSrc}
                onLoad={handleIframeLoaded}
                title="Prescription Preview"
                style={{
                  width: "100%",
                  height: "100%",
                  border: "none",
                  background: "#fff",
                }}
              />
            </div>
          </div>
        </div>
      </div>

      {/* ════════════════════════════════════════
          MODALS
      ════════════════════════════════════════ */}
      {showAddSymptom && (
        <CenterModal onClose={() => setShowAddSymptom(false)} title="Add Symptom">
          <div style={S.infoBox}>
            ⓘ Doctor language shows in your app. Patient language prints on the prescription.
          </div>
          <FieldLabel>Doctor language</FieldLabel>
          <input style={{ ...S.field, marginBottom: 4 }} placeholder="e.g. Chest Pain"
            value={drSymptom} onChange={e => setDrSymptom(e.target.value)} />
          <div style={{ fontSize: 11, color: C.textHint, marginBottom: 14 }}>Used in your app UI</div>
          <FieldLabel>Patient language</FieldLabel>
          <div style={{ display: "flex", alignItems: "center", gap: 10, background: C.fieldBg, borderRadius: 9, padding: "11px 13px", marginBottom: 4, border: `1px solid ${C.chipBorder}` }}>
            <span style={{ fontSize: 15, color: C.pink }}>🖨️</span>
            <input style={{ border: "none", background: "transparent", outline: "none", flex: 1, fontSize: 13, color: C.textMain }}
              placeholder="e.g. છાती में दर्द" value={ptSymptom} onChange={e => setPtSymptom(e.target.value)} />
          </div>
          <div style={{ fontSize: 11, color: C.textHint, marginBottom: 22 }}>Printed on prescription</div>
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={() => setShowAddSymptom(false)} style={S.ghostBtn}>Cancel</button>
            <button onClick={handleAddSymptom} style={{ ...S.pinkBtn, flex: 1 }}>Save Symptom</button>
          </div>
        </CenterModal>
      )}

      {showAddDiagnosis && (
        <CenterModal onClose={() => setShowAddDiagnosis(false)} title="Save Diagnosis">

          <div style={S.infoBox}>
            ⓘ Doctor language shows in your app. Patient language prints on the prescription.
          </div>

          <FieldLabel>Doctor language</FieldLabel>

          <input
            style={{ ...S.field, marginBottom: 4 }}
            placeholder="e.g. Pneumonia"
            value={drDiagnosis}
            onChange={(e) => setDrDiagnosis(e.target.value)}
          />

          <div
            style={{
              fontSize: 11,
              color: C.textHint,
              marginBottom: 14,
            }}
          >
            Used in your app UI
          </div>

          <FieldLabel>Patient language</FieldLabel>

          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 10,
              background: C.fieldBg,
              borderRadius: 9,
              padding: "11px 13px",
              marginBottom: 4,
              border: `1px solid ${C.chipBorder}`,
            }}
          >
            <span
              style={{
                fontSize: 15,
                color: C.pink,
              }}
            >
              🖨️
            </span>

            <input
              style={{
                border: "none",
                background: "transparent",
                outline: "none",
                flex: 1,
                fontSize: 13,
                color: C.textMain,
              }}
              placeholder="e.g. Pneumonia"
              value={ptDiagnosis}
              onChange={(e) => setPtDiagnosis(e.target.value)}
            />
          </div>

          <div
            style={{
              fontSize: 11,
              color: C.textHint,
              marginBottom: 22,
            }}
          >
            Printed on prescription
          </div>

          <div style={{ display: "flex", gap: 10 }}>
            <button
              onClick={() => setShowAddDiagnosis(false)}
              style={S.ghostBtn}
            >
              Cancel
            </button>

            <button
              onClick={handleAddDiagnosis}
              style={{ ...S.pinkBtn, flex: 1 }}
            >
              Save Diagnosis
            </button>
          </div>

        </CenterModal>
      )}

      {showAddInvestigation && (
        <CenterModal
          onClose={() => setShowAddInvestigation(false)}
          title="Save Investigation"
        >

          <div style={S.infoBox}>
            ⓘ Doctor language shows in your app. Patient language prints on the prescription.
          </div>

          <FieldLabel>Doctor language</FieldLabel>

          <input
            style={{ ...S.field, marginBottom: 4 }}
            placeholder="e.g. Urinalysis"
            value={drInvestigation}
            onChange={(e) => setDrInvestigation(e.target.value)}
          />

          <div
            style={{
              fontSize: 11,
              color: C.textHint,
              marginBottom: 14,
            }}
          >
            Used in your app UI
          </div>

          <FieldLabel>Patient language</FieldLabel>

          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 10,
              background: C.fieldBg,
              borderRadius: 9,
              padding: "11px 13px",
              marginBottom: 4,
              border: `1px solid ${C.chipBorder}`,
            }}
          >
            <span
              style={{
                fontSize: 15,
                color: C.pink,
              }}
            >
              🖨️
            </span>

            <input
              style={{
                border: "none",
                background: "transparent",
                outline: "none",
                flex: 1,
                fontSize: 13,
                color: C.textMain,
              }}
              placeholder="e.g. Urinalysis"
              value={ptInvestigation}
              onChange={(e) => setPtInvestigation(e.target.value)}
            />
          </div>

          <div
            style={{
              fontSize: 11,
              color: C.textHint,
              marginBottom: 22,
            }}
          >
            Printed on prescription
          </div>

          <div style={{ display: "flex", gap: 10 }}>
            <button
              onClick={() => setShowAddInvestigation(false)}
              style={S.ghostBtn}
            >
              Cancel
            </button>

            <button
              onClick={handleAddInvestigation}
              style={{ ...S.pinkBtn, flex: 1 }}
            >
              Save Investigation
            </button>
          </div>

        </CenterModal>
      )}
    </div>
  );
}

/* ═══════════════════════════════════════════════════════
   CENTER MODAL
═══════════════════════════════════════════════════════ */
function CenterModal({ children, onClose, title }: { children: React.ReactNode; onClose: () => void; title: string }) {
  return (
    <div style={{
      position: "fixed" as const, inset: 0, zIndex: 1000,
      display: "flex", alignItems: "center", justifyContent: "center",
    }}>
      <div onClick={onClose} style={{
        position: "absolute" as const, inset: 0,
        background: "rgba(10,4,30,0.5)",
      }} />
      <div style={{
        position: "relative" as const,
        background: C.white,
        borderRadius: 18,
        padding: "24px 22px 22px",
        maxHeight: "80vh",
        overflowY: "auto" as const,
        boxShadow: "0 20px 60px rgba(58,18,128,0.18)",
      }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: C.textMain }}>{title}</h3>
          <button onClick={onClose} style={{
            width: 30, height: 30, borderRadius: "50%",
            border: `1px solid ${C.chipBorder}`, background: C.fieldBg,
            color: C.textSub, cursor: "pointer", fontSize: 15,
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>×</button>
        </div>
        {children}
      </div>
    </div>
  );
}
/* ═══════════════════════════════════════════════════════
   BOTTOM SHEET MODAL — replaces CenterModal
   Web/desktop only: always centered, max-width 680px
   Same usage: <Bottomsheetmodal onClose={...} title="...">
═══════════════════════════════════════════════════════ */
function Bottomsheetmodal({
  children,
  onClose,
  title,
}: {
  children: React.ReactNode;
  onClose: () => void;
  title: string;
}) {
  return (
    <div
      style={{
        position: "fixed" as const,
        inset: 0,
        zIndex: 1000,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{
          position: "absolute" as const,
          inset: 0,
          background: "rgba(10,4,30,0.55)",
          backdropFilter: "blur(2px)",
        }}
      />

      {/* Dialog */}
      <div
        style={{
          position: "relative" as const,
          width: "min(680px, 92vw)",
          background: C.white,
          borderRadius: 22,
          padding: "0 0 28px",
          maxHeight: "88vh",
          display: "flex",
          flexDirection: "column" as const,
          boxShadow: "0 -4px 40px rgba(58,18,128,0.18)",
          overflow: "hidden",
        }}
      >
        {/* ── Header ── */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "22px 26px 14px",
            borderBottom: `1px solid ${C.cardBorder}`,
            flexShrink: 0,
          }}
        >
          <h3
            style={{
              margin: 0,
              fontSize: 17,
              fontWeight: 800,
              marginRight: 12,
              color: C.textMain,
              letterSpacing: "-0.01em",
            }}
          >
            {title}
          </h3>
          <button
            onClick={onClose}
            style={{
              width: 32,
              height: 32,
              borderRadius: "50%",
              border: `1px solid ${C.chipBorder}`,
              background: C.fieldBg,
              color: C.textSub,
              cursor: "pointer",
              fontSize: 16,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              flexShrink: 0,
            }}
          >
            ×
          </button>
        </div>

        {/* ── Scrollable body ── */}
        <div
          style={{
            flex: 1,
            overflowY: "auto" as const,
            padding: "20px 26px",
          }}
        >
          {children}
        </div>
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════════
   CONFIRMATION OF MEDICINES — inline list
   Rendered INLINE inside the left panel's own scrollable
   content area (see the main component above), instead of
   as a full-screen bottom-sheet overlay. This keeps it on
   the left side, next to the live preview on the right,
   and it scrolls using the same scrollbar as every other
   step. One card per selected medicine, each with editable
   Dose / Frequency / Quantity (and Meal-time / Injection-
   method where relevant) pill pickers, a trash button to
   remove the medicine, and a "+" per section that opens a
   small popup to add a brand new option (persisted for
   this session, merged on top of the DOSE_OPTIONS_BY_TYPE /
   QTY_OPTIONS_BY_TYPE tables and the saved dose_frequencies
   from the backend).
═══════════════════════════════════════════════════════ */
function MedicineConfirmationList({
  medicines,
  setMedicines,
  apiFrequencies,
  customDoses,
  setCustomDoses,
  customQtys,
  setCustomQtys,
  customFreqs,
  setCustomFreqs,
}: {
  medicines: Medicine[];
  setMedicines: React.Dispatch<React.SetStateAction<Medicine[]>>;
  apiFrequencies: ApiDoseFrequency[];
  customDoses: Record<string, string[]>;
  setCustomDoses: React.Dispatch<React.SetStateAction<Record<string, string[]>>>;
  customQtys: Record<string, string[]>;
  setCustomQtys: React.Dispatch<React.SetStateAction<Record<string, string[]>>>;
  customFreqs: string[];
  setCustomFreqs: React.Dispatch<React.SetStateAction<string[]>>;
}) {
  const [addDoseFor, setAddDoseFor] = useState<number | null>(null);
  const [addFreqFor, setAddFreqFor] = useState<number | null>(null);
  const [addQtyFor, setAddQtyFor] = useState<number | null>(null);

  function updateMedicine(index: number, patch: Partial<Medicine>) {
    setMedicines(prev => prev.map((m, i) => {
      if (i !== index) return m;
      const updated: Medicine = { ...m, ...patch };
      return {
        ...updated,
        // Keep the legacy combined fields in sync so anything else in the
        // app that still reads `dosage` / `duration` keeps working.
        dosage: [updated.dose, updated.frequency].filter(Boolean).join(" · "),
        duration: updated.qty ?? updated.duration,
      };
    }));
  }

  function removeMedicine(index: number) {
    setMedicines(prev => prev.filter((_, i) => i !== index));
  }

  const freqOptions = Array.from(
    new Set([...ALL_FREQ, ...apiFrequencies.map(f => f.drLang), ...customFreqs].filter(Boolean)),
  );

  return (
    <div style={{ display: "flex", flexDirection: "column" as const, gap: 18 }}>
      {medicines.map((m, index) => {
        const cfg = getMedicineFieldConfig(m.type);
        const MedIcon = MED_TYPE_PILLS.find(p => p.label === m.type)?.icon ?? Pill;
        const doseOptions = Array.from(new Set([...cfg.doseOptions, ...(customDoses[m.type] || [])]));
        const qtyOptions = Array.from(new Set([...cfg.qtyOptions, ...(customQtys[m.type] || [])]));

        return (
          <div
            key={index}
            style={{
              background: C.white, borderRadius: 18, overflow: "hidden",
              border: `1px solid ${C.cardBorder}`,
            }}
          >
            {/* Card header */}
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 16px", background: C.pinkLight }}>
              <div style={{
                width: 40, height: 40, borderRadius: "50%", background: C.white,
                display: "flex", alignItems: "center", justifyContent: "center",
                color: C.pink, flexShrink: 0,
              }}>
                <MedIcon size={20} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 800, fontSize: 16, color: C.purple }}>{m.name}</div>
                {m.note && <div style={{ fontSize: 12, color: C.pink, marginTop: 1 }}>{m.note}</div>}
              </div>
              <button
                onClick={() => removeMedicine(index)}
                style={{
                  width: 34, height: 34, borderRadius: "50%",
                  background: C.purple, border: "none", color: "#fff",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  cursor: "pointer", flexShrink: 0,
                }}
              >
                <Trash2 size={15} />
              </button>
            </div>

            <div style={{ padding: "14px 16px 16px", display: "flex", flexDirection: "column" as const, gap: 16 }}>
              {cfg.showDose && (
                <PillFieldSection
                  label={cfg.doseLabel}
                  options={doseOptions}
                  value={m.dose}
                  onSelect={(v) => updateMedicine(index, { dose: v })}
                  onAdd={() => setAddDoseFor(index)}
                />
              )}

              {cfg.showFreq && (
                <PillFieldSection
                  label="Frequency"
                  options={freqOptions}
                  value={m.frequency}
                  onSelect={(v) => updateMedicine(index, { frequency: v })}
                  onAdd={() => setAddFreqFor(index)}
                />
              )}

              <PillFieldSection
                label="Quantity (To buy from Pharmacy)"
                options={qtyOptions}
                value={m.qty ?? m.duration}
                onSelect={(v) => updateMedicine(index, { qty: v })}
                onAdd={() => setAddQtyFor(index)}
              />

              {cfg.showMeal && (
                <div>
                  <div style={{ fontSize: 12, fontWeight: 700, color: C.purple, marginBottom: 8 }}>Before / After Meal</div>
                  <div style={{ display: "flex", borderRadius: 12, overflow: "hidden", border: `1.5px solid ${C.chipBorder}` }}>
                    {MEAL_OPTS.map(opt => (
                      <button
                        key={opt}
                        onClick={() => updateMedicine(index, { note: opt })}
                        style={{
                          flex: 1, padding: "10px", border: "none",
                          background: m.note === opt ? C.pink : C.white,
                          color: m.note === opt ? "#fff" : C.textSub,
                          fontWeight: 700, fontSize: 12, cursor: "pointer",
                        }}
                      >
                        {opt}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {cfg.showMethod && (
                <div>
                  <div style={{ fontSize: 12, fontWeight: 700, color: C.purple, marginBottom: 8 }}>Method</div>
                  <div style={{ display: "flex", borderRadius: 12, overflow: "hidden", border: `1.5px solid ${C.chipBorder}` }}>
                    {METHOD_OPTS.map((opt, i) => (
                      <button
                        key={opt}
                        onClick={() => updateMedicine(index, { note: opt })}
                        style={{
                          flex: 1, padding: "10px", border: "none",
                          background: m.note === opt ? (i === 0 ? C.pink : C.purpleMid) : C.white,
                          color: m.note === opt ? "#fff" : C.textSub,
                          fontWeight: 700, fontSize: 12, cursor: "pointer",
                        }}
                      >
                        {opt}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        );
      })}

      {medicines.length === 0 && (
        <div style={{ textAlign: "center" as const, color: C.textHint, padding: "40px 0", fontSize: 13 }}>
          No medicines to confirm.
        </div>
      )}

      {/* ── "+" popups ── */}
      {addDoseFor !== null && (
        <AddDoseModal
          title={medicines[addDoseFor].type === "Surg. Items" ? "Add Size" : "Add Dose"}
          fieldLabel={medicines[addDoseFor].type === "Surg. Items" ? "Size" : "Dose"}
          onClose={() => setAddDoseFor(null)}
          onSave={(val) => {
            const type = medicines[addDoseFor].type;
            setCustomDoses(prev => ({ ...prev, [type]: [...(prev[type] || []), val] }));
            updateMedicine(addDoseFor, { dose: val });
            setAddDoseFor(null);
          }}
        />
      )}

      {addFreqFor !== null && (
        <AddFrequencyModal
          onClose={() => setAddFreqFor(null)}
          onSave={(drLang) => {
            setCustomFreqs(prev => Array.from(new Set([...prev, drLang])));
            updateMedicine(addFreqFor, { frequency: drLang });
            setAddFreqFor(null);
          }}
        />
      )}

      {addQtyFor !== null && (
        <AddQtyModal
          onClose={() => setAddQtyFor(null)}
          onSave={(val) => {
            const type = medicines[addQtyFor].type;
            setCustomQtys(prev => ({ ...prev, [type]: [...(prev[type] || []), val] }));
            updateMedicine(addQtyFor, { qty: val });
            setAddQtyFor(null);
          }}
        />
      )}
    </div>
  );
}

/** One labelled row of selectable pills + a "+" button to add a new option. */
function PillFieldSection({
  label, options, value, onSelect, onAdd,
}: {
  label: string;
  options: string[];
  value?: string;
  onSelect: (v: string) => void;
  onAdd: () => void;
}) {
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <span style={{ fontSize: 12, fontWeight: 700, color: C.purple }}>{label}</span>
        <button
          onClick={onAdd}
          style={{
            width: 24, height: 24, borderRadius: "50%", border: "none",
            background: C.pink, color: "#fff", fontSize: 15, fontWeight: 700,
            display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
          }}
        >
          +
        </button>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap" as const, gap: 8 }}>
        {options.map(opt => (
          <button
            key={opt}
            onClick={() => onSelect(opt)}
            style={{
              padding: "8px 16px", borderRadius: 20, border: "none",
              background: value === opt ? C.pink : C.purpleLight,
              color: value === opt ? "#fff" : C.textMain,
              fontWeight: 600, fontSize: 13, cursor: "pointer",
            }}
          >
            {opt}
          </button>
        ))}
      </div>
    </div>
  );
}

/* ── Small "Add X" popups — mirror the iOS bottom-sheet screens ── */
function AddDoseModal({
  title = "Add Dose", fieldLabel = "Dose", onClose, onSave,
}: { title?: string; fieldLabel?: string; onClose: () => void; onSave: (v: string) => void }) {
  const [val, setVal] = useState("");
  return (
    <Bottomsheetmodal onClose={onClose} title={title}>
      <FieldLabel>{fieldLabel}</FieldLabel>
      <input
        style={{ ...S.field, marginBottom: 20 }}
        placeholder="i.e. 1-0-1"
        value={val}
        onChange={e => setVal(e.target.value)}
      />
      <button
        onClick={() => val.trim() && onSave(val.trim())}
        style={{ ...S.pinkBtn, width: "100%" }}
      >
        Save
      </button>
    </Bottomsheetmodal>
  );
}

function AddFrequencyModal({
  onClose, onSave,
}: { onClose: () => void; onSave: (drLang: string, ptLang: string) => void }) {
  const [dr, setDr] = useState("");
  const [pt, setPt] = useState("");
  return (
    <Bottomsheetmodal onClose={onClose} title="Add Dose Frequency">
      <FieldLabel>Frequency in Dr. Language</FieldLabel>
      <input
        style={{ ...S.field, marginBottom: 16 }}
        placeholder="i.e. 1-0-1"
        value={dr}
        onChange={e => setDr(e.target.value)}
      />
      <FieldLabel>Frequency in Patient Language</FieldLabel>
      <input
        style={{ ...S.field, marginBottom: 20 }}
        placeholder="i.e. Morning - Noon - Evening"
        value={pt}
        onChange={e => setPt(e.target.value)}
      />
      <button
        onClick={() => dr.trim() && onSave(dr.trim(), pt.trim())}
        style={{ ...S.pinkBtn, width: "100%" }}
      >
        Save
      </button>
    </Bottomsheetmodal>
  );
}

function AddQtyModal({
  onClose, onSave,
}: { onClose: () => void; onSave: (v: string) => void }) {
  const [val, setVal] = useState("");
  return (
    <Bottomsheetmodal onClose={onClose} title="Add Qty">
      <FieldLabel>Qty</FieldLabel>
      <input
        style={{ ...S.field, marginBottom: 20 }}
        placeholder="i.e. 12"
        value={val}
        onChange={e => setVal(e.target.value)}
      />
      <button
        onClick={() => val.trim() && onSave(val.trim())}
        style={{ ...S.pinkBtn, width: "100%" }}
      >
        Save
      </button>
    </Bottomsheetmodal>
  );
}

/* ═══════════════════════════════════════════════════════
   MEDICINE STEP
═══════════════════════════════════════════════════════ */
function MedicineStep({
  medicines, setMedicines, apiMedicines,
}: {
  medicines: Medicine[];
  setMedicines: React.Dispatch<React.SetStateAction<Medicine[]>>;
  apiMedicines: ApiMedicine[];
}) {
  const { addMedicine } = useMedicineStore();
  const [activeTab, setActiveTab] = useState("Tablet");
  const [search, setSearch] = useState("");
  const [showModal, setShowModal] = useState(false);
  const [nm, setNm] = useState({
    name: "", type: "Tablet", forWhom: "All",
    dose: "1", freq: "0-0-1", qty: "1", meal: "After Meal",
  });

  const catalogForTab = apiMedicines.filter(m => m.type === activeTab);
  const filteredCatalog = search
    ? catalogForTab.filter(m => m.name.toLowerCase().includes(search.toLowerCase()))
    : catalogForTab;

  const isAdded = (name: string, type: string) =>
    medicines.some(m => m.name === name && m.type === type);

  function toggleFromCatalog(m: ApiMedicine) {
    if (isAdded(m.name, m.type)) {
      setMedicines(p => p.filter(x => !(x.name === m.name && x.type === m.type)));
    } else {
      setMedicines(p => [...p, {
        name: m.name, type: m.type,
        dosage: [m.dose, m.dose_frequency].filter(Boolean).join(" · "),
        duration: m.qty, note: m.meal_time, id: m.id,
        // Granular fields, so the Confirmation-of-Medicines screen can
        // edit dose / frequency / qty independently.
        dose: m.dose, frequency: m.dose_frequency, qty: m.qty,
      }]);
    }
  }

  async function doAdd() {
    if (!nm.name.trim()) return;
    const success = await addMedicine({
      name: nm.name, type: nm.type, dose: nm.dose,
      dose_frequency: nm.freq, qty: nm.qty,
      meal_time: nm.meal, patient_type: nm.forWhom,
    });
    if (!success) return;
    setShowModal(false);
    setNm({ name: "", type: "Tablet", forWhom: "All", dose: "1", freq: "0-0-1", qty: "1", meal: "After Meal" });
  }

  const totalAdded = medicines.length;

  // ── Per-type dose/frequency/qty/meal/method field config — shared with
  // the Confirmation-of-Medicines screen via getMedicineFieldConfig(). ──
  const t = nm.type;
  const cfg = getMedicineFieldConfig(t);
  const { showDose, doseLabel, doseOptions, showFreq, showMeal, showMethod, qtyOptions } = cfg;
  const showSize = t === "Surg. Items";

  const pill = (sel: boolean): React.CSSProperties => ({
    padding: "9px 16px",
    borderRadius: 30,
    border: sel ? "none" : "1.5px solid #e4e0f0",
    background: sel ? C.pink : C.white,
    color: sel ? "#fff" : "#5a5a7a",
    fontWeight: 600, fontSize: 13, cursor: "pointer",
    transition: "all .15s",
    boxShadow: sel ? "0 2px 8px rgba(240,98,146,0.3)" : "none",
    whiteSpace: "nowrap" as const,
  });

  const typeBtn = (sel: boolean): React.CSSProperties => ({
    padding: "12px 4px 10px", borderRadius: 14, border: "none",
    background: sel ? C.pink : "#e8e4f2",
    color: sel ? "#fff" : "#5a5a7a",
    cursor: "pointer", fontWeight: 600, fontSize: 11,
    display: "flex", flexDirection: "column" as const,
    alignItems: "center", gap: 6, transition: "all .15s",
    boxShadow: sel ? "0 2px 8px rgba(240,98,146,0.3)" : "none",
  });

  const sectionLabel = (text: string) => (
    <div style={{ fontSize: 13, fontWeight: 700, color: C.purple, marginBottom: 10, marginTop: 4 }}>
      {text}
    </div>
  );

  return (
    <>
      {/* Type tabs */}
      <div style={{
        display: "flex", overflowX: "auto" as const, background: C.white,
        borderRadius: 12, border: `1px solid ${C.cardBorder}`,
        marginBottom: 10, padding: "2px 4px",
        scrollbarWidth: "none" as const,
      }}>
        {MED_TABS.map(t => (
          <button key={t} onClick={() => { setActiveTab(t); setSearch(""); }} style={{
            padding: "9px 14px",
            border: "none", background: "transparent",
            fontSize: 13, fontWeight: 600,
            cursor: "pointer", whiteSpace: "nowrap" as const,
            color: activeTab === t ? C.pink : C.textSub,
            borderBottom: activeTab === t ? `2px solid ${C.pink}` : "2px solid transparent",
            transition: "all .15s", flexShrink: 0,
          }}>{t}</button>
        ))}
      </div>

      {totalAdded > 0 && (
        <div
          style={{
            background: C.pinkLight,
            borderRadius: 9,
            padding: "8px 13px",
            fontSize: 13,
            color: C.pink,
            fontWeight: 600,
            marginBottom: 10,
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}
        >
          <Pill size={16} />
          <span>
            {totalAdded} medicine{totalAdded > 1 ? "s" : ""} added to prescription
          </span>
        </div>
      )}

      <div style={{ background: C.white, borderRadius: 14, border: `1px solid ${C.cardBorder}`, padding: "14px", display: "flex", flexDirection: "column" as const, gap: 10 }}>
        {/* Search */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, background: C.fieldBg, borderRadius: 9, padding: "10px 13px" }}>
          <span style={{ color: C.textHint, fontSize: 15 }}>🔎</span>
          <input
            style={{ border: "none", background: "transparent", outline: "none", flex: 1, fontSize: 13, color: C.textMain }}
            placeholder={`Search ${activeTab.toLowerCase()}s…`}
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
          {search && (
            <button onClick={() => setSearch("")} style={{ border: "none", background: "none", color: C.textHint, cursor: "pointer", fontSize: 16 }}>×</button>
          )}
        </div>
        {filteredCatalog.length === 0 && !search && (
          <EmptyState
            icon={<Pill size={30} />}
            title={`No ${activeTab.toLowerCase()}s saved yet.`}
            subtitle="Tap 'Add custom medicine' below to add your own."
          />
        )}
        {filteredCatalog.length === 0 && search && (
          <div style={{ fontSize: 12, color: C.textHint, textAlign: "center" as const, padding: "8px 0" }}>
            No results for "{search}"
          </div>
        )}

        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(2, 1fr)",
            gap: 12,
          }}
        >
          {filteredCatalog.map(m => {
            const added = isAdded(m.name, m.type);
            const MedicineIcon = MED_TYPE_PILLS.find(p => p.label === m.type)?.icon;

            return (
              <div
                key={m.id}
                onClick={() => toggleFromCatalog(m)}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  padding: "11px 14px",
                  borderRadius: 10,
                  cursor: "pointer",
                  border: `1.5px solid ${added ? C.pink : C.cardBorder}`,
                  background: added ? C.pinkLight : C.white,
                  transition: "all .15s",
                }}
              >
                <div style={{ width: 20, height: 20, borderRadius: "50%", flexShrink: 0, border: added ? "none" : `2px solid ${C.chipBorder}`, background: added ? C.pink : "transparent", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  {added && <span style={{ color: "#fff", fontSize: 11, fontWeight: 700 }}>✓</span>}
                </div>
                <div
                  style={{
                    width: 34,
                    height: 34,
                    borderRadius: "50%",
                    flexShrink: 0,
                    background: added ? C.pink : C.purpleLight,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  {MedicineIcon && <MedicineIcon size={18} color={added ? "#fff" : "#666"} />}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 13, color: added ? C.pink : C.textMain, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" as const }}>{m.name}</div>
                  <div style={{ fontSize: 11, color: C.textSub, marginTop: 2 }}>
                    {[m.dose, m.dose_frequency, m.meal_time].filter(Boolean).join(" · ")}
                  </div>
                </div>
                {m.used > 0 && (
                  <div style={{ fontSize: 10, fontWeight: 700, color: C.textHint, background: C.fieldBg, borderRadius: 20, padding: "2px 8px", flexShrink: 0 }}>×{m.used}</div>
                )}
              </div>
            );
          })}
        </div>

        {medicines.filter(m => m.type === activeTab && !m.id).map((m, i) => (
          <div key={`custom-${i}`} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 9, border: `1px solid ${C.pinkBorder}`, background: C.pinkLight }}>
            <div style={{ width: 32, height: 32, borderRadius: "50%", background: C.pink, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14 }}>💊</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 13, color: C.textMain, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" as const }}>{m.name}</div>
              <div style={{ fontSize: 11, color: C.pink, marginTop: 1 }}>{m.dosage} · {m.note}</div>
            </div>
            <div style={{ fontSize: 10, color: C.pink, fontWeight: 600, background: C.white, borderRadius: 10, padding: "2px 8px", flexShrink: 0 }}>custom</div>
            <button
              style={{ background: "none", border: "none", color: C.textHint, fontSize: 17, cursor: "pointer", flexShrink: 0 }}
              onClick={e => { e.stopPropagation(); setMedicines(p => p.filter((_, j) => j !== medicines.indexOf(m))); }}
            >✕</button>
          </div>
        ))}

        <button onClick={() => setShowModal(true)} style={S.addDashedBtn}>
          <span style={S.plusCircle}>＋</span>
          <div style={{ textAlign: "left" as const }}>
            <div style={{ fontWeight: 600, fontSize: 13, color: C.textMain }}>Add custom medicine</div>
            <div style={{ fontSize: 11, color: C.textSub }}>Not in list? Add manually</div>
          </div>
        </button>
      </div>

      {/* ── Add Medicine Modal ── */}
      {showModal && (
        <Bottomsheetmodal onClose={() => setShowModal(false)} title="Add Medicine">
          <div style={{ paddingRight: 2 }}>

            {sectionLabel("Select Medicine Type")}
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginBottom: 20 }}>
              {MED_TYPE_PILLS.map(({ label, icon: Icon }) => (
                <button
                  key={label}
                  onClick={() =>
                    setNm(p => ({
                      ...p,
                      type: label,
                      dose: "1",
                      freq: "0-0-1",
                      qty: "1",
                      meal: "After Meal",
                    }))
                  }
                  style={typeBtn(nm.type === label)}
                >
                  <Icon size={22} />
                  <span>{label}</span>
                </button>
              ))}
            </div>

            {sectionLabel("For whom (multiple selection)")}
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginBottom: 20 }}>
              {FOR_WHOM.map(({ label, icon: Icon }) => (
                <button
                  key={label}
                  onClick={() => setNm(p => ({ ...p, forWhom: label }))}
                  style={typeBtn(nm.forWhom === label)}
                >
                  <Icon size={22} />
                  <span>{label}</span>
                </button>
              ))}
            </div>

            <input
              style={{ width: "100%", padding: "15px 18px", borderRadius: 14, border: "none", background: "#f0eef8", fontSize: 14, color: C.textMain, outline: "none", marginBottom: 20, boxSizing: "border-box" as const }}
              placeholder="Name"
              value={nm.name}
              onChange={e => setNm(p => ({ ...p, name: e.target.value }))}
            />

            {showDose && (
              <>
                {sectionLabel(doseLabel)}
                <div style={{ display: "flex", flexWrap: "wrap" as const, gap: 8, marginBottom: 20 }}>
                  {doseOptions.map(d => (
                    <button key={d} onClick={() => setNm(p => ({ ...p, dose: d }))} style={pill(nm.dose === d)}>{d}</button>
                  ))}
                </div>
              </>
            )}

            {showFreq && (
              <>
                {sectionLabel("Frequency")}
                <div style={{ display: "flex", flexWrap: "wrap" as const, gap: 8, marginBottom: 20 }}>
                  {ALL_FREQ.map(f => (
                    <button key={f} onClick={() => setNm(p => ({ ...p, freq: f }))} style={pill(nm.freq === f)}>{f}</button>
                  ))}
                </div>
              </>
            )}

            {sectionLabel("Quantity (To buy from Pharmacy)")}
            <div style={{ display: "flex", flexWrap: "wrap" as const, gap: 8, marginBottom: 20 }}>
              {qtyOptions.map(q => (
                <button key={q} onClick={() => setNm(p => ({ ...p, qty: q }))} style={pill(nm.qty === q)}>{q}</button>
              ))}
            </div>

            {showMeal && (
              <>
                {sectionLabel("Before / After Meal")}
                <div style={{ display: "flex", borderRadius: 16, overflow: "hidden", border: "1.5px solid #e4e0f0", marginBottom: 24, background: C.white }}>
                  {MEAL_OPTS.map(m => (
                    <button key={m} onClick={() => setNm(p => ({ ...p, meal: m }))} style={{
                      flex: 1, padding: "15px", border: "none",
                      background: nm.meal === m ? C.pink : C.white,
                      color: nm.meal === m ? "#fff" : "#a0a0bc",
                      fontWeight: 700, fontSize: 14, cursor: "pointer", transition: "all .15s",
                    }}>{m}</button>
                  ))}
                </div>
              </>
            )}

            {showMethod && (
              <>
                {sectionLabel("Method")}
                <div style={{ display: "flex", borderRadius: 16, overflow: "hidden", border: "1.5px solid #e4e0f0", marginBottom: 24 }}>
                  {METHOD_OPTS.map((m, i) => (
                    <button key={m} onClick={() => setNm(p => ({ ...p, meal: m }))} style={{
                      flex: 1, padding: "15px", border: "none",
                      background: nm.meal === m ? (i === 0 ? C.pink : C.purpleMid) : C.white,
                      color: nm.meal === m ? "#fff" : "#a0a0bc",
                      fontWeight: 700, fontSize: 15, cursor: "pointer", transition: "all .15s",
                    }}>{m}</button>
                  ))}
                </div>
              </>
            )}

            <button
              onClick={doAdd}
              style={{ width: "100%", padding: "15px", borderRadius: 16, border: "none", background: C.pink, color: "#fff", fontWeight: 700, fontSize: 15, cursor: "pointer", boxShadow: "0 4px 14px rgba(240,98,146,0.35)" }}
            >
              Add Medicine
            </button>
          </div>
        </Bottomsheetmodal>
      )}
    </>
  );
}

/* ═══════════════════════════════════════════════════════
   INSTRUCTION STEP
═══════════════════════════════════════════════════════ */
function InstructionStep({
  selected, onSelect, apiInstructions,
}: {
  selected: { lang: string; groupIndex: number } | null;
  onSelect: (lang: string, gi: number) => void;
  apiInstructions: ApiInstruction[];
}) {
  if (apiInstructions.length === 0) {
    return (
      <EmptyState
        icon={<ScanLine size={30} />}
        title="No instructions saved yet."
        subtitle="Tap below to import or add your own."
      />
    );
  }

  return (
    <>
      {apiInstructions.map((inst, gi) => {
        const isSel = selected?.groupIndex === gi;
        return (
          <div key={inst.id} onClick={() => onSelect("api", gi)} style={{
            background: C.white, borderRadius: 12, padding: 13, marginBottom: 9,
            border: isSel ? `2px solid ${C.pink}` : `1px solid ${C.cardBorder}`,
            cursor: "pointer", position: "relative" as const, transition: "border-color .15s",
          }}>
            <div style={{ position: "absolute" as const, top: 12, right: 12, width: 18, height: 18, borderRadius: "50%", border: isSel ? "none" : `2px solid ${C.chipBorder}`, background: isSel ? C.pink : "transparent", display: "flex", alignItems: "center", justifyContent: "center" }}>
              {isSel && <div style={{ width: 6, height: 6, borderRadius: "50%", background: "#fff" }} />}
            </div>
            <div style={{ fontWeight: 700, fontSize: 13, color: C.textMain, textAlign: "center" as const, marginBottom: 8, paddingBottom: 7, paddingRight: 24, borderBottom: `1px solid ${C.cardBorder}` }}>
              {inst.symptomName}
            </div>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 7, marginBottom: 5 }}>
              <span style={{ fontSize: 13, flexShrink: 0 }}>✅</span>
              <span style={{ fontSize: 13, color: "#000000", lineHeight: 1.5 }}>{inst.shouldDo}</span>
            </div>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 7, marginBottom: inst.extra ? 5 : 0 }}>
              <span style={{ fontSize: 13, flexShrink: 0 }}>❌</span>
              <span style={{ fontSize: 13, color: "#000000", lineHeight: 1.5 }}>{inst.shouldNotDo}</span>
            </div>
            {inst.extra && (
              <div style={{ display: "flex", alignItems: "flex-start", gap: 7 }}>
                <span style={{ fontSize: 13, flexShrink: 0 }}>📄</span>
                <span style={{ fontSize: 13, color: "#000000", lineHeight: 1.5 }}>{inst.extra}</span>
              </div>
            )}
          </div>
        );
      })}
    </>
  );
}

/* ═══════════════════════════════════════════════════════
   HELPERS
═══════════════════════════════════════════════════════ */
function FieldLabel({ children }: { children: React.ReactNode }) {
  return (
    <div style={{ fontSize: 11, fontWeight: 700, color: C.textSub, marginBottom: 6, textTransform: "uppercase" as const, letterSpacing: "0.06em" }}>
      {children}
    </div>
  );
}
function EmptyState({
  icon, title, subtitle,
}: { icon: React.ReactNode; title: string; subtitle: string }) {
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column" as const,
        alignItems: "center",
        justifyContent: "center",
        textAlign: "center" as const,
        padding: "44px 20px",
      }}
    >
      <div
        style={{
          width: 72,
          height: 72,
          borderRadius: 20,
          background: C.pinkLight,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          color: C.pink,
          marginBottom: 18,
        }}
      >
        {icon}
      </div>
      <div style={{ fontSize: 16, fontWeight: 800, color: C.textMain, marginBottom: 6 }}>
        {title}
      </div>
      <div style={{ fontSize: 13, color: C.textSub, maxWidth: 260, lineHeight: 1.5 }}>
        {subtitle}
      </div>
    </div>
  );
}
/* ═══════════════════════════════════════════════════════
   SHARED STYLES
═══════════════════════════════════════════════════════ */
const S = {
  card: {
    background: C.white, borderRadius: 14, padding: "16px", marginBottom: 12,
    border: `1px solid ${C.cardBorder}`, display: "flex" as const,
    flexDirection: "column" as const, gap: 10,
  },
  cardSectionLabel: {
    fontSize: 11, fontWeight: 700, color: C.textSub,
    textTransform: "uppercase" as const, letterSpacing: "0.06em",
    paddingBottom: 6, borderBottom: `1px solid ${C.cardBorder}`,
  },
  field: {
    width: "100%" as const, padding: "11px 13px", borderRadius: 9,
    border: `1px solid ${C.chipBorder}`, background: C.fieldBg,
    fontSize: 13, color: C.textMain, outline: "none" as const,
    display: "block" as const, boxSizing: "border-box" as const,
  },
  pinkBtn: {
    padding: "13px 22px", background: C.pink, color: "#fff",
    border: "none", borderRadius: 12, fontSize: 14, fontWeight: 700 as const,
    cursor: "pointer", display: "flex" as const,
    alignItems: "center" as const, justifyContent: "center" as const, gap: 8,
  },
  ghostBtn: {
    padding: "13px 18px", background: C.fieldBg, color: C.textSub,
    border: `1px solid ${C.chipBorder}`, borderRadius: 12,
    fontSize: 13, fontWeight: 600 as const, cursor: "pointer",
  },
  addDashedBtn: {
    display: "flex" as const, alignItems: "center" as const, gap: 12,
    padding: "11px 12px", borderRadius: 10,
    border: `1.5px dashed ${C.chipBorder}`, background: "transparent",
    cursor: "pointer", width: "100%", textAlign: "left" as const,
  },
  plusCircle: {
    width: 32, height: 32, borderRadius: "50%" as const,
    background: C.pinkLight, color: C.pink,
    display: "inline-flex" as const, alignItems: "center" as const,
    justifyContent: "center" as const, fontSize: 17, flexShrink: 0 as const,
  },
  emptyBox: {
    display: "flex" as const, flexDirection: "column" as const,
    alignItems: "center" as const, gap: 5, padding: "16px 0",
  },
  emptyIcon: {
    width: 44, height: 44, borderRadius: 10, background: C.purpleLight,
    display: "flex" as const, alignItems: "center" as const,
    justifyContent: "center" as const, fontSize: 20,
  },
  infoBox: {
    background: C.pinkLight, borderRadius: 9, padding: "10px 13px",
    marginBottom: 16, fontSize: 12, color: C.pink, lineHeight: 1.5,
  },
  previewContainer: {
    flex: 1, display: "flex", justifyContent: "center",
    alignItems: "flex-start", overflow: "hidden", padding: 24,
  },
};