import { Alert, Modal, ScrollView, Switch, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { useEffect, useRef, useState } from 'react';
import { useApp } from '../context/AppContext';
import { useAuth } from '../context/AuthContext';
import styles from '../styles/index';
import { hexToRgb } from '../utils/helpers';

export function SettingsModal() {
  const [lowStockThresholdInput, setLowStockThresholdInput] = useState('');
  const [staffPinCodes, setStaffPinCodes] = useState({});
  const [warehouseNameInput, setWarehouseNameInput] = useState('');
  const [quickPickNoticeVisible, setQuickPickNoticeVisible] = useState(false);
  const quickPickNoticeTimer = useRef(null);

  const {
    settingsVisible,
    setSettingsVisible,
    settingsTab,
    setSettingsTab,
    masterSettings,
    updateMasterSetting,
    themeColor,
    setColorPickerVisible,
    setTempR,
    setTempG,
    setTempB,
    isMasterUser,
    shippingProviders,
    cmsProviders,
    selectedShipProvider,
    setSelectedShipProvider,
    selectedEcomProvider,
    setSelectedEcomProvider,
    showProviderInputs,
    setShowProviderInputs,
    activeShippingConfig,
    activeEcommerceConfig,
    activeShippingDefs,
    activeEcommerceDefs,
    hasShippingSecret,
    hasEcommerceSecret,
    getProviderInput,
    setProviderInput,
    isSensitiveProviderField,
    saveProviderConfig,
    fetchProviders,
    forceUpdateCourier,
    forceUpdatingCourier,
    packageMappingVisible,
    setPackageMappingVisible,
    packageMappingProvider,
    packageStockOptions,
    packageMappingLoading,
    packageMappingSaving,
    fetchPackageMapping,
    setPackageStockSetting,
    savePackageMapping,
    isScanningPrinters,
    discoveredPrinters,
    scanForNetworkPrinters,
    printLocalTestLabel,
    previewLocalTestLabel,
    staffList,
    staffDirty,
    setStaffDirty,
    setStaffList,
    newStaffName,
    setNewStaffName,
    secondaryPassword,
    setSecondaryPassword,
    addStaff,
    deleteStaff,
    saveStaffChanges,
    saveSecondaryPassword,
  } = useApp();
  const { authCompany, handleSessionExpired, securityMode, setSecurityMode } = useAuth();
  const isPackieStockMapping = String(packageMappingProvider || selectedShipProvider || '').toLowerCase() === 'packie';
  const defaultWarehouseName = String(authCompany || '').trim()
    .replace(/[-_]+/g, ' ')
    .replace(/\b\w/g, c => c.toUpperCase());

  const saveSecurityMode = async (value) => {
    setSecurityMode(value);
    await updateMasterSetting('securityMode', value);
  };

  const openSettingsTab = (tabId) => {
    if ((tabId === 'printing' || tabId === 'courier' || tabId === 'ecommerce') && !isMasterUser) {
      Alert.alert('Settings', 'Sign in as Admin to view printing, courier and ecommerce settings.');
      return;
    }
    setSettingsTab(tabId);
  };

  useEffect(() => () => {
    if (quickPickNoticeTimer.current) clearTimeout(quickPickNoticeTimer.current);
  }, []);

  useEffect(() => {
    if (settingsVisible) {
      setWarehouseNameInput(String(masterSettings.warehouseDisplayName || ''));
    }
  }, [masterSettings.warehouseDisplayName, settingsVisible]);

  const showQuickPickNotice = () => {
    setQuickPickNoticeVisible(true);
    if (quickPickNoticeTimer.current) clearTimeout(quickPickNoticeTimer.current);
    quickPickNoticeTimer.current = setTimeout(() => {
      setQuickPickNoticeVisible(false);
      quickPickNoticeTimer.current = null;
    }, 3000);
  };

  const setQuickPickEnabled = (option, value) => {
    setPackageStockSetting(option.id, { quick_pick_enabled: value });
    if (value && !option.quick_pick_enabled) showQuickPickNotice();
  };

  const setQuickPickDefault = (option) => {
    setPackageStockSetting(option.id, { quick_pick_enabled: true, quick_pick_is_default: true });
    if (!option.quick_pick_enabled) showQuickPickNotice();
  };

  const settingsTabs = [
    ['general', 'General'],
    ['users', 'Users'],
    ...(isMasterUser ? [['printing', 'Printing'], ['courier', 'Courier'], ['ecommerce', 'Ecommerce']] : []),
  ];

  const visiblePrinterDrivers = ['direct', 'brother'];
  const showAdvancedPrinterDrivers = !!masterSettings.showAdvancedPrinterDrivers || !visiblePrinterDrivers.includes(masterSettings.localPrinterDriver);
  const printerDriverOptions = showAdvancedPrinterDrivers
    ? [['direct', 'DIRECT'], ['brother', 'BROTHER'], ['zpl', 'ZPL'], ['raw', 'RAW'], ['system', 'SYSTEM']]
    : [['direct', 'DIRECT'], ['brother', 'BROTHER QL']];
  const activeShippingUsername = activeShippingConfig.username
    || activeShippingConfig.UserName
    || activeShippingConfig.user_name
    || activeShippingConfig.shipping_username
    || activeShippingDefs.reduce((found, f, idx) => {
      if (found) return found;
      const key = String(f?.key || '').toLowerCase();
      const label = String(f?.label || '').toLowerCase();
      if (key.includes('user') || label.includes('user')) {
        return getProviderInput('shipping', selectedShipProvider, idx);
      }
      return '';
    }, '');

  return (
    <Modal visible={settingsVisible} transparent animationType="fade">
      <View style={styles.modalOverlay}>
        <View style={[styles.modalContent, { maxHeight: '90%', width: '100%' }]}>
          {quickPickNoticeVisible && (
            <View
              pointerEvents="none"
              style={{
                position: 'absolute',
                top: 8,
                left: 12,
                right: 12,
                zIndex: 20,
                borderRadius: 8,
                paddingVertical: 10,
                paddingHorizontal: 12,
                backgroundColor: '#fff7ed',
                borderWidth: 1,
                borderColor: '#fed7aa',
                shadowColor: '#000',
                shadowOpacity: 0.16,
                shadowRadius: 8,
                elevation: 4,
              }}
            >
              <Text style={{ color: '#9a3412', fontWeight: '900', fontSize: 13, textAlign: 'center' }}>
                Quick Print skips live prices. Use it only when the price is already known.
              </Text>
            </View>
          )}
          <Text style={{ fontSize: 22, fontWeight: 'bold', marginBottom: 12, textAlign: 'center' }}>Settings</Text>

          <View style={{ flexDirection: 'row', marginBottom: 12, justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <View style={{ flexDirection: 'row', gap: 8, flex: 1, flexWrap: 'wrap', marginRight: 8 }}>
              {settingsTabs.map(([id, label]) => (
                <TouchableOpacity
                  key={id}
                  onPress={() => openSettingsTab(id)}
                  style={{
                    paddingVertical: 8,
                    paddingHorizontal: 12,
                    borderRadius: 8,
                    backgroundColor: settingsTab === id ? themeColor : '#f2f2f2',
                  }}
                >
                  <Text style={{ color: settingsTab === id ? '#fff' : '#333', fontWeight: '700' }}>{label}</Text>
                </TouchableOpacity>
              ))}
            </View>
            <TouchableOpacity
              onPress={() => { setSettingsVisible(false); }}
              hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
              style={{ minWidth: 32, minHeight: 32, alignItems: 'center', justifyContent: 'center' }}
            >
              <Text style={{ fontWeight: '700', color: '#666' }}>✕</Text>
            </TouchableOpacity>
          </View>

          <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={{ paddingBottom: 100 }}>

            {/* GENERAL TAB */}
            {settingsTab === 'general' && (
              <View>
                {[
                  ['allowAddressEditing', 'Enable address editing'],
                  ['enableScanner', 'Enable scanner'],
                  ['showProductImages', 'Show product images'],
                  ['showRuralWarning', 'Show rural warning'],
                  ['showInternationalWarning', 'Show AU export warning'],
                  ['showDoubleOrderWarning', 'Show double order warning'],
                  ['enableScanSounds', 'Enable scan sounds (vibration)'],
                  ['showLowStockWarning', 'Show low stock warning'],
                  ['missingItemsCheck', 'Missing items check'],
                ].map(([key, label]) => (
                  <View key={key} style={styles.settingRow}>
                    <Text style={styles.settingLabel}>{label}</Text>
                    <Switch
                      value={!!masterSettings[key]}
                      onValueChange={value => updateMasterSetting(key, value)}
                    />
                  </View>
                ))}

                {masterSettings.showLowStockWarning && (
                  <View style={styles.settingRow}>
                    <Text style={styles.settingLabel}>Low Stock Threshold</Text>
                    <TextInput
                      style={[styles.obInput, { width: 80, textAlign: 'center' }]}
                      value={lowStockThresholdInput === '' ? String(masterSettings.lowStockThreshold ?? 5) : lowStockThresholdInput}
                      onChangeText={setLowStockThresholdInput}
                      onFocus={() => { setLowStockThresholdInput(''); }}
                      onBlur={() => {
                        const val = parseInt(lowStockThresholdInput) || 5;
                        updateMasterSetting('lowStockThreshold', val);
                      }}
                      keyboardType="number-pad"
                      returnKeyType="done"
                      onSubmitEditing={() => {
                        const val = parseInt(lowStockThresholdInput) || 5;
                        updateMasterSetting('lowStockThreshold', val);
                      }}
                    />
                  </View>
                )}

                <View style={styles.settingRow}>
                  <Text style={styles.settingLabel}>Theme Color</Text>
                  <TouchableOpacity
                    style={[styles.colorPreview, { backgroundColor: masterSettings.themeColor }]}
                    onPress={() => {
                      const rgb = hexToRgb(masterSettings.themeColor);
                      if (rgb) {
                        setTempR(rgb.r);
                        setTempG(rgb.g);
                        setTempB(rgb.b);
                      }
                      setColorPickerVisible(true);
                    }}
                  />
                </View>

                {isMasterUser && (
                  <View style={{ marginTop: 12, backgroundColor: '#f7f9fb', borderWidth: 1, borderColor: '#e7edf2', borderRadius: 10, padding: 12 }}>
                    <Text style={{ fontWeight: '800', color: '#334', marginBottom: 6 }}>Warehouse display name</Text>
                    <TextInput
                      style={[styles.obInput, { marginBottom: 8 }]}
                      value={warehouseNameInput}
                      placeholder={defaultWarehouseName || 'Warehouse'}
                      onChangeText={setWarehouseNameInput}
                      autoCorrect={false}
                    />
                    <Text style={{ color: '#667', fontSize: 12, marginBottom: 8 }}>
                      Leave blank to use {defaultWarehouseName || 'the company slug'}.
                    </Text>
                    <TouchableOpacity
                      style={[styles.packBtn, { backgroundColor: themeColor }]}
                      onPress={() => updateMasterSetting('warehouseDisplayName', warehouseNameInput.trim())}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>SAVE WAREHOUSE NAME</Text>
                    </TouchableOpacity>
                  </View>
                )}
              </View>
            )}

            {/* PRINTING TAB */}
            {settingsTab === 'printing' && isMasterUser && (
              <View>
                <View style={styles.settingRow}>
                  <Text style={styles.settingLabel}>Allow RD printing</Text>
                  <Switch
                    value={!!masterSettings.allowRdPrinting}
                    onValueChange={value => updateMasterSetting('allowRdPrinting', value)}
                  />
                </View>

                <View style={{ marginTop: 12, backgroundColor: '#f7f9fb', borderWidth: 1, borderColor: '#e7edf2', borderRadius: 10, padding: 12 }}>
                  <Text style={{ fontWeight: '800', color: '#334', marginBottom: 8 }}>Printing Settings Mode</Text>
                  <View style={{ flexDirection: 'row', gap: 8, marginBottom: 8 }}>
                    {[
                      ['company', 'ALL DEVICES'],
                      ['per_device', 'PER DEVICE'],
                    ].map(([value, label]) => {
                      const active = (masterSettings.printSettingsMode || 'company') === value;
                      return (
                        <TouchableOpacity
                          key={value}
                          style={[styles.packBtn, { flex: 1, backgroundColor: active ? themeColor : '#95a5a6' }]}
                          onPress={() => updateMasterSetting('printSettingsMode', value)}
                        >
                          <Text style={{ color: '#fff', fontWeight: 'bold' }}>{label}</Text>
                        </TouchableOpacity>
                      );
                    })}
                  </View>
                  <Text style={{ color: '#667', fontSize: 12 }}>
                    {(masterSettings.printSettingsMode || 'company') === 'per_device'
                      ? 'This device keeps its own printer method, address, driver, and label type.'
                      : 'These printer settings are pushed to every device using this company login.'}
                  </Text>
                </View>

                <View style={{ marginTop: 12, marginBottom: 12, backgroundColor: '#f7f9fb', borderWidth: 1, borderColor: '#e7edf2', borderRadius: 10, padding: 12 }}>
                  <Text style={{ fontWeight: '800', color: '#334', marginBottom: 8 }}>Print Method</Text>
                  <View style={{ flexDirection: 'row', gap: 8, marginBottom: 10 }}>
                    <TouchableOpacity
                      style={[styles.packBtn, { flex: 1, backgroundColor: masterSettings.preferredPrintMethod === 'packie_app' ? themeColor : '#95a5a6' }]}
                      onPress={() => updateMasterSetting('preferredPrintMethod', 'packie_app')}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>PACKIE APP</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                      style={[styles.packBtn, { flex: 1, backgroundColor: masterSettings.preferredPrintMethod === 'local' ? themeColor : '#95a5a6' }]}
                      onPress={() => updateMasterSetting('preferredPrintMethod', 'local')}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>LOCAL PRINTER</Text>
                    </TouchableOpacity>
                  </View>

                  {masterSettings.preferredPrintMethod === 'local' && (
                    <>
                      <Text style={{ color: '#556', marginBottom: 6 }}>Printer IP / Hostname</Text>
                      <TextInput
                        style={[styles.obInput, { marginBottom: 8 }]}
                        value={String(masterSettings.printerIpAddress || masterSettings.localPrinterHostname || '')}
                        placeholder="e.g. 192.168.1.100 or BRN30055C6A440.local"
                        autoCapitalize="none"
                        autoCorrect={false}
                        onChangeText={t => {
                          updateMasterSetting('printerIpAddress', t);
                          updateMasterSetting('localPrinterHostname', t);
                        }}
                      />

                      {masterSettings.localPrinterDriver === 'direct' ? (
                        <Text style={{ color: '#889', fontSize: 12, marginBottom: 8 }}>
                          Direct printing uses raw socket port 9100.
                        </Text>
                      ) : (
                        <>
                          <Text style={{ color: '#556', marginBottom: 6 }}>Port</Text>
                          <TextInput
                            style={[styles.obInput, { marginBottom: 8 }]}
                            value={String(masterSettings.localPrinterPort || '9100')}
                            placeholder="9100"
                            keyboardType="numeric"
                            onChangeText={t => updateMasterSetting('localPrinterPort', t)}
                          />
                        </>
                      )}

                      <Text style={{ color: '#556', marginBottom: 6, fontWeight: '600' }}>Printer Protocol / Driver</Text>
                      <View style={{ flexDirection: 'row', gap: 8, marginBottom: 4 }}>
                        {printerDriverOptions.map(([val, label]) => (
                          <TouchableOpacity
                            key={val}
                            style={[styles.packBtn, { flex: 1, backgroundColor: masterSettings.localPrinterDriver === val ? '#1f7a8c' : '#95a5a6' }]}
                            onPress={() => updateMasterSetting('localPrinterDriver', val)}
                          >
                            <Text style={{ color: '#fff', fontWeight: 'bold' }}>{label}</Text>
                          </TouchableOpacity>
                        ))}
                      </View>
                      <Text style={{ color: '#889', fontSize: 11, marginBottom: 10 }}>
                        DIRECT is raw socket printing. BROTHER QL is for QL-1110NWB label printers.
                      </Text>
                      {showAdvancedPrinterDrivers && <Text style={{ color: '#889', fontSize: 11, marginBottom: 10 }}>
                        BROTHER = QL label printer (QL-1110NWB) • ZPL = Zebra • RAW = plain TCP • SYSTEM = Android print dialog
                      </Text>}

                      <View style={[styles.settingRow, { paddingVertical: 4, marginBottom: 8 }]}>
                        <Text style={[styles.settingLabel, { color: '#556' }]}>Show advanced printer drivers</Text>
                        <Switch
                          value={!!masterSettings.showAdvancedPrinterDrivers}
                          onValueChange={value => {
                            updateMasterSetting('showAdvancedPrinterDrivers', value);
                            if (!value) updateMasterSetting('localPrinterDriver', 'direct');
                          }}
                        />
                      </View>

                      {masterSettings.localPrinterDriver === 'direct' && (
                        <View style={{ marginBottom: 10 }}>
                          <Text style={{ color: '#556', marginBottom: 6, fontWeight: '600' }}>Printer Hardware</Text>
                          <View style={{ flexDirection: 'row', gap: 8, marginBottom: 4 }}>
                            {[['THERMAL', 'ZPL THERMAL'], ['LASER', 'PDF DIRECT LASER']].map(([val, label]) => (
                              <TouchableOpacity
                                key={val}
                                style={[styles.packBtn, { flex: 1, backgroundColor: String(masterSettings.printerType || 'THERMAL').toUpperCase() === val ? themeColor : '#95a5a6' }]}
                                onPress={() => updateMasterSetting('printerType', val)}
                              >
                                <Text style={{ color: '#fff', fontWeight: 'bold' }}>{label}</Text>
                              </TouchableOpacity>
                            ))}
                          </View>
                          <Text style={{ color: '#889', fontSize: 11 }}>
                            PDF Direct only works on printers that advertise PDF Direct/raw PDF support. Most lasers need PCL, PostScript, IPP, or the system print path.
                          </Text>
                        </View>
                      )}

                      {masterSettings.localPrinterDriver === 'brother' && (
                        <View style={{ marginBottom: 10 }}>
                          <Text style={{ color: '#556', marginBottom: 6, fontWeight: '600' }}>Brother Label Type</Text>
                          <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginBottom: 8 }}>
                            {[
                              ['DK-11247', 'DK-11247', '103x164'],
                              ['DK-11241', 'DK-11241', '102x152'],
                              ['W103', 'W103', 'continuous'],
                            ].map(([value, title, sub]) => {
                              const active = String(masterSettings.localPrinterLabelType || 'DK-11247').trim().toUpperCase() === value;
                              return (
                                <TouchableOpacity
                                  key={value}
                                  style={[
                                    styles.packBtn,
                                    {
                                      minWidth: 96,
                                      flexGrow: 1,
                                      backgroundColor: active ? themeColor : '#95a5a6',
                                      paddingVertical: 10,
                                    },
                                  ]}
                                  onPress={() => updateMasterSetting('localPrinterLabelType', value)}
                                >
                                  <Text style={{ color: '#fff', fontWeight: 'bold', textAlign: 'center' }}>{title}</Text>
                                  <Text style={{ color: '#fff', fontSize: 11, textAlign: 'center', opacity: 0.9 }}>{sub}</Text>
                                </TouchableOpacity>
                              );
                            })}
                          </View>
                          <TextInput
                            style={[styles.obInput, { marginBottom: 4 }]}
                            value={String(masterSettings.localPrinterLabelType || 'DK-11247')}
                            placeholder="DK-11247"
                            autoCapitalize="none"
                            autoCorrect={false}
                            onChangeText={t => updateMasterSetting('localPrinterLabelType', t)}
                          />
                          <Text style={{ color: '#889', fontSize: 11 }}>
                            W103 = 103mm continuous • DK-11241 = 102×152mm die-cut • DK-11247 = 103×164mm die-cut
                          </Text>
                        </View>
                      )}

                      <TouchableOpacity
                        style={[styles.packBtn, { backgroundColor: isScanningPrinters ? '#9ca3af' : '#007ace', marginBottom: 8 }]}
                        onPress={scanForNetworkPrinters}
                        disabled={isScanningPrinters}
                      >
                        <Text style={{ color: '#fff', fontWeight: 'bold' }}>
                          {isScanningPrinters ? 'SCANNING...' : 'SCAN FOR PRINTERS'}
                        </Text>
                      </TouchableOpacity>

                      <View style={{ flexDirection: 'row', gap: 8, marginBottom: 8 }}>
                        <TouchableOpacity
                          style={[styles.packBtn, { flex: 1, backgroundColor: '#16a085' }]}
                          onPress={printLocalTestLabel}
                        >
                          <Text style={{ color: '#fff', fontWeight: 'bold' }}>TEST PRINT LABEL</Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                          style={[styles.packBtn, { flex: 1, backgroundColor: '#8e44ad' }]}
                          onPress={() => {
                            setSettingsVisible(false);
                            previewLocalTestLabel();
                          }}
                        >
                          <Text style={{ color: '#fff', fontWeight: 'bold' }}>PREVIEW LABEL</Text>
                        </TouchableOpacity>
                      </View>

                      {discoveredPrinters.length > 0 && (
                        <View style={{ marginTop: 6 }}>
                          {discoveredPrinters.map((p, idx) => (
                            <TouchableOpacity
                              key={`${p.host}-${p.port}-${idx}`}
                              style={{ backgroundColor: '#eef4f7', borderRadius: 8, padding: 10, marginBottom: 8 }}
                              onPress={() => {
                                const selectedPort = masterSettings.localPrinterDriver === 'direct' ? '9100' : (p.port || '9100');
                                updateMasterSetting('printerIpAddress', p.host);
                                updateMasterSetting('localPrinterHostname', p.host);
                                updateMasterSetting('localPrinterPort', selectedPort);
                                Alert.alert('Printer Selected', `${p.name} (${p.host}:${selectedPort})`);
                              }}
                            >
                              <Text style={{ color: '#1f2d3d', fontWeight: '700' }}>{p.name}</Text>
                              <Text style={{ color: '#4b5c6b', marginTop: 2 }}>{p.host}:{p.port || '9100'}</Text>
                            </TouchableOpacity>
                          ))}
                        </View>
                      )}
                    </>
                  )}
                </View>
              </View>
            )}

            {/* USERS TAB */}
            {settingsTab === 'users' && (
              <View>
                <Text style={{ color: '#666', marginBottom: 10 }}>Manage staff members and permissions.</Text>

                {!isMasterUser ? (
                  <View style={{ backgroundColor: '#fff7e6', borderWidth: 1, borderColor: '#f3d08a', borderRadius: 10, padding: 12, marginBottom: 14 }}>
                    <Text style={{ color: '#7a5a00', fontWeight: '700' }}>Read-only access</Text>
                    <Text style={{ color: '#7a5a00', marginTop: 4 }}>
                      Sign in as Admin to add staff, change permissions, or edit shared passwords.
                    </Text>
                  </View>
                ) : null}

                {isMasterUser ? (
                  <View style={{ backgroundColor: '#f7f9fb', borderWidth: 1, borderColor: '#e7edf2', borderRadius: 10, padding: 12, marginBottom: 14 }}>
                    <Text style={{ fontSize: 12, fontWeight: '800', color: '#445', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>
                      Shared secondary login password
                    </Text>
                    <TextInput
                      style={[styles.dimInput, { textAlign: 'left', marginBottom: 10 }]}
                      placeholder="Set shared user password"
                      secureTextEntry
                      value={secondaryPassword}
                      onChangeText={setSecondaryPassword}
                      onSubmitEditing={saveSecondaryPassword}
                    />
                    <TouchableOpacity style={[styles.packBtn, { backgroundColor: themeColor }]} onPress={saveSecondaryPassword}>
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>SAVE SECONDARY PASSWORD</Text>
                    </TouchableOpacity>
                  </View>
                ) : null}

                {isMasterUser ? (
                  <View style={{ backgroundColor: '#f0f4f8', borderWidth: 1, borderColor: '#d1d9e6', borderRadius: 10, padding: 12, marginBottom: 14 }}>
                    <Text style={{ fontSize: 12, fontWeight: '800', color: '#445', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>
                      Global Security Mode
                    </Text>
                    <Text style={{ fontSize: 12, color: '#666', marginBottom: 10 }}>
                      Controls how workers access the device
                    </Text>
                    {[
                      ['master_only', 'Master Admin Only', 'Device runs with full master rights, no user switching'],
                      ['shared_honor', 'Shared Honor System', 'Simple roster selection without password verification'],
                      ['individual_pin', 'Individual PIN Codes', 'Name + 4-digit PIN required for each worker'],
                    ].map(([value, label, description]) => (
                      <TouchableOpacity
                        key={value}
                        style={{
                          flexDirection: 'row',
                          alignItems: 'flex-start',
                          padding: 10,
                          marginBottom: 8,
                          borderRadius: 8,
                          backgroundColor: securityMode === value ? '#e8f4fd' : '#fff',
                          borderWidth: 1,
                          borderColor: securityMode === value ? '#4a90d9' : '#d1d9e6',
                        }}
                        onPress={() => saveSecurityMode(value)}
                      >
                        <View style={{ marginRight: 10, marginTop: 2 }}>
                          <View style={{
                            width: 18,
                            height: 18,
                            borderRadius: 9,
                            borderWidth: 2,
                            borderColor: securityMode === value ? '#4a90d9' : '#ccc',
                            alignItems: 'center',
                            justifyContent: 'center',
                          }}>
                            {securityMode === value && (
                              <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: '#4a90d9' }} />
                            )}
                          </View>
                        </View>
                        <View style={{ flex: 1 }}>
                          <Text style={{ fontWeight: '700', color: '#333', fontSize: 13 }}>{label}</Text>
                          <Text style={{ color: '#666', fontSize: 11, marginTop: 2 }}>{description}</Text>
                        </View>
                      </TouchableOpacity>
                    ))}
                  </View>
                ) : null}

                {isMasterUser ? (
                  <View style={{ flexDirection: 'row', gap: 10, marginBottom: 20 }}>
                    <TextInput
                      style={[styles.dimInput, { flex: 1, textAlign: 'left', fontSize: 16 }]}
                      placeholder="Full name (e.g. Anisha)"
                      value={newStaffName}
                      onChangeText={setNewStaffName}
                      onSubmitEditing={() => addStaff(newStaffName)}
                    />
                    <TouchableOpacity
                      style={[styles.packBtn, { backgroundColor: themeColor, paddingHorizontal: 20 }]}
                      onPress={() => addStaff(newStaffName)}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 15 }}>ADD</Text>
                    </TouchableOpacity>
                  </View>
                ) : null}

                {staffList.map(item => (
                  <View key={item.id} style={[styles.adminStaffRow, { flexDirection: 'column' }]}>
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                      <View style={{ flex: 1 }}>
                        <Text style={styles.adminStaffName}>{item.name}</Text>
                        <Text style={{ fontSize: 12, color: '#888', marginTop: 2, textTransform: 'capitalize' }}>
                          {item.role || 'secondary'}
                        </Text>
                      </View>
                      {isMasterUser ? (
                        <TouchableOpacity style={styles.adminTrashBtn} onPress={() => deleteStaff(item.id)}>
                          <Text style={{ fontSize: 20 }}>🗑️</Text>
                        </TouchableOpacity>
                      ) : null}
                    </View>

                    {isMasterUser ? (
                      <>
                        <View style={{ flexDirection: 'row', gap: 8, marginTop: 10 }}>
                          {[['Pick', 'can_pick'], ['Pack', 'can_pack'], ['Print', 'can_print'], ['Active', 'is_active']].map(([label, field]) => (
                            <View key={field} style={{ flex: 1 }}>
                              <TouchableOpacity
                                onPress={() => {
                                  const nextValue = !item[field];
                                  setStaffList(prev => prev.map(s => s.id === item.id ? { ...s, [field]: nextValue } : s));
                                  setStaffDirty(prev => ({ ...prev, [item.id]: { ...(prev[item.id] || {}), [field]: nextValue ? 1 : 0 } }));
                                }}
                                style={{
                                  alignItems: 'center', paddingVertical: 7, borderRadius: 8,
                                  backgroundColor: item[field] ? '#e6f4ef' : '#f4f4f4',
                                  borderWidth: 1, borderColor: item[field] ? '#a3d9c3' : '#e0e0e0',
                                }}
                              >
                                <Text style={{ fontSize: 10, fontWeight: '800', color: item[field] ? '#007a58' : '#aaa', textTransform: 'uppercase', letterSpacing: 0.4 }}>
                                  {label}
                                </Text>
                                <Text style={{ fontSize: 16, marginTop: 2 }}>{item[field] ? '✅' : '○'}</Text>
                              </TouchableOpacity>
                            </View>
                          ))}
                        </View>

                        <View style={{ flexDirection: 'row', gap: 8, marginTop: 8 }}>
                          {staffDirty[item.id] ? (
                            <TouchableOpacity
                              style={[styles.packBtn, { backgroundColor: themeColor, flex: 1 }]}
                              onPress={() => saveStaffChanges(item.id)}
                            >
                              <Text style={{ color: '#fff', fontWeight: 'bold' }}>SAVE</Text>
                            </TouchableOpacity>
                          ) : (
                            <View style={{ flex: 1 }} />
                          )}
                        </View>

                        {securityMode === 'individual_pin' && item.role !== 'master' && (
                          <View style={{ marginTop: 10, paddingTop: 10, borderTopWidth: 1, borderTopColor: '#e0e0e0' }}>
                            <Text style={{ fontSize: 11, fontWeight: '700', color: '#666', marginBottom: 6 }}>4-Digit PIN Code</Text>
                            <TextInput
                              style={[styles.dimInput, { textAlign: 'left', fontSize: 14, letterSpacing: 4 }]}
                              placeholder="0000"
                              keyboardType="number-pad"
                              maxLength={4}
                              secureTextEntry
                              value={Object.prototype.hasOwnProperty.call(staffPinCodes, item.id) ? staffPinCodes[item.id] : (item.pin_code || '')}
                              onChangeText={(text) => {
                                const numericText = text.replace(/[^0-9]/g, '');
                                setStaffPinCodes(prev => ({ ...prev, [item.id]: numericText }));
                                if (numericText.length === 0 || numericText.length === 4) {
                                  setStaffDirty(prev => ({ ...prev, [item.id]: { ...(prev[item.id] || {}), pin_code: numericText } }));
                                }
                              }}
                            />
                          </View>
                        )}
                      </>
                    ) : null}
                  </View>
                ))}

                <TouchableOpacity
                  style={{ backgroundColor: '#e74c3c', borderRadius: 10, paddingVertical: 14, alignItems: 'center', marginTop: 10 }}
                  onPress={() => {
                    Alert.alert('Log Out', 'Sign out of this device?', [
                      { text: 'Cancel', style: 'cancel' },
                      {
                        text: 'Log Out', style: 'destructive', onPress: async () => {
                          setSettingsVisible(false);
                          await handleSessionExpired();
                        },
                      },
                    ]);
                  }}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold' }}>LOG OUT</Text>
                </TouchableOpacity>
              </View>
            )}

            {/* COURIER TAB */}
            {settingsTab === 'courier' && (
              <View>
                <Text style={{ color: '#666', marginBottom: 10 }}>
                  Active courier is highlighted below. Live pricing uses all returned Packie carrier options for the selected stock. Sensitive credentials are hidden unless you choose to edit them.
                </Text>
                {shippingProviders.length === 0 ? (
                  <View style={{ alignItems: 'center', padding: 20 }}>
                    <Text style={{ color: '#aaa', marginBottom: 10 }}>Loading providers...</Text>
                    <TouchableOpacity
                      style={[styles.packBtn, { backgroundColor: themeColor, paddingHorizontal: 20 }]}
                      onPress={() => fetchProviders()}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>RETRY</Text>
                    </TouchableOpacity>
                  </View>
                ) : (
                  shippingProviders.map(p => (
                    <TouchableOpacity
                      key={p.slug}
                      onPress={() => {
                        setSelectedShipProvider(p.slug);
                      }}
                      style={{
                        padding: 12, borderRadius: 8,
                        backgroundColor: selectedShipProvider === p.slug ? '#e8f8f3' : '#fafafa',
                        marginBottom: 8,
                        borderWidth: selectedShipProvider === p.slug ? 1 : 0,
                        borderColor: '#9fdac2',
                      }}
                    >
                      <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Text style={{ fontWeight: '700' }}>{p.display_name}</Text>
                        {selectedShipProvider === p.slug ? (
                          <View style={{ backgroundColor: '#007a58', borderRadius: 999, paddingHorizontal: 10, paddingVertical: 3 }}>
                            <Text style={{ color: '#fff', fontSize: 11, fontWeight: '800' }}>ACTIVE</Text>
                          </View>
                        ) : null}
                      </View>
                      {p.notes ? <Text style={{ color: '#666', marginTop: 4 }}>{p.notes}</Text> : null}

                      {selectedShipProvider === p.slug ? (
                        <TouchableOpacity
                          style={[styles.packBtn, { backgroundColor: forceUpdatingCourier ? '#9ca3af' : '#1f7a8c', marginTop: 10 }]}
                          onPress={forceUpdateCourier}
                          disabled={forceUpdatingCourier}
                        >
                          <Text style={{ color: '#fff', fontWeight: 'bold' }}>
                            {forceUpdatingCourier ? 'UPDATING...' : 'FORCE UPDATE & SET STOCKS'}
                          </Text>
                        </TouchableOpacity>
                      ) : null}
                    </TouchableOpacity>
                  ))
                )}

                <View style={{ marginTop: 12, backgroundColor: '#f7f9fb', borderWidth: 1, borderColor: '#e7edf2', borderRadius: 10, padding: 12 }}>
                  <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 10 }}>
                    <View style={{ flex: 1 }}>
                      <Text style={{ fontWeight: '800', color: '#334' }}>Stock size mapping</Text>
                      <Text style={{ color: '#667', fontSize: 12, marginTop: 2 }}>
                        Match app sizes to the selected courier stock list.
                      </Text>
                    </View>
                    <TouchableOpacity
                      style={[styles.packBtn, { backgroundColor: '#6b7280', paddingHorizontal: 12 }]}
                      onPress={() => packageMappingVisible ? setPackageMappingVisible(false) : fetchPackageMapping(selectedShipProvider, true)}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>
                        {packageMappingVisible ? 'HIDE' : 'SET STOCKS'}
                      </Text>
                    </TouchableOpacity>
                  </View>

                  {packageMappingVisible && (
                    <View style={{ marginTop: 12 }}>
                      <Text style={{ color: '#445', fontSize: 12, marginBottom: 8 }}>
                        Courier: {packageMappingProvider || selectedShipProvider}
                      </Text>
                      {packageMappingLoading ? (
                        <Text style={{ color: '#889' }}>Loading stock options...</Text>
                      ) : packageStockOptions.length === 0 ? (
                        <Text style={{ color: '#667', fontSize: 12 }}>
                          This courier has no stock catalogue yet, so these sizes will use the saved dimensions.
                        </Text>
                      ) : (
                        <>
                          {isPackieStockMapping ? (
                            <>
                              <Text style={{ fontWeight: '800', color: '#223', marginTop: 2 }}>
                                Packie stock rules
                              </Text>
                              <Text style={{ color: '#667', fontSize: 12, marginTop: 2, marginBottom: 8 }}>
                                Quick pick stocks appear on the fast print screen. Live-only stocks stay available for rate checks.
                              </Text>
                              {packageStockOptions.map(option => (
                                <View key={`packie-stock-rule-${option.id}`} style={{ borderTopWidth: 1, borderTopColor: '#e1e7ec', paddingTop: 10, marginTop: 10 }}>
                                  <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
                                    <View style={{ flex: 1 }}>
                                      <Text style={{ fontWeight: '800', color: '#223' }}>{option.label}</Text>
                                      <Text style={{ color: '#667', fontSize: 12, marginTop: 2 }}>
                                        {option.length} x {option.width} x {option.height} cm, {option.weight} kg
                                      </Text>
                                      {option.quick_pick_is_default ? (
                                        <Text style={{ color: themeColor, fontSize: 11, fontWeight: '900', marginTop: 3 }}>
                                          DEFAULT QUICK PICK
                                        </Text>
                                      ) : null}
                                    </View>
                                    <View style={{ alignItems: 'center' }}>
                                      <Switch
                                        value={!!option.quick_pick_enabled}
                                        onValueChange={value => setQuickPickEnabled(option, value)}
                                      />
                                      <Text style={{ color: option.quick_pick_enabled ? themeColor : '#667', fontWeight: '800', fontSize: 11 }}>
                                        {option.quick_pick_enabled ? 'QUICK' : 'LIVE'}
                                      </Text>
                                    </View>
                                  </View>

                                  {option.quick_pick_enabled ? (
                                    <View style={{ marginTop: 8, gap: 8 }}>
                                      <View>
                                        <Text style={{ color: '#667', fontSize: 12, fontWeight: '700', marginBottom: 6 }}>
                                          Carrier
                                        </Text>
                                        <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6 }}>
                                          {(option.quick_pick_carrier_options || []).length === 0 ? (
                                            <Text style={{ color: '#b45309', fontSize: 12 }}>
                                              No Packie couriers loaded. Run Force Update and Set Stocks again.
                                            </Text>
                                          ) : null}
                                          {(option.quick_pick_carrier_options || []).map(carrier => {
                                            const active = String(option.quick_pick_carrier || '') === String(carrier);
                                            return (
                                              <TouchableOpacity
                                                key={`${option.id}-${carrier}`}
                                                style={{
                                                  backgroundColor: active ? themeColor : '#e5e7eb',
                                                  borderRadius: 8,
                                                  paddingHorizontal: 10,
                                                  paddingVertical: 8,
                                                }}
                                                onPress={() => setPackageStockSetting(option.id, { quick_pick_carrier: carrier })}
                                              >
                                                <Text style={{ color: active ? '#fff' : '#334', fontWeight: '800', fontSize: 12 }}>
                                                  {carrier}
                                                </Text>
                                              </TouchableOpacity>
                                            );
                                          })}
                                        </View>
                                      </View>
                                      <TextInput
                                        value={option.quick_pick_display_name || option.display_label || option.label || option.name || ''}
                                        onChangeText={text => setPackageStockSetting(option.id, { quick_pick_display_name: text })}
                                        placeholder="Quick pick display name"
                                        style={[styles.input, { marginBottom: 0 }]}
                                      />
                                      <TouchableOpacity
                                        style={{
                                          backgroundColor: option.quick_pick_is_default ? themeColor : '#e5e7eb',
                                          borderRadius: 8,
                                          paddingVertical: 10,
                                          alignItems: 'center',
                                        }}
                                        onPress={() => setQuickPickDefault(option)}
                                      >
                                        <Text style={{ color: option.quick_pick_is_default ? '#fff' : '#334', fontWeight: '900' }}>
                                          {option.quick_pick_is_default ? 'DEFAULT SELECTED' : 'SET AS DEFAULT'}
                                        </Text>
                                      </TouchableOpacity>
                                    </View>
                                  ) : null}
                                </View>
                              ))}
                            </>
                          ) : null}

                        </>
                      )}

                      {packageStockOptions.length > 0 && (
                        <TouchableOpacity
                          style={[styles.packBtn, { backgroundColor: packageMappingSaving ? '#9ca3af' : themeColor, marginTop: 12 }]}
                          onPress={savePackageMapping}
                          disabled={packageMappingSaving}
                        >
                          <Text style={{ color: '#fff', fontWeight: 'bold' }}>
                            {packageMappingSaving ? 'SAVING...' : 'SAVE STOCK SETTINGS'}
                          </Text>
                        </TouchableOpacity>
                      )}
                    </View>
                  )}
                </View>

                <View style={{ marginTop: 12 }}>
                  <Text style={{ fontWeight: '700', marginBottom: 6 }}>Credentials for {selectedShipProvider}</Text>
                  <View style={{ backgroundColor: '#f5f7f8', borderRadius: 8, padding: 10, marginBottom: 10 }}>
                    <Text style={{ color: '#333', fontSize: 12 }}>
                      Username: {activeShippingUsername ? 'Saved' : 'Not set'}
                    </Text>
                    <Text style={{ color: '#333', fontSize: 12, marginTop: 2 }}>
                      {selectedShipProvider === 'zappy' ? 'Password' : 'API/Token'}: {hasShippingSecret ? 'Saved (hidden)' : 'Not set'}
                    </Text>
                  </View>

                  <TouchableOpacity
                    style={[styles.packBtn, { backgroundColor: '#6b7280', marginBottom: 10 }]}
                    onPress={() => setShowProviderInputs(prev => ({ ...prev, shipping: !prev.shipping }))}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold' }}>
                      {showProviderInputs.shipping ? 'HIDE CREDENTIAL FIELDS' : 'EDIT CREDENTIAL FIELDS'}
                    </Text>
                  </TouchableOpacity>

                  {showProviderInputs.shipping && activeShippingDefs.map((f, idx) => (
                    <View key={`${selectedShipProvider}-${f.key || 'field'}-${idx}`} style={{ marginBottom: 10 }}>
                      <Text style={{ color: '#444', marginBottom: 4 }}>
                        {selectedShipProvider === 'zappy' && String(f.key || '').toLowerCase() === 'api_key' ? 'Zappy Password' : f.label}
                      </Text>
                      <TextInput
                        style={styles.obInput}
                        value={getProviderInput('shipping', selectedShipProvider, idx)}
                        onChangeText={t => setProviderInput('shipping', selectedShipProvider, idx, t)}
                        secureTextEntry={isSensitiveProviderField(f)}
                        placeholder={isSensitiveProviderField(f) ? (f.example || '••••••••') : (f.example || '')}
                        autoCapitalize="none"
                        autoCorrect={false}
                      />
                    </View>
                  ))}

                  <TouchableOpacity
                    style={[styles.packBtn, { backgroundColor: themeColor, marginTop: 6 }]}
                    onPress={() => saveProviderConfig('shipping')}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold' }}>SAVE COURIER SETTINGS</Text>
                  </TouchableOpacity>
                </View>
              </View>
            )}

            {/* ECOMMERCE TAB */}
            {settingsTab === 'ecommerce' && (
              <View>
                <Text style={{ color: '#666', marginBottom: 10 }}>
                  Active ecommerce provider is highlighted below. Sensitive credentials are hidden unless editing.
                </Text>
                {cmsProviders.length === 0 ? (
                  <View style={{ alignItems: 'center', padding: 20 }}>
                    <Text style={{ color: '#aaa', marginBottom: 10 }}>Loading providers...</Text>
                    <TouchableOpacity
                      style={[styles.packBtn, { backgroundColor: themeColor, paddingHorizontal: 20 }]}
                      onPress={() => fetchProviders()}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>RETRY</Text>
                    </TouchableOpacity>
                  </View>
                ) : (
                  [
                    { slug: 'none', display_name: 'None', notes: '' },
                    ...cmsProviders,
                  ].map(p => (
                    <TouchableOpacity
                      key={p.slug}
                      onPress={() => { setSelectedEcomProvider(p.slug); }}
                      style={{
                        padding: 12, borderRadius: 8,
                        backgroundColor: selectedEcomProvider === p.slug ? '#e8f8f3' : '#fafafa',
                        marginBottom: 8,
                        borderWidth: selectedEcomProvider === p.slug ? 1 : 0,
                        borderColor: '#9fdac2',
                      }}
                    >
                      <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Text style={{ fontWeight: '700' }}>{p.display_name}</Text>
                        {selectedEcomProvider === p.slug ? (
                          <View style={{ backgroundColor: '#007a58', borderRadius: 999, paddingHorizontal: 10, paddingVertical: 3 }}>
                            <Text style={{ color: '#fff', fontSize: 11, fontWeight: '800' }}>ACTIVE</Text>
                          </View>
                        ) : null}
                      </View>
                      {p.notes ? <Text style={{ color: '#666', marginTop: 4 }}>{p.notes}</Text> : null}
                    </TouchableOpacity>
                  ))
                )}

                {selectedEcomProvider !== 'none' && (
                  <View style={{ marginTop: 12 }}>
                    <Text style={{ fontWeight: '700', marginBottom: 6 }}>Credentials for {selectedEcomProvider}</Text>
                    <View style={{ backgroundColor: '#f5f7f8', borderRadius: 8, padding: 10, marginBottom: 10 }}>
                      <Text style={{ color: '#333', fontSize: 12 }}>
                        Store URL: {activeEcommerceConfig.store_url ? 'Saved' : 'Not set'}
                      </Text>
                      <Text style={{ color: '#333', fontSize: 12, marginTop: 2 }}>
                        API/Token: {hasEcommerceSecret ? 'Saved (hidden)' : 'Not set'}
                      </Text>
                    </View>

                    <TouchableOpacity
                      style={[styles.packBtn, { backgroundColor: '#6b7280', marginBottom: 10 }]}
                      onPress={() => setShowProviderInputs(prev => ({ ...prev, ecommerce: !prev.ecommerce }))}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>
                        {showProviderInputs.ecommerce ? 'HIDE CREDENTIAL FIELDS' : 'EDIT CREDENTIAL FIELDS'}
                      </Text>
                    </TouchableOpacity>

                    {showProviderInputs.ecommerce && activeEcommerceDefs.map((f, idx) => (
                      <View key={`${selectedEcomProvider}-${f.key || 'field'}-${idx}`} style={{ marginBottom: 10 }}>
                        <Text style={{ color: '#444', marginBottom: 4 }}>{f.label}</Text>
                        <TextInput
                          style={styles.obInput}
                          value={getProviderInput('ecommerce', selectedEcomProvider, idx)}
                          onChangeText={t => setProviderInput('ecommerce', selectedEcomProvider, idx, t)}
                          secureTextEntry={isSensitiveProviderField(f)}
                          placeholder={isSensitiveProviderField(f) ? (f.example || '••••••••') : (f.example || '')}
                          autoCapitalize="none"
                          autoCorrect={false}
                        />
                      </View>
                    ))}

                    <TouchableOpacity
                      style={[styles.packBtn, { backgroundColor: themeColor, marginTop: 6 }]}
                      onPress={() => saveProviderConfig('ecommerce')}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>SAVE ECOMMERCE SETTINGS</Text>
                    </TouchableOpacity>
                  </View>
                )}

                {selectedEcomProvider === 'none' && (
                  <TouchableOpacity
                    style={[styles.packBtn, { backgroundColor: '#e74c3c', marginTop: 16 }]}
                    onPress={() => saveProviderConfig('ecommerce')}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold' }}>DISABLE ECOMMERCE</Text>
                  </TouchableOpacity>
                )}
              </View>
            )}

          </ScrollView>
        </View>
      </View>
    </Modal>
  );
}
