/**
 * Settings Component
 *
 * Provides configuration for pharmacokinetic parameters (half-lives,
 * absorption rates) and UI settings (chart view, therapeutic ranges,
 * x-axis format). Includes data management (import/export/reset).
 *
 * @author Andreas Weyer
 * @license MIT
 */

import React from 'react';
import { Card, CardContent } from './ui/card';
import { Label } from './ui/label';
import { Switch } from './ui/switch';
import { Separator } from './ui/separator';
import { Button } from './ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { FormNumericInput } from './ui/form-numeric-input';
import CollapsibleCardHeader from './ui/collapsible-card-header';
import { Info } from 'lucide-react';
import { getDefaultState } from '../constants/defaults';

/**
 * Helper function to create translation interpolation values for defaults.
 * Derives default values dynamically from hardcoded defaults.
 */
const getDefaultsForTranslation = (pkParams: any, therapeuticRange: any, uiSettings: any) => {
  const defaults = getDefaultState();

  return {
    // UI Settings
    simulationDays: defaults.uiSettings.simulationDays,
    displayedDays: defaults.uiSettings.displayedDays,
    yAxisMin: defaults.uiSettings.yAxisMin,
    yAxisMax: defaults.uiSettings.yAxisMax,
    therapeuticRangeMin: defaults.therapeuticRange.min,
    therapeuticRangeMax: defaults.therapeuticRange.max,

    // PK Parameters
    damphHalfLife: defaults.pkParams.damph.halfLife,
    ldxHalfLife: defaults.pkParams.ldx.halfLife,
    ldxAbsorptionHalfLife: defaults.pkParams.ldx.absorptionHalfLife,

    // Advanced Settings
    standardVdValue: defaults.pkParams.advanced.standardVd?.preset === 'adult' ? '377' : defaults.pkParams.advanced.standardVd?.preset === 'child' ? '175' : defaults.pkParams.advanced.standardVd?.customValue || '377',
    standardVdPreset: defaults.pkParams.advanced.standardVd?.preset || 'adult',
    customVdValue: defaults.pkParams.advanced.standardVd.customValue,
    bodyWeight: defaults.pkParams.advanced.standardVd.bodyWeight,
    tmaxDelay: defaults.pkParams.advanced.foodEffect.tmaxDelay,
    fOral: defaults.pkParams.advanced.fOral,
    fOralPercent: String((parseFloat(defaults.pkParams.advanced.fOral) * 100).toFixed(1)),
    steadyStateDays: defaults.pkParams.advanced.steadyStateDays,
  };
};

/**
 * Helper function to interpolate translation strings with default values.
 * @example t('simulationDurationTooltip', defaultsForT) → "...Default: 5 days."
 */
const tWithDefaults = (translationFn: any, key: string, defaults: Record<string, string>) => {
  const translated = translationFn(key);
  let result = translated;

  // Replace all {{placeholder}} patterns with values from defaults object
  Object.entries(defaults).forEach(([placeholder, value]) => {
    result = result.replace(new RegExp(`{{${placeholder}}}`, 'g'), String(value));
  });

  return result;
};

/**
 * Helper function to render tooltip content with inline source links.
 * Parses [link text](url) markdown-style syntax and renders as clickable links.
 * @example "See [this study](https://example.com)" → clickable link within tooltip
 */
const renderTooltipWithLinks = (text: string): React.ReactNode => {
  const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
  const parts: React.ReactNode[] = [];
  let lastIndex = 0;
  let match;

  while ((match = linkRegex.exec(text)) !== null) {
    // Add text before link
    if (match.index > lastIndex) {
      parts.push(text.substring(lastIndex, match.index));
    }
    // Add link
    parts.push(
      <a
        key={`link-${match.index}`}
        href={match[2]}
        target="_blank"
        rel="noopener noreferrer"
        className="underline italic text-yellow-300 hover:text-yellow-200 cursor-pointer"
      >
        {match[1]}
      </a>
    );
    lastIndex = linkRegex.lastIndex;
  }

  // Add remaining text
  if (lastIndex < text.length) {
    parts.push(text.substring(lastIndex));
  }

  return parts.length > 0 ? parts : text;
};

const Settings = ({
  pkParams,
  therapeuticRange,
  uiSettings,
  days,
  doseIncrement,
  onUpdatePkParams,
  onUpdateTherapeuticRange,
  onUpdateUiSetting,
  onImportDays,
  onOpenDataManagement,
  t
}: any) => {
  const { showDayTimeOnXAxis, yAxisMin, yAxisMax, showTemplateDay, simulationDays, displayedDays } = uiSettings;
  const showDayReferenceLines = (uiSettings as any).showDayReferenceLines ?? true;
  const showTherapeuticRange = (uiSettings as any).showTherapeuticRange ?? true;
  const steadyStateDaysEnabled = (uiSettings as any).steadyStateDaysEnabled ?? true;

  const [isDiagramExpanded, setIsDiagramExpanded] = React.useState(true);
  const [isSimulationExpanded, setIsSimulationExpanded] = React.useState(true);
  const [isPharmacokineticExpanded, setIsPharmacokineticExpanded] = React.useState(true);
  const [isAdvancedExpanded, setIsAdvancedExpanded] = React.useState(false);

  // Track which tooltip is currently open (for mobile touch interaction)
  const [openTooltipId, setOpenTooltipId] = React.useState<string | null>(null);

  // Validation state for range inputs
  const [therapeuticRangeError, setTherapeuticRangeError] = React.useState<string>('');
  const [yAxisRangeError, setYAxisRangeError] = React.useState<string>('');

  // Track window width for responsive tooltip positioning
  const [isNarrowScreen, setIsNarrowScreen] = React.useState(
    typeof window !== 'undefined' ? window.innerWidth < 640 : false
  );

  // Update narrow screen state on window resize
  React.useEffect(() => {
    const handleResize = () => {
      setIsNarrowScreen(window.innerWidth < 640);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // Determine tooltip side based on screen width
  const tooltipSide = isNarrowScreen ? 'top' : 'right';

  // Load and persist settings card expansion states
  React.useEffect(() => {
    const savedStates = localStorage.getItem('settingsCardStates_v1');
    if (savedStates) {
      try {
        const states = JSON.parse(savedStates);
        if (states.diagram !== undefined) setIsDiagramExpanded(states.diagram);
        if (states.simulation !== undefined) setIsSimulationExpanded(states.simulation);
        if (states.pharmacokinetic !== undefined) setIsPharmacokineticExpanded(states.pharmacokinetic);
        if (states.advanced !== undefined) setIsAdvancedExpanded(states.advanced);
      } catch (e) {
        console.warn('Failed to load settings card states:', e);
      }
    }
  }, []);

  // Close tooltip when clicking outside
  React.useEffect(() => {
    if (!openTooltipId) return;

    const handleClickOutside = (e: MouseEvent | TouchEvent) => {
      const target = e.target as HTMLElement;
      // Check if click is outside tooltip content and button
      if (!target.closest('[role="tooltip"]') && !target.closest('button[aria-label*="Tooltip"]')) {
        setOpenTooltipId(null);
      }
    };

    // Small delay to prevent immediate closure
    setTimeout(() => {
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('touchstart', handleClickOutside);
    }, 10);

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
    };
  }, [openTooltipId]);

  // Helper to toggle tooltip (for mobile click interaction)
  const handleTooltipToggle = (tooltipId: string) => (e: React.MouseEvent<HTMLButtonElement> | React.TouchEvent<HTMLButtonElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setOpenTooltipId(current => current === tooltipId ? null : tooltipId);
  };

  const updateDiagramExpanded = (value: boolean) => {
    setIsDiagramExpanded(value);
    saveCardStates({ diagram: value, simulation: isSimulationExpanded, pharmacokinetic: isPharmacokineticExpanded, advanced: isAdvancedExpanded });
  };

  const updateSimulationExpanded = (value: boolean) => {
    setIsSimulationExpanded(value);
    saveCardStates({ diagram: isDiagramExpanded, simulation: value, pharmacokinetic: isPharmacokineticExpanded, advanced: isAdvancedExpanded });
  };

  const updatePharmacokineticExpanded = (value: boolean) => {
    setIsPharmacokineticExpanded(value);
    saveCardStates({ diagram: isDiagramExpanded, simulation: isSimulationExpanded, pharmacokinetic: value, advanced: isAdvancedExpanded });
  };

  const updateAdvancedExpanded = (value: boolean) => {
    setIsAdvancedExpanded(value);
    saveCardStates({ diagram: isDiagramExpanded, simulation: isSimulationExpanded, pharmacokinetic: isPharmacokineticExpanded, advanced: value });
  };

  const saveCardStates = (states: any) => {
    localStorage.setItem('settingsCardStates_v1', JSON.stringify(states));
  };

  // Create defaults object for translation interpolation
  const defaultsForT = getDefaultsForTranslation(pkParams, therapeuticRange, uiSettings);

  // Validate range inputs
  React.useEffect(() => {
    // Therapeutic range validation (blocking error)
    const minTherapeutic = parseFloat(therapeuticRange.min);
    const maxTherapeutic = parseFloat(therapeuticRange.max);
    if (!isNaN(minTherapeutic) && !isNaN(maxTherapeutic) && minTherapeutic >= maxTherapeutic) {
      setTherapeuticRangeError(t('errorTherapeuticRangeInvalid'));
    } else {
      setTherapeuticRangeError('');
    }

    // Y-axis range validation (non-blocking warning)
    const minYAxis = parseFloat(yAxisMin);
    const maxYAxis = parseFloat(yAxisMax);
    if (!isNaN(minYAxis) && !isNaN(maxYAxis) && minYAxis >= maxYAxis) {
      setYAxisRangeError(t('errorYAxisRangeInvalid'));
    } else {
      setYAxisRangeError('');
    }
  }, [therapeuticRange.min, therapeuticRange.max, yAxisMin, yAxisMax, t]);

  // Helper to update nested advanced settings
  const updateAdvanced = (category: string, key: string, value: any) => {
    onUpdatePkParams('advanced', {
      ...pkParams.advanced,
      [category]: {
        ...pkParams.advanced[category],
        [key]: value
      }
    });
  };

  const updateAdvancedDirect = (key: string, value: any) => {
    onUpdatePkParams('advanced', {
      ...pkParams.advanced,
      [key]: value
    });
  };

  // Check for out-of-range warnings
  const absorptionHL = parseFloat(pkParams.ldx.absorptionHalfLife);
  const conversionHL = parseFloat(pkParams.ldx.halfLife);
  const eliminationHL = parseFloat(pkParams.damph.halfLife);

  const absorptionWarning = (absorptionHL < 0.7 || absorptionHL > 1.2);
  const conversionWarning = (conversionHL < 0.7 || conversionHL > 1.2);
  const eliminationWarning = (eliminationHL < 9 || eliminationHL > 12);
  const eliminationExtreme = (eliminationHL < 7 || eliminationHL > 15);
  return (
    <div className="space-y-4">
      {/* Diagram Settings Card */}
      <Card>
        <CollapsibleCardHeader
          title={t('diagramSettings')}
          isCollapsed={!isDiagramExpanded}
          onToggle={() => updateDiagramExpanded(!isDiagramExpanded)}
        />
        {isDiagramExpanded && (
          <CardContent className="space-y-4">
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <Switch
                  id="showTemplateDay"
                  checked={showTemplateDay}
                  onCheckedChange={checked => onUpdateUiSetting('showTemplateDay', checked)}
                />
                <Label htmlFor="showTemplateDay" className="font-medium">
                  {t('showTemplateDayInChart')}
                </Label>
                  <Tooltip open={openTooltipId === 'showTemplateDay'} onOpenChange={(open) => setOpenTooltipId(open ? 'showTemplateDay' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('showTemplateDay')}
                        onTouchStart={handleTooltipToggle('showTemplateDay')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('showTemplateDayTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'showTemplateDayTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <Switch
                  id="showDayReferenceLines"
                  checked={showDayReferenceLines}
                  onCheckedChange={checked => onUpdateUiSetting('showDayReferenceLines', checked)}
                />
                <Label htmlFor="showDayReferenceLines" className="font-medium">
                  {t('showDayReferenceLines')}
                </Label>
                  <Tooltip open={openTooltipId === 'showDayReferenceLines'} onOpenChange={(open) => setOpenTooltipId(open ? 'showDayReferenceLines' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('showDayReferenceLines')}
                        onTouchStart={handleTooltipToggle('showDayReferenceLines')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('showDayReferenceLinesTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'showDayReferenceLinesTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <Switch
                  id="showTherapeuticRange"
                  checked={showTherapeuticRange}
                  onCheckedChange={checked => onUpdateUiSetting('showTherapeuticRange', checked)}
                />
                <Label htmlFor="showTherapeuticRange" className="font-medium">
                  {t('showTherapeuticRangeLines')}
                </Label>
                  <Tooltip open={openTooltipId === 'showTherapeuticRangeLines'} onOpenChange={(open) => setOpenTooltipId(open ? 'showTherapeuticRangeLines' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('showTherapeuticRangeLines')}
                        onTouchStart={handleTooltipToggle('showTherapeuticRangeLines')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('showTherapeuticRangeLinesTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'showTherapeuticRangeLinesTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              {showTherapeuticRange && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2">
                    <Label className="font-medium">
                      {t('therapeuticRange')}
                    </Label>
                      <Tooltip open={openTooltipId === 'therapeuticRange'} onOpenChange={(open) => setOpenTooltipId(open ? 'therapeuticRange' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('therapeuticRange')}
                        onTouchStart={handleTooltipToggle('therapeuticRange')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('therapeuticRangeTooltip')}
                      >
                            <Info className="h-4 w-4" />
                          </button>
                        </TooltipTrigger>
                        <TooltipContent side={tooltipSide}>
                          <p className="text-xs max-w-xs">{tWithDefaults(t, 'therapeuticRangeTooltip', defaultsForT)}</p>
                        </TooltipContent>
                      </Tooltip>
                  </div>
                  <div className="flex flex-wrap items-center gap-2">
                    <FormNumericInput
                      value={therapeuticRange.min}
                      onChange={val => onUpdateTherapeuticRange('min', val)}
                      increment={0.5}
                      min={0}
                      max={500}
                      placeholder={t('min')}
                      required={true}
                      error={!!therapeuticRangeError || !therapeuticRange.min}
                      errorMessage={therapeuticRangeError || t('errorTherapeuticRangeMinRequired') || 'Minimum therapeutic range is required'}
                      showResetButton={true}
                      defaultValue={defaultsForT.therapeuticRangeMin}
                    />
                    <span className="text-muted-foreground">-</span>
                    <FormNumericInput
                      value={therapeuticRange.max}
                      onChange={val => onUpdateTherapeuticRange('max', val)}
                      increment={0.5}
                      min={0}
                      max={500}
                      placeholder={t('max')}
                      unit="ng/ml"
                      required={true}
                      error={!!therapeuticRangeError || !therapeuticRange.max}
                      errorMessage={therapeuticRangeError || t('errorTherapeuticRangeMaxRequired') || 'Maximum therapeutic range is required'}
                      showResetButton={true}
                      defaultValue={defaultsForT.therapeuticRangeMax}
                    />
                  </div>
                </div>
              )}
            </div>

            <Separator className="my-4" />

            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Label className="font-medium">{t('displayedDays')}</Label>
                  <Tooltip open={openTooltipId === 'displayedDays'} onOpenChange={(open) => setOpenTooltipId(open ? 'displayedDays' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('displayedDays')}
                        onTouchStart={handleTooltipToggle('displayedDays')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('displayedDaysTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'displayedDaysTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              <FormNumericInput
                value={displayedDays}
                onChange={val => onUpdateUiSetting('displayedDays', val)}
                increment={1}
                min={1}
                max={parseInt(simulationDays, 10) || 3}
                unit={t('unitDays')}
                required={true}
                errorMessage={t('errorNumberRequired')}
                showResetButton={true}
                defaultValue={defaultsForT.displayedDays}
              />
            </div>

            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Label className="font-medium">{t('yAxisRange')}</Label>
                  <Tooltip open={openTooltipId === 'yAxisRange'} onOpenChange={(open) => setOpenTooltipId(open ? 'yAxisRange' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('yAxisRange')}
                        onTouchStart={handleTooltipToggle('yAxisRange')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('yAxisRangeTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'yAxisRangeTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <FormNumericInput
                  value={yAxisMin}
                  onChange={val => onUpdateUiSetting('yAxisMin', val)}
                  increment={1}
                  min={0}
                  max={500}
                  placeholder={t('auto')}
                  allowEmpty={true}
                  showResetButton={true}
                  defaultValue={defaultsForT.yAxisMin}
                  warning={!!yAxisRangeError}
                  warningMessage={yAxisRangeError}
                />
                <span className="text-muted-foreground">-</span>
                <FormNumericInput
                  value={yAxisMax}
                  onChange={val => onUpdateUiSetting('yAxisMax', val)}
                  increment={1}
                  min={0}
                  max={500}
                  placeholder={t('auto')}
                  unit="ng/ml"
                  allowEmpty={true}
                  showResetButton={true}
                  defaultValue={defaultsForT.yAxisMax}
                  warning={!!yAxisRangeError}
                  warningMessage={yAxisRangeError}
                />
              </div>
            </div>

            <Separator className="my-4" />

            <div className="space-y-2">
              <Label className="font-medium">{t('xAxisTimeFormat')}</Label>
                <Select
                  value={showDayTimeOnXAxis}
                  onValueChange={value => onUpdateUiSetting('showDayTimeOnXAxis', value)}
                >
                  <SelectTrigger className="w-[360px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <SelectItem value="continuous">
                          {t('xAxisFormatContinuous')}
                        </SelectItem>
                      </TooltipTrigger>
                      <TooltipContent side={tooltipSide}>
                        <p className="text-xs">{t('xAxisFormatContinuousDesc')}</p>
                      </TooltipContent>
                    </Tooltip>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <SelectItem value="24h">
                          {t('xAxisFormat24h')}
                        </SelectItem>
                      </TooltipTrigger>
                      <TooltipContent side={tooltipSide}>
                        <p className="text-xs">{t('xAxisFormat24hDesc')}</p>
                      </TooltipContent>
                    </Tooltip>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <SelectItem value="12h">
                          {t('xAxisFormat12h')}
                        </SelectItem>
                      </TooltipTrigger>
                      <TooltipContent side={tooltipSide}>
                        <p className="text-xs">{t('xAxisFormat12hDesc')}</p>
                      </TooltipContent>
                    </Tooltip>
                  </SelectContent>
                </Select>
            </div>
          </CardContent>
        )}
      </Card>

      {/* Simulation Settings Card */}
      <Card>
        <CollapsibleCardHeader
          title={t('simulationSettings')}
          isCollapsed={!isSimulationExpanded}
          onToggle={() => updateSimulationExpanded(!isSimulationExpanded)}
        />
        {isSimulationExpanded && (
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Label className="font-medium">{t('simulationDuration')}</Label>
                  <Tooltip open={openTooltipId === 'simulationDuration'} onOpenChange={(open) => setOpenTooltipId(open ? 'simulationDuration' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('simulationDuration')}
                        onTouchStart={handleTooltipToggle('simulationDuration')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('simulationDurationTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'simulationDurationTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              <FormNumericInput
                value={simulationDays}
                onChange={val => onUpdateUiSetting('simulationDays', val)}
                increment={1}
                min={3}
                max={7}
                unit={t('unitDays')}
                required={true}
                errorMessage={t('errorNumberRequired')}
                showResetButton={true}
                defaultValue={defaultsForT.simulationDays}
              />
            </div>

            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <Switch
                  id="steadyStateDaysEnabled"
                  checked={steadyStateDaysEnabled}
                  onCheckedChange={checked => {
                    onUpdateUiSetting('steadyStateDaysEnabled', checked);
                    // When toggling off, set steadyStateDays to '0'
                    if (!checked) {
                      updateAdvancedDirect('steadyStateDays', '0');
                    } else {
                      // When toggling on, set to default 7 if it's currently 0
                      if (pkParams.advanced.steadyStateDays === '0') {
                        updateAdvancedDirect('steadyStateDays', '7');
                      }
                    }
                  }}
                />
                <Label htmlFor="steadyStateDaysEnabled" className="font-medium">
                  {t('steadyStateDays')}
                </Label>
                  <Tooltip open={openTooltipId === 'steadyStateDays'} onOpenChange={(open) => setOpenTooltipId(open ? 'steadyStateDays' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('steadyStateDays')}
                        onTouchStart={handleTooltipToggle('steadyStateDays')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('steadyStateDaysTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'steadyStateDaysTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              {steadyStateDaysEnabled && (
                <div className="space-y-2">
                  <FormNumericInput
                    value={pkParams.advanced.steadyStateDays}
                    onChange={val => updateAdvancedDirect('steadyStateDays', val)}
                    increment={1}
                    min={0}
                    max={7}
                    unit={t('unitDays')}
                    required={true}
                    showResetButton={true}
                    defaultValue={defaultsForT.steadyStateDays}
                  />
                </div>
              )}
            </div>
          </CardContent>
        )}
      </Card>

      {/* Pharmacokinetic Settings Card */}
      <Card>
        <CollapsibleCardHeader
          title={t('pharmacokineticsSettings')}
          isCollapsed={!isPharmacokineticExpanded}
          onToggle={() => updatePharmacokineticExpanded(!isPharmacokineticExpanded)}
        />
        {isPharmacokineticExpanded && (
          <CardContent className="space-y-4">
            <h3 className="text-lg font-semibold">{t('dAmphetamineParameters')}</h3>
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Label className="font-medium">{t('halfLife')}</Label>
                  <Tooltip open={openTooltipId === 'halfLife'} onOpenChange={(open) => setOpenTooltipId(open ? 'halfLife' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('halfLife')}
                        onTouchStart={handleTooltipToggle('halfLife')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('halfLifeTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{renderTooltipWithLinks(tWithDefaults(t, 'halfLifeTooltip', defaultsForT))}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              <FormNumericInput
                value={pkParams.damph.halfLife}
                onChange={val => onUpdatePkParams('damph', { ...pkParams.damph, halfLife: val })}
                increment={0.5}
                min={5}
                max={50}
                unit="h"
                required={true}
                warning={eliminationWarning && !eliminationExtreme}
                error={eliminationExtreme}
                warningMessage={t('warningEliminationOutOfRange')}
                errorMessage={t('errorEliminationHalfLifeRequired')}
                showResetButton={true}
                defaultValue={defaultsForT.damphHalfLife}
              />
            </div>

            <Separator className="my-4" />

            <h3 className="text-lg font-semibold">{t('lisdexamfetamineParameters')}</h3>
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Label className="font-medium">{t('conversionHalfLife')}</Label>
                  <Tooltip open={openTooltipId === 'conversionHalfLife'} onOpenChange={(open) => setOpenTooltipId(open ? 'conversionHalfLife' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('conversionHalfLife')}
                        onTouchStart={handleTooltipToggle('conversionHalfLife')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('conversionHalfLifeTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'conversionHalfLifeTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              <FormNumericInput
                value={pkParams.ldx.halfLife}
                onChange={val => onUpdatePkParams('ldx', { ...pkParams.ldx, halfLife: val })}
                increment={0.1}
                min={0.5}
                max={5}
                unit="h"
                required={true}
                warning={conversionWarning}
                warningMessage={t('warningConversionOutOfRange')}
                errorMessage={t('errorConversionHalfLifeRequired')}
                showResetButton={true}
                defaultValue={defaultsForT.ldxHalfLife}
              />
            </div>

            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Label className="font-medium">{t('absorptionHalfLife')}</Label>
                  <Tooltip open={openTooltipId === 'absorptionHalfLife'} onOpenChange={(open) => setOpenTooltipId(open ? 'absorptionHalfLife' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('absorptionHalfLife')}
                        onTouchStart={handleTooltipToggle('absorptionHalfLife')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('absorptionHalfLifeTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'absorptionHalfLifeTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              <FormNumericInput
                value={pkParams.ldx.absorptionHalfLife}
                onChange={val => onUpdatePkParams('ldx', { ...pkParams.ldx, absorptionHalfLife: val })}
                increment={0.1}
                min={0.5}
                max={5}
                unit="h"
                required={true}
                warning={absorptionWarning}
                warningMessage={t('warningAbsorptionOutOfRange')}
                errorMessage={t('errorAbsorptionRateRequired')}
                showResetButton={true}
                defaultValue={defaultsForT.ldxAbsorptionHalfLife}
              />
            </div>
          </CardContent>
        )}
      </Card>

      {/* Advanced Settings Card */}
      <Card>
        <CollapsibleCardHeader
          title={t('advancedSettings')}
          isCollapsed={!isAdvancedExpanded}
          onToggle={() => updateAdvancedExpanded(!isAdvancedExpanded)}
        />
        {isAdvancedExpanded && (
          <CardContent className="space-y-4">
            <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md p-3 text-sm">
              <p className="text-yellow-800 dark:text-yellow-200">{t('advancedSettingsWarning')}</p>
            </div>

            {/* Standard Volume of Distribution */}
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <Label className="text-sm font-medium">{t('standardVolumeOfDistribution')}</Label>
                <Tooltip open={openTooltipId === 'standardVd'} onOpenChange={(open) => setOpenTooltipId(open ? 'standardVd' : null)}>
                  <TooltipTrigger asChild>
                    <button
                      type="button"
                      onClick={handleTooltipToggle('standardVd')}
                      onTouchStart={handleTooltipToggle('standardVd')}
                      className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                      aria-label={t('standardVdTooltip')}
                    >
                      <Info className="h-4 w-4" />
                    </button>
                  </TooltipTrigger>
                  <TooltipContent side={tooltipSide}>
                    <p className="text-xs max-w-xs">{renderTooltipWithLinks(tWithDefaults(t, 'standardVdTooltip', {
                      ...defaultsForT,
                      standardVdValue: pkParams.advanced.standardVd?.preset === 'adult' ? '377' : pkParams.advanced.standardVd?.preset === 'child' ? '175' : pkParams.advanced.standardVd?.customValue || '377',
                      standardVdPreset: t(`standardVdPreset${pkParams.advanced.standardVd?.preset?.charAt(0).toUpperCase()}${pkParams.advanced.standardVd?.preset?.slice(1)}` || 'standardVdPresetAdult')
                    }))}</p>
                  </TooltipContent>
                </Tooltip>
              </div>
              <Select
                value={pkParams.advanced.standardVd?.preset || 'adult'}
                onValueChange={(value: 'adult' | 'child' | 'custom' | 'weight-based') => updateAdvanced('standardVd', 'preset', value)}
              >
                <SelectTrigger className="w-[360px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="adult">{t('standardVdPresetAdult')}</SelectItem>
                  <SelectItem value="child">{t('standardVdPresetChild')}</SelectItem>
                  <SelectItem value="custom">{t('standardVdPresetCustom')}</SelectItem>
                  <SelectItem value="weight-based">{t('standardVdPresetWeightBased')}</SelectItem>
                </SelectContent>
              </Select>
              {pkParams.advanced.standardVd?.preset === 'weight-based' && (
                <div className="ml-0 mt-2 p-2 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded text-xs text-blue-800 dark:text-blue-200">
                  ⓘ {t('weightBasedVdInfo')}
                </div>
              )}
              {pkParams.advanced.standardVd?.preset === 'custom' && (
                <div className="mt-2">
                  <Label className="text-sm font-medium">{t('customVdValue')}</Label>
                  <FormNumericInput
                    value={pkParams.advanced.standardVd?.customValue || '377'}
                    onChange={val => updateAdvanced('standardVd', 'customValue', val)}
                    increment={10}
                    min={50}
                    max={2000}
                    unit="L"
                    required={true}
                    showResetButton={true}
                    defaultValue={defaultsForT.customVdValue}
                  />
                </div>
              )}
              {pkParams.advanced.standardVd?.preset === 'weight-based' && (
                <div className="mt-2">
                  <div className="flex items-center gap-2">
                    <Label className="text-sm font-medium">{t('bodyWeight')}</Label>
                    <Tooltip open={openTooltipId === 'bodyWeight'} onOpenChange={(open) => setOpenTooltipId(open ? 'bodyWeight' : null)}>
                      <TooltipTrigger asChild>
                        <button
                          type="button"
                          onClick={handleTooltipToggle('bodyWeight')}
                          onTouchStart={handleTooltipToggle('bodyWeight')}
                          className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                          aria-label={t('bodyWeightTooltip')}
                        >
                          <Info className="h-4 w-4" />
                        </button>
                      </TooltipTrigger>
                      <TooltipContent side={tooltipSide}>
                        <p className="text-xs max-w-xs">{renderTooltipWithLinks(tWithDefaults(t, 'bodyWeightTooltip', defaultsForT))}</p>
                      </TooltipContent>
                    </Tooltip>
                  </div>
                  <FormNumericInput
                    value={pkParams.advanced.standardVd?.bodyWeight || '70'}
                    onChange={val => updateAdvanced('standardVd', 'bodyWeight', val)}
                    increment={1}
                    min={20}
                    max={300}
                    unit={t('bodyWeightUnit')}
                    required={true}
                    showResetButton={true}
                    defaultValue={defaultsForT.bodyWeight}
                  />
                </div>
              )}
            </div>

            <Separator className="my-4" />

            {/* Food Effect Absorption Delay */}
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <Label className="text-sm font-medium">{t('foodEffectDelay')}</Label>
                <Tooltip open={openTooltipId === 'tmaxDelay'} onOpenChange={(open) => setOpenTooltipId(open ? 'tmaxDelay' : null)}>
                  <TooltipTrigger asChild>
                    <button
                      type="button"
                      onClick={handleTooltipToggle('tmaxDelay')}
                      onTouchStart={handleTooltipToggle('tmaxDelay')}
                      className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                      aria-label={t('tmaxDelayTooltip')}
                    >
                      <Info className="h-4 w-4" />
                    </button>
                  </TooltipTrigger>
                  <TooltipContent side={tooltipSide}>
                    <p className="text-xs max-w-xs">{renderTooltipWithLinks(tWithDefaults(t, 'tmaxDelayTooltip', defaultsForT))}</p>
                  </TooltipContent>
                </Tooltip>
              </div>
              <FormNumericInput
                value={pkParams.advanced.foodEffect.tmaxDelay}
                onChange={val => updateAdvanced('foodEffect', 'tmaxDelay', val)}
                increment={0.1}
                min={0}
                max={5}
                unit={t('tmaxDelayUnit')}
                required={true}
                showResetButton={true}
                defaultValue={defaultsForT.tmaxDelay}
              />
            </div>

            <Separator className="my-4" />

            {/* Urine pH */}
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <Label htmlFor="urinePHMode" className="font-medium">
                  {t('urinePHTendency')}
                </Label>
                  <Tooltip open={openTooltipId === 'urinePH'} onOpenChange={(open) => setOpenTooltipId(open ? 'urinePH' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('urinePH')}
                        onTouchStart={handleTooltipToggle('urinePH')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('urinePHTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{tWithDefaults(t, 'urinePHTooltip', defaultsForT)}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              <div>
                <Select
                  value={pkParams.advanced.urinePh.mode}
                  onValueChange={(value: 'normal' | 'acidic' | 'alkaline') =>
                    updateAdvanced('urinePh', 'mode', value)
                  }
                >
                  <SelectTrigger id="urinePHMode" className="w-[360px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="normal">{t('urinePHModeNormal')}</SelectItem>
                    <SelectItem value="acidic">{t('urinePHModeAcidic')}</SelectItem>
                    <SelectItem value="alkaline">{t('urinePHModeAlkaline')}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <Separator className="my-4" />

            {/* Age Group Selection */}
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <Label className="text-sm font-medium">{t('ageGroup')}</Label>
                <Tooltip open={openTooltipId === 'ageGroup'} onOpenChange={(open) => setOpenTooltipId(open ? 'ageGroup' : null)}>
                  <TooltipTrigger asChild>
                    <button
                      type="button"
                      onClick={handleTooltipToggle('ageGroup')}
                      onTouchStart={handleTooltipToggle('ageGroup')}
                      className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                      aria-label={t('ageGroupTooltip')}
                    >
                      <Info className="h-4 w-4" />
                    </button>
                  </TooltipTrigger>
                  <TooltipContent side={tooltipSide}>
                    <p className="text-xs max-w-xs">{renderTooltipWithLinks(tWithDefaults(t, 'ageGroupTooltip', defaultsForT))}</p>
                  </TooltipContent>
                </Tooltip>
              </div>
              <Select
                value={pkParams.advanced.ageGroup?.preset || 'adult'}
                onValueChange={(value: 'child' | 'adult' | 'custom') => {
                  updateAdvancedDirect('ageGroup', { preset: value });
                }}
              >
                <SelectTrigger className="w-[360px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="adult">{t('ageGroupAdult')}</SelectItem>
                  <SelectItem value="child">{t('ageGroupChild')}</SelectItem>
                  <SelectItem value="custom">{t('ageGroupCustom')}</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <Separator className="my-4" />

            {/* Renal Function */}
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <Switch
                  id="renalFunctionEnabled"
                  checked={pkParams.advanced.renalFunction?.enabled || false}
                  onCheckedChange={checked => {
                    updateAdvancedDirect('renalFunction', {
                      enabled: checked,
                      severity: pkParams.advanced.renalFunction?.severity || 'normal'
                    });
                  }}
                />
                <Label htmlFor="renalFunctionEnabled" className="font-medium">
                  {t('renalFunction')}
                </Label>
                <Tooltip open={openTooltipId === 'renalFunction'} onOpenChange={(open) => setOpenTooltipId(open ? 'renalFunction' : null)}>
                  <TooltipTrigger asChild>
                    <button
                      type="button"
                      onClick={handleTooltipToggle('renalFunction')}
                      onTouchStart={handleTooltipToggle('renalFunction')}
                      className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                      aria-label={t('renalFunctionTooltip')}
                    >
                      <Info className="h-4 w-4" />
                    </button>
                  </TooltipTrigger>
                  <TooltipContent side={tooltipSide}>
                    <p className="text-xs max-w-xs">{renderTooltipWithLinks(tWithDefaults(t, 'renalFunctionTooltip', defaultsForT))}</p>
                  </TooltipContent>
                </Tooltip>
              </div>
              {(pkParams.advanced.renalFunction?.enabled) && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2">
                    <Label className="text-sm font-medium">{t('renalFunctionSeverity')}</Label>
                  </div>
                  <Select
                    value={pkParams.advanced.renalFunction?.severity || 'normal'}
                    onValueChange={(value: 'normal' | 'mild' | 'severe') => {
                      updateAdvancedDirect('renalFunction', {
                        enabled: true,
                        severity: value
                      });
                    }}
                  >
                    <SelectTrigger className="w-full">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="normal">{t('renalFunctionNormal')}</SelectItem>
                      <SelectItem value="mild">{t('renalFunctionMild')}</SelectItem>
                      <SelectItem value="severe">{t('renalFunctionSevere')}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              )}
            </div>

            <Separator className="my-4" />

            {/* Oral Bioavailability */}
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Label className="font-medium">{t('oralBioavailability')}</Label>
                  <Tooltip open={openTooltipId === 'oralBioavailability'} onOpenChange={(open) => setOpenTooltipId(open ? 'oralBioavailability' : null)}>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={handleTooltipToggle('oralBioavailability')}
                        onTouchStart={handleTooltipToggle('oralBioavailability')}
                        className="inline-flex items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                        aria-label={t('oralBioavailabilityTooltip')}
                      >
                        <Info className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side={tooltipSide}>
                      <p className="text-xs max-w-xs">{renderTooltipWithLinks(tWithDefaults(t, 'oralBioavailabilityTooltip', defaultsForT))}</p>
                    </TooltipContent>
                  </Tooltip>
              </div>
              <FormNumericInput
                value={pkParams.advanced.fOral}
                onChange={val => updateAdvancedDirect('fOral', val)}
                increment={0.01}
                min={0.5}
                max={1.0}
                required={true}
                showResetButton={true}
                defaultValue={defaultsForT.fOral}
              />
            </div>
          </CardContent>
        )}
      </Card>

      {/* Data Management Button */}
      <Button
        type="button"
        onClick={onOpenDataManagement}
        variant="outline"
        className="w-full"
      >
        {t('openDataManagement')}
      </Button>
    </div>
  );
};

export default Settings;
