import React, { useCallback, useState } from 'react';
import { FaArrowLeft, FaCheckCircle, FaExclamationTriangle, FaPhoneAlt, FaRedo, FaThLarge } from 'react-icons/fa';

// ── Types ─────────────────────────────────────────────────────────────────────

type NodeId = string;

interface QuestionNode {
  type: 'question';
  id: NodeId;
  ref: string;           // e.g. "7-7-1"
  question: string;
  yes: NodeId;
  no: NodeId;
}

interface ActionNode {
  type: 'action';
  id: NodeId;
  ref: string;
  variant: 'fix' | 'escalate' | 'info';
  title: string;
  body: string;
}

interface ChecklistNode {
  type: 'checklist';
  id: NodeId;
  ref: string;
  title: string;
  steps: string[];       // sequential numbered steps
}

type FlowNode = QuestionNode | ActionNode | ChecklistNode;

interface FlowTree {
  id: string;
  label: string;
  icon: string;
  symptom: string;       // short label shown on selector button
  startId: NodeId;
  nodes: Record<NodeId, FlowNode>;
}

// ── Flowchart data from GE Voluson 730 Service Manual Section 7-7 ─────────────

const FLOWS: FlowTree[] = [
  // ── 7-7-1 System does not Power On / Boot Up ─────────────────────────────
  {
    id: 'boot',
    label: 'System does not Power On / Boot Up',
    icon: '⚡',
    symptom: 'Won\'t power on',
    startId: 'q1',
    nodes: {
      q1: {
        type: 'question', id: 'q1', ref: '7-7-1',
        question: 'Is the scanner plugged into a wall outlet?',
        yes: 'q2', no: 'a_plug',
      },
      a_plug: {
        type: 'action', id: 'a_plug', ref: '7-7-1', variant: 'fix',
        title: 'Plug in the scanner',
        body: 'Make sure the scanner is plugged into a standard wall outlet. Do NOT use a red emergency power outlet.',
      },
      q2: {
        type: 'question', id: 'q2', ref: '7-7-1',
        question: 'Is there AC voltage at the wall outlet and is the circuit breaker ON?',
        yes: 'q3', no: 'a_power',
      },
      a_power: {
        type: 'action', id: 'a_power', ref: '7-7-1', variant: 'escalate',
        title: 'No mains power detected',
        body: 'Check the circuit breaker and confirm mains supply. If the breaker is tripped, reset it. If AC is still absent, contact facilities — this is a building power issue.',
      },
      q3: {
        type: 'question', id: 'q3', ref: '7-7-1',
        question: 'Is there fan noise within a few seconds of pressing the ON/OFF switch?',
        yes: 'a_ready', no: 'a_no_fan',
      },
      a_ready: {
        type: 'action', id: 'a_ready', ref: '7-7-1', variant: 'fix',
        title: 'System is booting normally',
        body: 'Fan noise confirms the Primary Power Supply is working. Wait for the system to fully boot. The ON/OFF button should illuminate amber (standby) then green (ready).',
      },
      a_no_fan: {
        type: 'action', id: 'a_no_fan', ref: '7-7-1', variant: 'escalate',
        title: 'Primary Power Supply suspect',
        body: 'No fan noise indicates the Primary Power Supply (CPN) may be faulty.\n• Check the power switch above the mains plug on the CPN — ensure it is ON.\n• Check all connections to and from the Power Supply.\n• Check the cable from the Power Supply to the GEF module (see Section 7-3 for voltage check points).\n• If connections are OK but still no power, replace the Primary Power Supply. Contact your dealer.',
      },
    },
  },

  // ── 7-7-2 Noise in Image ─────────────────────────────────────────────────
  {
    id: 'noise',
    label: 'Noise in Image',
    icon: '📡',
    symptom: 'Image noise / artefacts',
    startId: 'q1',
    nodes: {
      q1: {
        type: 'question', id: 'q1', ref: '7-7-2',
        question: 'Are there any electrical devices near the scanner (monitors, phones, other medical equipment)?',
        yes: 'a_move', no: 'a_probe',
      },
      a_move: {
        type: 'action', id: 'a_move', ref: '7-7-2', variant: 'fix',
        title: 'Remove interfering electrical devices',
        body: 'Keep the scanner away from devices that may cause electromagnetic interference. Try a different wall socket on a separate circuit. Re-test image quality after moving the device.',
      },
      a_probe: {
        type: 'action', id: 'a_probe', ref: '7-7-2', variant: 'fix',
        title: 'Check the probe / transducer',
        body: 'No obvious nearby interference detected. Inspect the probe:\n• Check the probe cable for kinks or damage.\n• Try a different probe connector port.\n• If noise persists with all probes, contact your dealer — possible GEF board issue.',
      },
    },
  },

  // ── 7-7-3 Trackball ──────────────────────────────────────────────────────
  {
    id: 'trackball',
    label: 'Trackball Low Sensitivity',
    icon: '🖱️',
    symptom: 'Trackball not working',
    startId: 'q1',
    nodes: {
      q1: {
        type: 'question', id: 'q1', ref: '7-7-3',
        question: 'Does the trackball move at all when rolled?',
        yes: 'a_clean', no: 'a_replace',
      },
      a_clean: {
        type: 'action', id: 'a_clean', ref: '7-7-3', variant: 'fix',
        title: 'Clean the trackball',
        body: 'The ball moves but is sluggish — it needs cleaning.\n• Remove the ball from the trackball housing.\n• Clean the ball and the internal rollers with a dry lint-free cloth.\n• Reinsert and test sensitivity.',
      },
      a_replace: {
        type: 'action', id: 'a_replace', ref: '7-7-3', variant: 'escalate',
        title: 'Replace the trackball unit',
        body: 'The trackball does not respond at all — the unit is likely faulty.\n• Replacement part: KTZ208256 (Trackball top fixation ring, Section 8-4).\n• Contact your dealer for unit replacement if not in stock.',
      },
    },
  },

  // ── 7-7-4 System does not Power Off / Shutdown ──────────────────────────
  {
    id: 'shutdown',
    label: 'System does not Power Off / Shutdown',
    icon: '🔴',
    symptom: 'Won\'t shut down',
    startId: 'q1',
    nodes: {
      q1: {
        type: 'question', id: 'q1', ref: '7-7-4',
        question: 'After pressing the OFF button, does the system start the shutdown procedure at all?',
        yes: 'q2', no: 'a_switch',
      },
      a_switch: {
        type: 'action', id: 'a_switch', ref: '7-7-4', variant: 'escalate',
        title: 'Check ON/OFF switch and cable',
        body: 'The shutdown procedure does not start — the ON/OFF switch or its cable may be faulty.\n• Inspect the switch cable.\n• If the cable is OK, the Primary Power Supply (CPN) is likely defective.\n• Contact your dealer.',
      },
      q2: {
        type: 'question', id: 'q2', ref: '7-7-4',
        question: 'Does the system eventually power off automatically (within ~3 minutes)?',
        yes: 'a_normal', no: 'a_cpn',
      },
      a_normal: {
        type: 'action', id: 'a_normal', ref: '7-7-4', variant: 'fix',
        title: 'Shutdown is working normally',
        body: 'The system shuts down automatically after approximately 3 minutes as designed. This is normal behaviour — the OS completes its shutdown sequence before cutting power.',
      },
      a_cpn: {
        type: 'action', id: 'a_cpn', ref: '7-7-4', variant: 'escalate',
        title: 'Primary Power Supply (CPN) defective',
        body: 'The system starts shutdown but never fully powers off — the CPN is likely defective.\n• Contact your dealer for CPN replacement.',
      },
    },
  },

  // ── 7-7-5 Monitor Troubleshooting ────────────────────────────────────────
  {
    id: 'monitor',
    label: 'Monitor Troubleshooting',
    icon: '🖥️',
    symptom: 'Monitor / display issue',
    startId: 'q1',
    nodes: {
      q1: {
        type: 'question', id: 'q1', ref: '7-7-5',
        question: 'Is there any image at all on the monitor (even partial or distorted)?',
        yes: 'q2', no: 'a_no_image',
      },
      a_no_image: {
        type: 'action', id: 'a_no_image', ref: '7-7-5', variant: 'fix',
        title: 'No image — check power and cables',
        body: 'Check these items in order:\n• Power cord is properly connected to the monitor and wall.\n• Mains supply switch is set to ON.\n• Video cable is properly connected — no bent pins.\n• If the Power Saving indicator is lit, the monitor is in sleep mode — move the mouse or press a key.\n• If Power indicator flashes alternately green and orange: potential monitor failure — contact your dealer.',
      },
      q2: {
        type: 'question', id: 'q2', ref: '7-7-5',
        question: 'Is the image fuzzy or the colour non-uniform?',
        yes: 'a_fuzzy', no: 'a_position',
      },
      a_fuzzy: {
        type: 'action', id: 'a_fuzzy', ref: '7-7-5', variant: 'fix',
        title: 'Fuzzy image or colour issues',
        body: '• Turn monitor off then on to activate Auto-Degauss (fixes colour non-uniformity).\n• Adjust contrast and brightness settings.\n• Check that no extra video cable is connected to the second video output with the other end loose — this increases video output level and causes fuzz.\n• If problem persists after adjustments, contact your dealer.',
      },
      a_position: {
        type: 'action', id: 'a_position', ref: '7-7-5', variant: 'fix',
        title: 'Image not centred or sized correctly',
        body: 'Adjust picture location, picture size, picture rotation, or pincushion distortion via the monitor\'s on-screen menu. Some video modes do not fill the screen to the edge — this is normal at higher refresh rates.',
      },
    },
  },

  // ── 7-7-7 Printer Troubleshooting ────────────────────────────────────────
  {
    id: 'printer',
    label: 'Printer Troubleshooting',
    icon: '🖨️',
    symptom: 'Printer not working',
    startId: 'q1',
    nodes: {
      q1: {
        type: 'question', id: 'q1', ref: '7-7-7',
        question: 'Is the printer properly connected (signal and power cables secured at both ends)?',
        yes: 'q2', no: 'a_cables',
      },
      a_cables: {
        type: 'action', id: 'a_cables', ref: '7-7-7', variant: 'fix',
        title: 'Reconnect printer cables',
        body: 'Check all signal and power supply cable connections between the printer and the scanner. Reseat all connectors firmly. Power-cycle the printer after reconnecting.',
      },
      q2: {
        type: 'question', id: 'q2', ref: '7-7-7',
        question: 'Is there paper/film loaded in the printer?',
        yes: 'q3', no: 'a_paper',
      },
      a_paper: {
        type: 'action', id: 'a_paper', ref: '7-7-7', variant: 'fix',
        title: 'Load printer paper / film',
        body: 'Insert the correct printer paper or thermal film. Ensure it is loaded in the correct orientation. Close the paper tray firmly.',
      },
      q3: {
        type: 'question', id: 'q3', ref: '7-7-7',
        question: 'Is the Print key correctly configured in the system settings?',
        yes: 'q4', no: 'a_config',
      },
      a_config: {
        type: 'action', id: 'a_config', ref: '7-7-7', variant: 'fix',
        title: 'Configure the Print key',
        body: 'Go to System Setup → Peripherals and configure the Print key(s) to point to the correct printer. Save the configuration and retry printing.',
      },
      q4: {
        type: 'question', id: 'q4', ref: '7-7-7',
        question: 'Is printing unavailable even by manual operation on the printer itself?',
        yes: 'a_gef_cables', no: 'q5',
      },
      a_gef_cables: {
        type: 'action', id: 'a_gef_cables', ref: '7-7-7', variant: 'escalate',
        title: 'Check GEF to backpanel signal cables',
        body: 'Check the signal cables between the GEF board and the Back Panel. If connections are OK, the printer unit may need replacement — contact your dealer.',
      },
      q5: {
        type: 'question', id: 'q5', ref: '7-7-7',
        question: 'Is there still no image on the printout?',
        yes: 'a_video_out', no: 'a_printer_ok',
      },
      a_printer_ok: {
        type: 'action', id: 'a_printer_ok', ref: '7-7-7', variant: 'fix',
        title: 'Printer is OK',
        body: 'The printer is functioning correctly. The issue was likely a temporary communication error. Monitor for recurrence.',
      },
      a_video_out: {
        type: 'action', id: 'a_video_out', ref: '7-7-7', variant: 'escalate',
        title: 'Check video output / replace CKV',
        body: 'No image on printout despite printer responding:\n• Test video output from the system.\n• If video output is faulty → Replace CKV board.\n• If video output is OK → Replace the printer unit.\n• Contact your dealer for board/unit replacement.',
      },
    },
  },

  // ── 7-7-10 Network Troubleshooting ───────────────────────────────────────
  {
    id: 'network',
    label: 'Network — No Connection',
    icon: '🌐',
    symptom: 'No network connection',
    startId: 'q1',
    nodes: {
      q1: {
        type: 'question', id: 'q1', ref: '7-7-10',
        question: 'Is the network cable connected at both ends — scanner and wall socket?',
        yes: 'q2', no: 'a_cable',
      },
      a_cable: {
        type: 'action', id: 'a_cable', ref: '7-7-10', variant: 'fix',
        title: 'Reconnect the network cable',
        body: 'Plug the network cable firmly into both the scanner\'s network port and the wall network socket. Ensure the clip locks in place at both ends.',
      },
      q2: {
        type: 'question', id: 'q2', ref: '7-7-10',
        question: 'Does replacing the cable with a known-good cable restore the connection?',
        yes: 'a_bad_cable', no: 'q3',
      },
      a_bad_cable: {
        type: 'action', id: 'a_bad_cable', ref: '7-7-10', variant: 'fix',
        title: 'Faulty cable — replace it',
        body: 'The original cable was faulty. Replace it with the known-good cable permanently. Label and dispose of the faulty cable.',
      },
      q3: {
        type: 'question', id: 'q3', ref: '7-7-10',
        question: 'Can you ping from the scanner to a PC on the same network?',
        yes: 'a_soft', no: 'a_internal',
      },
      a_soft: {
        type: 'action', id: 'a_soft', ref: '7-7-10', variant: 'fix',
        title: 'Hardware OK — check network settings',
        body: 'Ping is successful, so the hardware path inside the scanner is working. The issue is likely:\n• Wrong IP address or subnet configured on the scanner.\n• VLAN or firewall blocking DICOM traffic.\n• Contact your IT/network team to verify the scanner\'s network configuration.',
      },
      a_internal: {
        type: 'action', id: 'a_internal', ref: '7-7-10', variant: 'escalate',
        title: 'Internal cable — check LAN connector',
        body: 'No ping response indicates a hardware problem inside the scanner.\n• Check the cable between the network connector on the Back Panel and the LAN connector on the GEF board.\n• If the internal cable is OK, the GEF board\'s network interface may be faulty.\n• Contact your dealer.',
      },
    },
  },

  // ── 7-7-6 Unable to Record to VCR ───────────────────────────────────────
  {
    id: 'vcr',
    label: 'Unable to Record to VCR',
    icon: '📼',
    symptom: 'Cannot record to VCR',
    startId: 'q1',
    nodes: {
      q1: {
        type: 'question', id: 'q1', ref: '7-7-6',
        question: 'Is the VCR properly connected (all signal and power cables secured)?',
        yes: 'q2', no: 'a_cables',
      },
      a_cables: {
        type: 'action', id: 'a_cables', ref: '7-7-6', variant: 'fix',
        title: 'Reconnect VCR cables',
        body: 'Check all signal and power supply cable connections to the VCR unit. Reseat all connectors firmly at both ends. Power-cycle the VCR after reconnecting.',
      },
      q2: {
        type: 'question', id: 'q2', ref: '7-7-6',
        question: 'Is a tape inserted and rewound in the VCR?',
        yes: 'q3', no: 'a_tape',
      },
      a_tape: {
        type: 'action', id: 'a_tape', ref: '7-7-6', variant: 'fix',
        title: 'Insert and rewind the tape',
        body: 'Put the VCR tape into the device and rewind it to the beginning before attempting to record.',
      },
      q3: {
        type: 'question', id: 'q3', ref: '7-7-6',
        question: 'Is recording impossible even by manual operation on the VCR itself?',
        yes: 'q4', no: 'a_signal_cables',
      },
      a_signal_cables: {
        type: 'action', id: 'a_signal_cables', ref: '7-7-6', variant: 'fix',
        title: 'Check signal cables between VCR and Internal I/O',
        body: 'The VCR works manually but not from the scanner — check the signal cable connections between the VCR and the Internal I/O board. Reseat all connectors.',
      },
      q4: {
        type: 'question', id: 'q4', ref: '7-7-6',
        question: 'Is the video output of the system working correctly?',
        yes: 'a_replace_vcr', no: 'a_replace_ckv',
      },
      a_replace_vcr: {
        type: 'action', id: 'a_replace_vcr', ref: '7-7-6', variant: 'escalate',
        title: 'Replace the VCR unit',
        body: 'The system video output is OK but the VCR still will not record — the VCR unit is faulty.\n• Contact your dealer for VCR unit replacement.',
      },
      a_replace_ckv: {
        type: 'action', id: 'a_replace_ckv', ref: '7-7-6', variant: 'escalate',
        title: 'Replace the CKV board',
        body: 'The system video output is faulty — the CKV board needs replacement.\n• Contact your dealer for CKV board replacement.',
      },
    },
  },

  // ── 7-7-7-1 CD-RW Troubleshooting ────────────────────────────────────────
  {
    id: 'cdrw',
    label: 'CD-RW Troubleshooting',
    icon: '💿',
    symptom: 'CD-RW drive issue',
    startId: 'c1',
    nodes: {
      c1: {
        type: 'checklist', id: 'c1', ref: '7-7-7-1',
        title: 'CD-RW Backup Procedure',
        steps: [
          'Insert an empty CD-RW disc into the drive.',
          'Press the NETWORK key on the control panel to enter Sonoview.',
          'Click the "Open" icon to display the list of exams.',
          'Select the exam(s) you want to back up.',
          'Choose "CD-ROM" as the destination drive.',
          'Verify the backed-up images are visible on the CD-ROM after the process completes.',
        ],
      },
    },
  },

  // ── 7-7-8 MOD Troubleshooting ────────────────────────────────────────────
  {
    id: 'mod',
    label: 'MOD (MO Disk) Troubleshooting',
    icon: '💾',
    symptom: 'MO disk drive issue',
    startId: 'c1',
    nodes: {
      c1: {
        type: 'checklist', id: 'c1', ref: '7-7-8',
        title: 'MOD Backup Procedure',
        steps: [
          'Insert an empty MO disk into the drive.',
          'Press the NETWORK key on the control panel to enter Sonoview.',
          'Click the "Open" icon to display the list of exams.',
          'Select the exam(s) you want to back up.',
          'Choose "MO" as the destination drive.',
          'Verify the backed-up images are visible on the MO disk after the process completes.',
        ],
      },
    },
  },

  // ── 7-7-9 Audio Test ─────────────────────────────────────────────────────
  {
    id: 'audio',
    label: 'Audio Test',
    icon: '🔊',
    symptom: 'Audio / speaker issue',
    startId: 'c1',
    nodes: {
      c1: {
        type: 'checklist', id: 'c1', ref: '7-7-9',
        title: 'Loudspeaker Audio Test',
        steps: [
          'Start a probe on the scanner.',
          'Select PW-Mode (Pulsed Wave Doppler).',
          'Locate the volume digipot on the control panel.',
          'Slowly increase the volume from 0 to 96 dB.',
          'Listen to both loudspeakers — both should produce clear audio at each volume level.',
          'If one or both speakers produce no sound or distorted sound, contact your dealer.',
        ],
      },
    },
  },
];

// ── Breadcrumb trail type ─────────────────────────────────────────────────────

interface HistoryEntry {
  nodeId: NodeId;
  answer?: 'yes' | 'no';
}

// ── Props ─────────────────────────────────────────────────────────────────────

interface UltrasoundFlowchartProps {
  /** Called when the technician completes a flow or escalates — optional */
  onComplete?: (flowId: string, terminal: ActionNode) => void;
}

// ── Component ─────────────────────────────────────────────────────────────────

const UltrasoundFlowchart: React.FC<UltrasoundFlowchartProps> = ({ onComplete }) => {
  const [selectedFlow, setSelectedFlow] = useState<FlowTree | null>(null);
  const [currentNodeId, setCurrentNodeId] = useState<NodeId>('');
  const [history, setHistory] = useState<HistoryEntry[]>([]);

  // ── Navigation ───────────────────────────────────────────────────────────

  const selectFlow = useCallback((flow: FlowTree) => {
    setSelectedFlow(flow);
    setCurrentNodeId(flow.startId);
    setHistory([]);
  }, []);

  const answer = useCallback(
    (choice: 'yes' | 'no') => {
      if (!selectedFlow) return;
      const node = selectedFlow.nodes[currentNodeId];
      if (node.type !== 'question') return;

      setHistory((h) => [...h, { nodeId: currentNodeId, answer: choice }]);
      setCurrentNodeId(choice === 'yes' ? node.yes : node.no);
    },
    [selectedFlow, currentNodeId],
  );

  const goBack = useCallback(() => {
    if (!history.length) {
      // Back to problem selector
      setSelectedFlow(null);
      setCurrentNodeId('');
      setHistory([]);
      return;
    }
    const prev = history[history.length - 1];
    setCurrentNodeId(prev.nodeId);
    setHistory((h) => h.slice(0, -1));
  }, [history]);

  const restart = useCallback(() => {
    if (!selectedFlow) return;
    setCurrentNodeId(selectedFlow.startId);
    setHistory([]);
  }, [selectedFlow]);

  const backToSelector = useCallback(() => {
    setSelectedFlow(null);
    setCurrentNodeId('');
    setHistory([]);
  }, []);

  // ── Derived state ────────────────────────────────────────────────────────

  const currentNode = selectedFlow ? selectedFlow.nodes[currentNodeId] : null;
  const isTerminal = currentNode?.type === 'action';

  // Notify parent when reaching a terminal
  React.useEffect(() => {
    if (isTerminal && selectedFlow && currentNode?.type === 'action') {
      onComplete?.(selectedFlow.id, currentNode);
    }
  }, [isTerminal, selectedFlow, currentNode, onComplete]);

  // ── Breadcrumb labels ────────────────────────────────────────────────────

  const breadcrumbs = history.map((h) => {
    if (!selectedFlow) return null;
    const n = selectedFlow.nodes[h.nodeId];
    if (n.type !== 'question') return null;
    return { question: n.question, answer: h.answer! };
  }).filter(Boolean) as { question: string; answer: 'yes' | 'no' }[];

  // ── Shared style tokens (matching SupportTroubleshoot.tsx) ───────────────

  const TEAL_GRADIENT = 'bg-gradient-to-r from-blue-500 to-teal-600';
  const TEAL_GRADIENT_HOVER = 'hover:from-blue-600 hover:to-teal-700';

  const BTN_YES =
    'flex-1 min-h-[52px] flex items-center justify-center gap-2 py-3 px-4 rounded-2xl text-white text-sm font-semibold shadow-md transition-all active:scale-[0.98] focus:outline-none focus-visible:ring-2 focus-visible:ring-teal-400 focus-visible:ring-offset-2 bg-gradient-to-r from-teal-500 to-green-500 hover:from-teal-600 hover:to-green-600';

  const BTN_NO =
    'flex-1 min-h-[52px] flex items-center justify-center gap-2 py-3 px-4 rounded-2xl text-white text-sm font-semibold shadow-md transition-all active:scale-[0.98] focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400 focus-visible:ring-offset-2 bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600';

  const BTN_BACK =
    'flex items-center gap-1.5 text-sm font-medium text-blue-700 dark:text-teal-300 hover:text-blue-900 dark:hover:text-white transition-colors min-h-[44px] px-1';

  const BTN_RESTART =
    'flex items-center gap-1.5 text-sm font-medium text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors min-h-[44px] px-1';

  // ── Terminal card colours ────────────────────────────────────────────────

  const terminalStyle = (variant: ActionNode['variant']) => {
    if (variant === 'fix')
      return {
        bg: 'bg-green-50 dark:bg-green-900/20',
        border: 'border-green-200 dark:border-green-800',
        icon: <FaCheckCircle className="text-green-500 text-xl shrink-0 mt-0.5" />,
        badge: 'bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300',
        badgeLabel: 'Self-fix action',
      };
    if (variant === 'escalate')
      return {
        bg: 'bg-amber-50 dark:bg-amber-900/20',
        border: 'border-amber-200 dark:border-amber-800',
        icon: <FaPhoneAlt className="text-amber-500 text-xl shrink-0 mt-0.5" />,
        badge: 'bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300',
        badgeLabel: 'Contact your dealer',
      };
    return {
      bg: 'bg-blue-50 dark:bg-blue-900/20',
      border: 'border-blue-200 dark:border-blue-800',
      icon: <FaExclamationTriangle className="text-blue-500 text-xl shrink-0 mt-0.5" />,
      badge: 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300',
      badgeLabel: 'Information',
    };
  };

  // ── Render: problem selector ─────────────────────────────────────────────

  if (!selectedFlow) {
    return (
      <div className="space-y-4">
        {/* Instruction row */}
        <p className="text-[10px] sm:text-[11px] font-semibold tracking-wide text-gray-500 dark:text-gray-400 uppercase">
          Select a problem type
        </p>

        {/* Flow selector grid */}
        <div className="grid grid-cols-1 gap-2 sm:gap-3">
          {FLOWS.map((flow) => (
            <button
              key={flow.id}
              type="button"
              onClick={() => selectFlow(flow)}
              className="w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl text-left text-sm font-medium transition-all min-h-[56px] bg-white/80 dark:bg-gray-800/90 border border-blue-100 dark:border-gray-700 hover:border-teal-400 dark:hover:border-teal-500 hover:bg-blue-50/60 dark:hover:bg-teal-950/30 active:scale-[0.99] shadow-sm group"
            >
              <span className="text-xl shrink-0 w-7 text-center">{flow.icon}</span>
              <div className="min-w-0 flex-1">
                <span className="block text-gray-800 dark:text-gray-100 font-semibold text-sm leading-snug group-hover:text-teal-700 dark:group-hover:text-teal-300 transition-colors">
                  {flow.symptom}
                </span>
              </div>
              <span className="text-gray-300 dark:text-gray-600 group-hover:text-teal-400 transition-colors text-lg">›</span>
            </button>
          ))}
        </div>
      </div>
    );
  }

  // ── Render: active flowchart ─────────────────────────────────────────────

  if (!currentNode) return null;

  return (
    <div className="space-y-4">
      {/* Top navigation row */}
      <div className="flex items-center justify-between">
        <button type="button" onClick={goBack} className={BTN_BACK}>
          <FaArrowLeft className="text-sm" />
          {history.length === 0 ? 'All problems' : 'Back'}
        </button>
        <div className="flex items-center gap-3">
          <button type="button" onClick={backToSelector} className={BTN_RESTART} title="Back to problem list">
            <FaThLarge className="text-sm" />
          </button>
          {history.length > 0 && (
            <button type="button" onClick={restart} className={BTN_RESTART} title="Restart this flowchart">
              <FaRedo className="text-sm" />
            </button>
          )}
        </div>
      </div>

      {/* Flow title chip */}
      <div className="flex items-center gap-2">
        <span className="text-base">{selectedFlow.icon}</span>
        <span className={`text-xs font-semibold px-2.5 py-1 rounded-full text-white ${TEAL_GRADIENT}`}>
          {currentNode.ref}
        </span>
        <span className="text-xs text-gray-500 dark:text-gray-400 truncate">
          {selectedFlow.symptom}
        </span>
      </div>

      {/* Breadcrumb trail */}
      {breadcrumbs.length > 0 && (
        <div className="flex flex-col gap-1 px-3 py-2.5 rounded-xl bg-gray-50 dark:bg-gray-900/50 border border-gray-100 dark:border-gray-700">
          {breadcrumbs.map((b, i) => (
            <div key={i} className="flex items-start gap-2 text-xs text-gray-500 dark:text-gray-400">
              <span className={`shrink-0 font-bold mt-0.5 ${b.answer === 'yes' ? 'text-green-600 dark:text-green-400' : 'text-red-500 dark:text-red-400'}`}>
                {b.answer === 'yes' ? 'YES' : 'NO '}
              </span>
              <span className="leading-relaxed line-clamp-2">{b.question}</span>
            </div>
          ))}
        </div>
      )}

      {/* ── Question node ── */}
      {currentNode.type === 'question' && (
        <div className="rounded-2xl border border-blue-200/60 dark:border-gray-700 bg-white/95 dark:bg-gray-800/95 shadow-lg shadow-blue-500/5 overflow-hidden">
          {/* Teal header bar */}
          <div className={`h-1.5 w-full ${TEAL_GRADIENT}`} />

          <div className="p-5 sm:p-6 space-y-5">
            {/* Step indicator */}
            <p className="text-[10px] font-semibold tracking-widest text-gray-400 dark:text-gray-500 uppercase">
              Step {history.length + 1}
            </p>

            {/* Question */}
            <h3 className="text-base sm:text-lg font-bold text-gray-900 dark:text-white leading-snug">
              {currentNode.question}
            </h3>

            {/* YES / NO buttons */}
            <div className="flex gap-3 pt-1">
              <button type="button" onClick={() => answer('yes')} className={BTN_YES}>
                <span className="text-lg">✓</span>
                YES
              </button>
              <button type="button" onClick={() => answer('no')} className={BTN_NO}>
                <span className="text-lg">✗</span>
                NO
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── Terminal / action node ── */}
      {currentNode.type === 'action' && (() => {
        const style = terminalStyle(currentNode.variant);
        return (
          <div className={`rounded-2xl border ${style.border} ${style.bg} overflow-hidden shadow-md`}>
            <div className="p-5 sm:p-6 space-y-4">
              {/* Badge */}
              <span className={`inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full ${style.badge}`}>
                {style.icon}
                {style.badgeLabel}
              </span>

              {/* Title */}
              <h3 className="text-base sm:text-lg font-bold text-gray-900 dark:text-white leading-snug">
                {currentNode.title}
              </h3>

              {/* Body — preserve newlines */}
              <div className="rounded-xl bg-white/70 dark:bg-gray-900/40 border border-white/80 dark:border-gray-700 p-4">
                {currentNode.body.split('\n').map((line, i) => (
                  <p key={i} className={`text-sm text-gray-700 dark:text-gray-300 leading-relaxed ${i > 0 && line.startsWith('•') ? 'mt-1.5' : i > 0 ? 'mt-2' : ''}`}>
                    {line}
                  </p>
                ))}
              </div>

              {/* Manual reference */}
              <p className="text-xs text-gray-400 dark:text-gray-500">
                GE Voluson 730 Service Manual · Section {currentNode.ref}
              </p>

              {/* Restart / back buttons */}
              <div className="flex gap-3 pt-1">
                <button
                  type="button"
                  onClick={restart}
                  className="flex-1 min-h-[48px] flex items-center justify-center gap-2 py-3 px-4 rounded-2xl text-sm font-semibold border-2 border-blue-300/80 dark:border-teal-700/60 text-blue-700 dark:text-teal-300 bg-white/80 dark:bg-gray-800/80 hover:bg-blue-50 dark:hover:bg-teal-950/30 transition-all active:scale-[0.98]"
                >
                  <FaRedo className="text-xs" />
                  Restart flow
                </button>
                <button
                  type="button"
                  onClick={backToSelector}
                  className="flex-1 min-h-[48px] flex items-center justify-center gap-2 py-3 px-4 rounded-2xl text-sm font-semibold border-2 border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300 bg-white/80 dark:bg-gray-800/80 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-all active:scale-[0.98]"
                >
                  <FaThLarge className="text-xs" />
                  All problems
                </button>
              </div>
            </div>
          </div>
        );
      })()}
      {/* ── Checklist node ── */}
      {currentNode.type === 'checklist' && (
        <div className="rounded-2xl border border-teal-200/60 dark:border-gray-700 bg-white/95 dark:bg-gray-800/95 shadow-lg overflow-hidden">
          <div className={`h-1.5 w-full ${TEAL_GRADIENT}`} />
          <div className="p-5 sm:p-6 space-y-4">
            <span className="inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-300">
              📋 Step-by-step procedure
            </span>
            <h3 className="text-base sm:text-lg font-bold text-gray-900 dark:text-white leading-snug">
              {currentNode.title}
            </h3>
            <div className="rounded-xl bg-gray-50 dark:bg-gray-900/50 border border-gray-100 dark:border-gray-700 divide-y divide-gray-100 dark:divide-gray-700">
              {currentNode.steps.map((step, i) => (
                <div key={i} className="flex items-start gap-3 p-3.5">
                  <span className={`shrink-0 w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white mt-0.5 ${TEAL_GRADIENT}`}>
                    {i + 1}
                  </span>
                  <p className="text-sm text-gray-700 dark:text-gray-300 leading-relaxed">{step}</p>
                </div>
              ))}
            </div>
            <p className="text-xs text-gray-400 dark:text-gray-500">
              GE Voluson 730 Service Manual · Section {currentNode.ref}
            </p>
            <div className="flex gap-3 pt-1">
              <button
                type="button"
                onClick={backToSelector}
                className="flex-1 min-h-[48px] flex items-center justify-center gap-2 py-3 px-4 rounded-2xl text-sm font-semibold border-2 border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300 bg-white/80 dark:bg-gray-800/80 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-all active:scale-[0.98]"
              >
                <FaThLarge className="text-xs" />
                All problems
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default UltrasoundFlowchart;