All files / src/screens Settings.tsx

0% Statements 0/292
0% Branches 0/201
0% Functions 0/62
0% Lines 0/278

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { useState, useEffect } from 'react'
import {
  ArrowLeft,
  Key,
  Bot,
  Check,
  X,
  ChevronDown,
  ChevronUp,
  AlertCircle,
  AlertTriangle,
  Loader2,
  Globe,
  Code,
  Settings as SettingsIcon,
  Github,
  ToggleLeft,
  ToggleRight,
  CheckCircle,
  XCircle,
  HelpCircle,
  Play,
  Users,
  Trash2,
} from 'lucide-react'
import { toast } from 'sonner'
import {
  api,
  type AIPrompt,
  type AIModel,
  type AIStatus,
  type Source,
  type ProfileWithStats,
  type DeletionPreview,
  type ResetPreview,
} from '../api/client'
import { cn } from '../lib/utils'
import { useAIStatus } from '../contexts/AIStatusContext'
 
interface SettingsProps {
  onBack: () => void
  currentProfileId?: number | null
}
 
type Tab = 'general' | 'prompts' | 'sources' | 'selectors' | 'users' | 'danger'
 
export default function Settings({ onBack, currentProfileId }: SettingsProps) {
  const [activeTab, setActiveTab] = useState<Tab>('general')
  const [aiStatus, setAiStatus] = useState<AIStatus | null>(null)
  const [prompts, setPrompts] = useState<AIPrompt[]>([])
  const [models, setModels] = useState<AIModel[]>([])
  const [sources, setSources] = useState<Source[]>([])
  const [loading, setLoading] = useState(true)
  const globalAIStatus = useAIStatus()
 
  // Users tab state
  const [profiles, setProfiles] = useState<ProfileWithStats[]>([])
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [deletePreview, setDeletePreview] = useState<DeletionPreview | null>(null)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [deleting, setDeleting] = useState(false)
 
  // Danger Zone state
  const [showResetModal, setShowResetModal] = useState(false)
  const [resetPreview, setResetPreview] = useState<ResetPreview | null>(null)
  const [resetStep, setResetStep] = useState<1 | 2>(1)
  const [resetConfirmText, setResetConfirmText] = useState('')
  const [resetting, setResetting] = useState(false)
 
  // API Key state
  const [apiKey, setApiKey] = useState('')
  const [testingKey, setTestingKey] = useState(false)
  const [savingKey, setSavingKey] = useState(false)
 
  // Editing state for prompts
  const [editingPromptType, setEditingPromptType] = useState<string | null>(null)
  const [editForm, setEditForm] = useState<{
    system_prompt: string
    user_prompt_template: string
    model: string
    is_active: boolean
  } | null>(null)
  const [savingPrompt, setSavingPrompt] = useState(false)
 
  // Expanded prompts for viewing
  const [expandedPrompts, setExpandedPrompts] = useState<Set<string>>(new Set())
 
  // Sources state
  const [togglingSourceId, setTogglingSourceId] = useState<number | null>(null)
  const [bulkToggling, setBulkToggling] = useState(false)
 
  // Selectors state
  const [editingSourceId, setEditingSourceId] = useState<number | null>(null)
  const [editingSelectorValue, setEditingSelectorValue] = useState('')
  const [savingSelector, setSavingSelector] = useState(false)
  const [testingSourceId, setTestingSourceId] = useState<number | null>(null)
  const [testingAll, setTestingAll] = useState(false)
 
  useEffect(() => {
    loadData()
  }, [])
 
  const loadData = async () => {
    try {
      const [statusData, promptsData, modelsData, sourcesData, profilesData] = await Promise.all([
        api.ai.status(),
        api.ai.prompts.list(),
        api.ai.models(),
        api.sources.list(),
        api.profiles.list(),
      ])
      setAiStatus(statusData)
      setPrompts(promptsData)
      setModels(modelsData)
      setSources(sourcesData)
      setProfiles(profilesData)
    } catch (error) {
      console.error('Failed to load settings:', error)
      toast.error('Failed to load settings')
    } finally {
      setLoading(false)
    }
  }
 
  // API Key handlers
  const handleTestApiKey = async () => {
    if (!apiKey.trim()) {
      toast.error('Please enter an API key')
      return
    }
 
    setTestingKey(true)
    try {
      const result = await api.ai.testApiKey(apiKey.trim())
      if (result.success) {
        toast.success(result.message)
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      console.error('Failed to test API key:', error)
      toast.error('Failed to test API key')
    } finally {
      setTestingKey(false)
    }
  }
 
  const handleSaveApiKey = async () => {
    if (!apiKey.trim()) {
      toast.error('Please enter an API key')
      return
    }
 
    setSavingKey(true)
    try {
      const result = await api.ai.saveApiKey(apiKey.trim())
      if (result.success) {
        toast.success(result.message)
        setApiKey('')
        const statusData = await api.ai.status()
        setAiStatus(statusData)
        await globalAIStatus.refresh()
        const modelsData = await api.ai.models()
        setModels(modelsData)
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      console.error('Failed to save API key:', error)
      toast.error('Failed to save API key')
    } finally {
      setSavingKey(false)
    }
  }
 
  // Prompt handlers
  const handleEditPrompt = (prompt: AIPrompt) => {
    setEditingPromptType(prompt.prompt_type)
    setEditForm({
      system_prompt: prompt.system_prompt,
      user_prompt_template: prompt.user_prompt_template,
      model: prompt.model,
      is_active: prompt.is_active,
    })
  }
 
  const handleCancelEdit = () => {
    setEditingPromptType(null)
    setEditForm(null)
  }
 
  const handleSavePrompt = async () => {
    if (!editingPromptType || !editForm) return
 
    setSavingPrompt(true)
    try {
      const updated = await api.ai.prompts.update(editingPromptType, editForm)
      setPrompts(prompts.map(p =>
        p.prompt_type === editingPromptType ? updated : p
      ))
      toast.success('Prompt saved successfully')
      setEditingPromptType(null)
      setEditForm(null)
    } catch (error) {
      console.error('Failed to save prompt:', error)
      let errorMessage = 'Failed to save prompt'
      if (error instanceof Error) {
        try {
          const parsed = JSON.parse(error.message)
          if (parsed.message) {
            errorMessage = parsed.message
          }
        } catch {
          // Not JSON
        }
      }
      toast.error(errorMessage)
    } finally {
      setSavingPrompt(false)
    }
  }
 
  const toggleExpandPrompt = (promptType: string) => {
    setExpandedPrompts(prev => {
      const next = new Set(prev)
      if (next.has(promptType)) {
        next.delete(promptType)
      } else {
        next.add(promptType)
      }
      return next
    })
  }
 
  // Source handlers
  const handleToggleSource = async (sourceId: number) => {
    setTogglingSourceId(sourceId)
    try {
      const result = await api.sources.toggle(sourceId)
      setSources(sources.map(s =>
        s.id === sourceId ? { ...s, is_enabled: result.is_enabled } : s
      ))
    } catch (error) {
      console.error('Failed to toggle source:', error)
      toast.error('Failed to toggle source')
    } finally {
      setTogglingSourceId(null)
    }
  }
 
  const handleBulkToggle = async (enable: boolean) => {
    setBulkToggling(true)
    try {
      await api.sources.bulkToggle(enable)
      setSources(sources.map(s => ({ ...s, is_enabled: enable })))
      toast.success(enable ? 'All sources enabled' : 'All sources disabled')
    } catch (error) {
      console.error('Failed to bulk toggle sources:', error)
      toast.error('Failed to update sources')
    } finally {
      setBulkToggling(false)
    }
  }
 
  // Selector handlers
  const handleEditSelector = (source: Source) => {
    setEditingSourceId(source.id)
    setEditingSelectorValue(source.result_selector)
  }
 
  const handleCancelEditSelector = () => {
    setEditingSourceId(null)
    setEditingSelectorValue('')
  }
 
  const handleSaveSelector = async () => {
    if (editingSourceId === null) return
 
    setSavingSelector(true)
    try {
      const result = await api.sources.updateSelector(editingSourceId, editingSelectorValue)
      setSources(sources.map(s =>
        s.id === editingSourceId ? { ...s, result_selector: result.result_selector } : s
      ))
      toast.success('Selector updated')
      setEditingSourceId(null)
      setEditingSelectorValue('')
    } catch (error) {
      console.error('Failed to update selector:', error)
      toast.error('Failed to update selector')
    } finally {
      setSavingSelector(false)
    }
  }
 
  const handleTestSource = async (sourceId: number) => {
    setTestingSourceId(sourceId)
    try {
      const result = await api.sources.test(sourceId)
      if (result.success) {
        toast.success(result.message)
        // Refresh sources to update status
        const sourcesData = await api.sources.list()
        setSources(sourcesData)
      } else {
        toast.error(result.message)
        const sourcesData = await api.sources.list()
        setSources(sourcesData)
      }
    } catch (error) {
      console.error('Failed to test source:', error)
      toast.error('Failed to test source')
    } finally {
      setTestingSourceId(null)
    }
  }
 
  const handleTestAllSources = async () => {
    setTestingAll(true)
    try {
      const result = await api.sources.testAll()
      toast.success(`Tested ${result.tested} sources: ${result.passed} passed, ${result.failed} failed`)
      // Refresh sources
      const sourcesData = await api.sources.list()
      setSources(sourcesData)
    } catch (error) {
      console.error('Failed to test all sources:', error)
      toast.error('Failed to test all sources')
    } finally {
      setTestingAll(false)
    }
  }
 
  const getModelName = (modelId: string) => {
    const model = models.find(m => m.id === modelId)
    return model?.name || modelId
  }
 
  const getSourceStatus = (source: Source): 'working' | 'broken' | 'untested' => {
    if (!source.last_validated_at) return 'untested'
    if (source.needs_attention || source.consecutive_failures >= 3) return 'broken'
    return 'working'
  }
 
  const formatRelativeTime = (dateStr: string | null): string => {
    if (!dateStr) return 'Never'
    const date = new Date(dateStr)
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffMins = Math.floor(diffMs / 60000)
    if (diffMins < 1) return 'Just now'
    if (diffMins < 60) return `${diffMins}m ago`
    const diffHours = Math.floor(diffMins / 60)
    if (diffHours < 24) return `${diffHours}h ago`
    const diffDays = Math.floor(diffHours / 24)
    return `${diffDays}d ago`
  }
 
  // Profile deletion handlers
  const handleDeleteClick = async (profileId: number) => {
    try {
      const preview = await api.profiles.deletionPreview(profileId)
      setDeletePreview(preview)
      setDeletingId(profileId)
      setShowDeleteModal(true)
    } catch (error) {
      console.error('Failed to load deletion preview:', error)
      toast.error('Failed to load profile info')
    }
  }
 
  const handleConfirmDelete = async () => {
    if (!deletingId) return
 
    setDeleting(true)
    try {
      await api.profiles.delete(deletingId)
      setProfiles(profiles.filter(p => p.id !== deletingId))
      toast.success('Profile deleted successfully')
      setShowDeleteModal(false)
      setDeletePreview(null)
      setDeletingId(null)
    } catch (error) {
      console.error('Failed to delete profile:', error)
      toast.error('Failed to delete profile')
    } finally {
      setDeleting(false)
    }
  }
 
  const handleCancelDelete = () => {
    setShowDeleteModal(false)
    setDeletePreview(null)
    setDeletingId(null)
  }
 
  // Database Reset handlers
  const handleResetClick = async () => {
    try {
      const preview = await api.system.resetPreview()
      setResetPreview(preview)
      setResetStep(1)
      setResetConfirmText('')
      setShowResetModal(true)
    } catch (error) {
      console.error('Failed to load reset preview:', error)
      toast.error('Failed to load reset preview')
    }
  }
 
  const handleResetContinue = () => {
    setResetStep(2)
  }
 
  const handleResetBack = () => {
    setResetStep(1)
    setResetConfirmText('')
  }
 
  const handleConfirmReset = async () => {
    if (resetConfirmText !== 'RESET') return
 
    setResetting(true)
    try {
      await api.system.reset('RESET')
      toast.success('Database reset complete')
      // Redirect to home/profile creation
      window.location.href = '/'
    } catch (error) {
      console.error('Failed to reset database:', error)
      toast.error('Failed to reset database')
    } finally {
      setResetting(false)
    }
  }
 
  const handleCancelReset = () => {
    setShowResetModal(false)
    setResetPreview(null)
    setResetStep(1)
    setResetConfirmText('')
  }
 
  const formatDate = (dateStr: string): string => {
    return new Date(dateStr).toLocaleDateString()
  }
 
  const enabledCount = sources.filter(s => s.is_enabled).length
 
  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="flex items-center gap-4 border-b border-border px-4 py-3">
        <button
          onClick={onBack}
          className="rounded-lg p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
        >
          <ArrowLeft className="h-5 w-5" />
        </button>
        <h1 className="text-xl font-medium text-foreground">Settings</h1>
      </header>
 
      {/* Tab navigation */}
      <div className="border-b border-border px-4">
        <div className="mx-auto max-w-4xl">
          <div className="flex gap-4 overflow-x-auto">
            <button
              onClick={() => setActiveTab('general')}
              className={cn(
                'border-b-2 py-3 text-sm font-medium transition-colors whitespace-nowrap',
                activeTab === 'general'
                  ? 'border-primary text-primary'
                  : 'border-transparent text-muted-foreground hover:text-foreground'
              )}
            >
              <span className="flex items-center gap-2">
                <SettingsIcon className="h-4 w-4" />
                General
              </span>
            </button>
            <button
              onClick={() => setActiveTab('prompts')}
              className={cn(
                'border-b-2 py-3 text-sm font-medium transition-colors whitespace-nowrap',
                activeTab === 'prompts'
                  ? 'border-primary text-primary'
                  : 'border-transparent text-muted-foreground hover:text-foreground'
              )}
            >
              <span className="flex items-center gap-2">
                <Bot className="h-4 w-4" />
                AI Prompts
              </span>
            </button>
            <button
              onClick={() => setActiveTab('sources')}
              className={cn(
                'border-b-2 py-3 text-sm font-medium transition-colors whitespace-nowrap',
                activeTab === 'sources'
                  ? 'border-primary text-primary'
                  : 'border-transparent text-muted-foreground hover:text-foreground'
              )}
            >
              <span className="flex items-center gap-2">
                <Globe className="h-4 w-4" />
                Sources
              </span>
            </button>
            <button
              onClick={() => setActiveTab('selectors')}
              className={cn(
                'border-b-2 py-3 text-sm font-medium transition-colors whitespace-nowrap',
                activeTab === 'selectors'
                  ? 'border-primary text-primary'
                  : 'border-transparent text-muted-foreground hover:text-foreground'
              )}
            >
              <span className="flex items-center gap-2">
                <Code className="h-4 w-4" />
                Selectors
              </span>
            </button>
            <button
              onClick={() => setActiveTab('users')}
              className={cn(
                'border-b-2 py-3 text-sm font-medium transition-colors whitespace-nowrap',
                activeTab === 'users'
                  ? 'border-primary text-primary'
                  : 'border-transparent text-muted-foreground hover:text-foreground'
              )}
            >
              <span className="flex items-center gap-2">
                <Users className="h-4 w-4" />
                Users
              </span>
            </button>
            <button
              onClick={() => setActiveTab('danger')}
              className={cn(
                'border-b-2 py-3 text-sm font-medium transition-colors whitespace-nowrap',
                activeTab === 'danger'
                  ? 'border-destructive text-destructive'
                  : 'border-transparent text-muted-foreground hover:text-destructive'
              )}
            >
              <span className="flex items-center gap-2">
                <AlertTriangle className="h-4 w-4" />
                Danger Zone
              </span>
            </button>
          </div>
        </div>
      </div>
 
      {/* Content */}
      <main className="px-4 py-6">
        <div className="mx-auto max-w-4xl">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : activeTab === 'general' ? (
            /* General Tab */
            <div className="space-y-6">
              {/* OpenRouter API */}
              <div className="rounded-lg border border-border bg-card p-4">
                <h2 className="mb-4 text-lg font-medium text-foreground">OpenRouter API</h2>
 
                <div className="mb-4 flex items-center gap-2">
                  <div
                    className={cn(
                      'h-2 w-2 rounded-full',
                      aiStatus?.available ? 'bg-green-500' : aiStatus?.configured ? 'bg-yellow-500' : 'bg-red-500'
                    )}
                  />
                  <span className="text-sm text-muted-foreground">
                    {aiStatus?.available ? 'Connected' : aiStatus?.configured ? 'Invalid key' : 'Not configured'}
                  </span>
                </div>
 
                {aiStatus?.configured && !aiStatus?.valid && (
                  <div className="mb-4 flex items-center gap-2 rounded-lg border border-yellow-500/50 bg-yellow-500/10 p-3">
                    <AlertCircle className="h-5 w-5 flex-shrink-0 text-yellow-500" />
                    <p className="text-sm text-yellow-600 dark:text-yellow-400">
                      {aiStatus?.error || 'Your API key appears to be invalid or expired. Please update it.'}
                    </p>
                  </div>
                )}
 
                {aiStatus?.available && (
                  <div className="mb-4 text-sm text-muted-foreground">
                    Default model: <span className="font-medium text-foreground">{getModelName(aiStatus.default_model)}</span>
                  </div>
                )}
 
                <div className="space-y-3">
                  <label className="block">
                    <span className="mb-1 block text-sm font-medium text-foreground">
                      {aiStatus?.available ? 'Update API Key' : 'API Key'}
                    </span>
                    <input
                      type="password"
                      value={apiKey}
                      onChange={(e) => setApiKey(e.target.value)}
                      placeholder="sk-or-v1-..."
                      className="w-full rounded-lg border border-border bg-input-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                    />
                  </label>
 
                  <div className="flex gap-2">
                    <button
                      onClick={handleTestApiKey}
                      disabled={testingKey || !apiKey.trim()}
                      className="flex items-center gap-2 rounded-lg border border-border bg-background px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      {testingKey ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <Check className="h-4 w-4" />
                      )}
                      Test Key
                    </button>
                    <button
                      onClick={handleSaveApiKey}
                      disabled={savingKey || !apiKey.trim()}
                      className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      {savingKey ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <Key className="h-4 w-4" />
                      )}
                      Save Key
                    </button>
                  </div>
                </div>
 
                <p className="mt-4 text-sm text-muted-foreground">
                  Get your API key from{' '}
                  <a
                    href="https://openrouter.ai/keys"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-primary hover:underline"
                  >
                    openrouter.ai/keys
                  </a>
                </p>
              </div>
 
              {/* About */}
              <div className="rounded-lg border border-border bg-card p-4">
                <h2 className="mb-4 text-lg font-medium text-foreground">About</h2>
                <div className="space-y-2 text-sm text-muted-foreground">
                  <div className="flex items-center justify-between">
                    <span>Version</span>
                    <span className="font-medium text-foreground">1.0.0</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span>Source Code</span>
                    <a
                      href="https://github.com/matthewdeaves/cookie.git"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center gap-1 text-primary hover:underline"
                    >
                      <Github className="h-4 w-4" />
                      GitHub
                    </a>
                  </div>
                </div>
              </div>
            </div>
          ) : activeTab === 'prompts' ? (
            /* AI Prompts Tab */
            <div className="space-y-4">
              <div className="flex items-start gap-3 rounded-lg border border-border bg-card p-4">
                <AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-primary" />
                <div>
                  <h2 className="font-medium text-foreground">AI Prompts Configuration</h2>
                  <p className="text-sm text-muted-foreground">
                    Customize the prompts used for AI features. Each prompt has a system prompt that sets the AI's behavior
                    and a user prompt template that includes placeholders for dynamic content.
                  </p>
                </div>
              </div>
 
              {!aiStatus?.available && (
                <div className="flex items-center gap-3 rounded-lg border border-yellow-500/50 bg-yellow-500/10 p-4">
                  <AlertCircle className="h-5 w-5 text-yellow-500" />
                  <p className="text-sm text-yellow-600 dark:text-yellow-400">
                    Configure your OpenRouter API key in the General tab to enable AI features.
                  </p>
                </div>
              )}
 
              {prompts.map((prompt) => {
                const isEditing = editingPromptType === prompt.prompt_type
                const isExpanded = expandedPrompts.has(prompt.prompt_type)
 
                return (
                  <div
                    key={prompt.prompt_type}
                    className="rounded-lg border border-border bg-card"
                  >
                    <div className="flex items-center justify-between p-4">
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <h3 className="font-medium text-foreground">{prompt.name}</h3>
                          {!prompt.is_active && (
                            <span className="rounded bg-muted px-2 py-0.5 text-xs text-muted-foreground">
                              Disabled
                            </span>
                          )}
                        </div>
                        <p className="mt-1 text-sm text-muted-foreground">{prompt.description}</p>
                        <div className="mt-2 flex items-center gap-2">
                          <span className="rounded bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
                            {getModelName(prompt.model)}
                          </span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {!isEditing && (
                          <>
                            <button
                              onClick={() => toggleExpandPrompt(prompt.prompt_type)}
                              className="rounded-lg p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
                              aria-label={isExpanded ? 'Collapse' : 'Expand'}
                            >
                              {isExpanded ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
                            </button>
                            <button
                              onClick={() => handleEditPrompt(prompt)}
                              className="rounded-lg bg-primary/10 px-3 py-1.5 text-sm font-medium text-primary transition-colors hover:bg-primary/20"
                            >
                              Edit
                            </button>
                          </>
                        )}
                      </div>
                    </div>
 
                    {isExpanded && !isEditing && (
                      <div className="border-t border-border px-4 py-4">
                        <div className="space-y-4">
                          <div>
                            <label className="mb-1 block text-sm font-medium text-muted-foreground">System Prompt</label>
                            <pre className="whitespace-pre-wrap rounded-lg bg-muted p-3 text-sm text-foreground">
                              {prompt.system_prompt}
                            </pre>
                          </div>
                          <div>
                            <label className="mb-1 block text-sm font-medium text-muted-foreground">User Prompt Template</label>
                            <pre className="whitespace-pre-wrap rounded-lg bg-muted p-3 text-sm text-foreground">
                              {prompt.user_prompt_template}
                            </pre>
                          </div>
                        </div>
                      </div>
                    )}
 
                    {isEditing && editForm && (
                      <div className="border-t border-border px-4 py-4">
                        <div className="space-y-4">
                          <div>
                            <label className="mb-1 block text-sm font-medium text-foreground">System Prompt</label>
                            <textarea
                              value={editForm.system_prompt}
                              onChange={(e) => setEditForm({ ...editForm, system_prompt: e.target.value })}
                              rows={6}
                              className="w-full rounded-lg border border-border bg-input-background px-3 py-2 font-mono text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                            />
                          </div>
                          <div>
                            <label className="mb-1 block text-sm font-medium text-foreground">User Prompt Template</label>
                            <textarea
                              value={editForm.user_prompt_template}
                              onChange={(e) => setEditForm({ ...editForm, user_prompt_template: e.target.value })}
                              rows={4}
                              className="w-full rounded-lg border border-border bg-input-background px-3 py-2 font-mono text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                            />
                            <p className="mt-1 text-xs text-muted-foreground">
                              Use {'{placeholders}'} for dynamic content
                            </p>
                          </div>
                          <div className="flex gap-4">
                            <div className="flex-1">
                              <label className="mb-1 block text-sm font-medium text-foreground">Model</label>
                              <select
                                value={editForm.model}
                                onChange={(e) => setEditForm({ ...editForm, model: e.target.value })}
                                className="w-full rounded-lg border border-border bg-input-background px-3 py-2 text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                              >
                                {models.map((model) => (
                                  <option key={model.id} value={model.id}>{model.name}</option>
                                ))}
                              </select>
                            </div>
                            <div>
                              <label className="mb-1 block text-sm font-medium text-foreground">Status</label>
                              <button
                                onClick={() => setEditForm({ ...editForm, is_active: !editForm.is_active })}
                                className={cn(
                                  'rounded-lg px-4 py-2 text-sm font-medium transition-colors',
                                  editForm.is_active
                                    ? 'bg-green-500/10 text-green-600 hover:bg-green-500/20 dark:text-green-400'
                                    : 'bg-muted text-muted-foreground hover:bg-muted/80'
                                )}
                              >
                                {editForm.is_active ? 'Active' : 'Disabled'}
                              </button>
                            </div>
                          </div>
                          <div className="flex justify-end gap-2">
                            <button
                              onClick={handleCancelEdit}
                              className="flex items-center gap-2 rounded-lg border border-border bg-background px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-muted"
                            >
                              <X className="h-4 w-4" />
                              Cancel
                            </button>
                            <button
                              onClick={handleSavePrompt}
                              disabled={savingPrompt}
                              className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"
                            >
                              {savingPrompt ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
                              Save Changes
                            </button>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          ) : activeTab === 'sources' ? (
            /* Sources Tab */
            <div className="space-y-4">
              <div className="flex items-center justify-between rounded-lg border border-border bg-card p-4">
                <div>
                  <h2 className="text-lg font-medium text-foreground">Recipe Sources</h2>
                  <p className="text-sm text-muted-foreground">
                    {enabledCount} of {sources.length} sources currently enabled
                  </p>
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={() => handleBulkToggle(true)}
                    disabled={bulkToggling || enabledCount === sources.length}
                    className="rounded-lg border border-border bg-background px-3 py-1.5 text-sm font-medium text-foreground transition-colors hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    Enable All
                  </button>
                  <button
                    onClick={() => handleBulkToggle(false)}
                    disabled={bulkToggling || enabledCount === 0}
                    className="rounded-lg border border-border bg-background px-3 py-1.5 text-sm font-medium text-foreground transition-colors hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    Disable All
                  </button>
                </div>
              </div>
 
              <div className="space-y-2">
                {sources.map((source) => (
                  <div
                    key={source.id}
                    className={cn(
                      'flex items-center justify-between rounded-lg border p-4 transition-colors',
                      source.is_enabled ? 'border-border bg-card' : 'border-border/50 bg-muted/30'
                    )}
                  >
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-foreground">{source.name}</span>
                        {source.is_enabled && (
                          <span className="rounded bg-green-500/10 px-2 py-0.5 text-xs font-medium text-green-600 dark:text-green-400">
                            Active
                          </span>
                        )}
                      </div>
                      <p className="text-sm text-muted-foreground">{source.host}</p>
                    </div>
                    <button
                      onClick={() => handleToggleSource(source.id)}
                      disabled={togglingSourceId === source.id}
                      className="text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50"
                    >
                      {togglingSourceId === source.id ? (
                        <Loader2 className="h-6 w-6 animate-spin" />
                      ) : source.is_enabled ? (
                        <ToggleRight className="h-8 w-8 text-primary" />
                      ) : (
                        <ToggleLeft className="h-8 w-8" />
                      )}
                    </button>
                  </div>
                ))}
              </div>
            </div>
          ) : activeTab === 'selectors' ? (
            /* Selectors Tab */
            <div className="space-y-4">
              <div className="flex items-center justify-between rounded-lg border border-border bg-card p-4">
                <div>
                  <h2 className="text-lg font-medium text-foreground">Search Source Selector Management</h2>
                  <p className="text-sm text-muted-foreground">
                    Edit CSS selectors and test source connectivity
                  </p>
                </div>
                <button
                  onClick={handleTestAllSources}
                  disabled={testingAll}
                  className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {testingAll ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <Play className="h-4 w-4" />
                  )}
                  Test All Sources
                </button>
              </div>
 
              <div className="space-y-3">
                {sources.map((source) => {
                  const status = getSourceStatus(source)
                  const isEditing = editingSourceId === source.id
                  const isTesting = testingSourceId === source.id
 
                  return (
                    <div
                      key={source.id}
                      className="rounded-lg border border-border bg-card p-4"
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <span className="font-medium text-foreground">{source.name}</span>
                            {status === 'working' && (
                              <CheckCircle className="h-4 w-4 text-green-500" />
                            )}
                            {status === 'broken' && (
                              <XCircle className="h-4 w-4 text-red-500" />
                            )}
                            {status === 'untested' && (
                              <HelpCircle className="h-4 w-4 text-muted-foreground" />
                            )}
                          </div>
                          <p className="text-sm text-muted-foreground">{source.host}</p>
                          {source.consecutive_failures >= 3 && (
                            <p className="mt-1 text-xs text-red-500">
                              Failed {source.consecutive_failures} times - auto-disabled
                            </p>
                          )}
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="text-xs text-muted-foreground">
                            Last tested: {formatRelativeTime(source.last_validated_at)}
                          </span>
                          <button
                            onClick={() => handleTestSource(source.id)}
                            disabled={isTesting || testingAll}
                            className="flex items-center gap-1 rounded-lg border border-border bg-background px-3 py-1.5 text-sm font-medium text-foreground transition-colors hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"
                          >
                            {isTesting ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                              <Play className="h-4 w-4" />
                            )}
                            Test
                          </button>
                        </div>
                      </div>
 
                      <div className="mt-3">
                        <label className="mb-1 block text-xs font-medium text-muted-foreground">CSS Selector</label>
                        {isEditing ? (
                          <div className="flex gap-2">
                            <input
                              type="text"
                              value={editingSelectorValue}
                              onChange={(e) => setEditingSelectorValue(e.target.value)}
                              className="flex-1 rounded-lg border border-border bg-input-background px-3 py-1.5 font-mono text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                            />
                            <button
                              onClick={handleCancelEditSelector}
                              className="rounded-lg border border-border bg-background px-3 py-1.5 text-sm font-medium text-foreground transition-colors hover:bg-muted"
                            >
                              Cancel
                            </button>
                            <button
                              onClick={handleSaveSelector}
                              disabled={savingSelector}
                              className="flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"
                            >
                              {savingSelector ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
                              Save
                            </button>
                          </div>
                        ) : (
                          <div className="flex items-center gap-2">
                            <code className="flex-1 rounded bg-muted px-3 py-1.5 font-mono text-sm text-foreground">
                              {source.result_selector || '(none)'}
                            </code>
                            <button
                              onClick={() => handleEditSelector(source)}
                              className="rounded-lg bg-primary/10 px-3 py-1.5 text-sm font-medium text-primary transition-colors hover:bg-primary/20"
                            >
                              Edit
                            </button>
                          </div>
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          ) : activeTab === 'users' ? (
            /* Users Tab */
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-lg font-medium text-foreground">User Management</h2>
                  <p className="text-sm text-muted-foreground">
                    Manage user profiles and their data
                  </p>
                </div>
                <span className="text-sm text-muted-foreground">
                  {profiles.length} profile{profiles.length !== 1 ? 's' : ''}
                </span>
              </div>
 
              <div className="space-y-3">
                {profiles.map((profile) => {
                  const isCurrent = profile.id === currentProfileId
 
                  return (
                    <div
                      key={profile.id}
                      className="flex items-center justify-between rounded-lg border border-border bg-card p-4"
                    >
                      <div className="flex items-center gap-3">
                        {/* Avatar */}
                        <div
                          className="h-10 w-10 rounded-full"
                          style={{ backgroundColor: profile.avatar_color }}
                        />
                        <div>
                          <div className="flex items-center gap-2">
                            <span className="font-medium text-foreground">{profile.name}</span>
                            {isCurrent && (
                              <span className="rounded bg-primary/10 px-2 py-0.5 text-xs text-primary">
                                Current
                              </span>
                            )}
                          </div>
                          <div className="text-sm text-muted-foreground">
                            Created {formatDate(profile.created_at)}
                          </div>
                          <div className="text-xs text-muted-foreground">
                            {profile.stats.favorites} favorites · {profile.stats.collections} collections · {profile.stats.remixes} remixes
                          </div>
                        </div>
                      </div>
 
                      <button
                        onClick={() => handleDeleteClick(profile.id)}
                        disabled={isCurrent}
                        className={cn(
                          'rounded p-2 transition-colors',
                          isCurrent
                            ? 'cursor-not-allowed text-muted-foreground/50'
                            : 'text-muted-foreground hover:bg-destructive/10 hover:text-destructive'
                        )}
                        title={isCurrent ? 'Cannot delete current profile' : 'Delete profile'}
                      >
                        <Trash2 className="h-5 w-5" />
                      </button>
                    </div>
                  )
                })}
              </div>
            </div>
          ) : activeTab === 'danger' ? (
            /* Danger Zone Tab */
            <div className="space-y-6">
              <div className="flex items-center gap-2 text-destructive">
                <AlertTriangle className="h-5 w-5" />
                <h2 className="text-lg font-medium">Danger Zone</h2>
              </div>
 
              <p className="text-sm text-muted-foreground">
                Destructive operations that cannot be undone
              </p>
 
              <div className="rounded-lg border border-destructive/50 bg-destructive/5 p-6">
                <h3 className="font-medium text-destructive">Reset Database</h3>
                <p className="mt-1 text-sm text-muted-foreground">
                  Completely reset the application to factory state
                </p>
 
                <ul className="mt-4 space-y-1 text-sm text-muted-foreground">
                  <li>• All recipes (scraped and remixed)</li>
                  <li>• All recipe images</li>
                  <li>• All user profiles</li>
                  <li>• All favorites, collections, and view history</li>
                  <li>• All cached AI data</li>
                </ul>
 
                <p className="mt-4 text-xs text-muted-foreground">
                  Search source configurations and AI prompts will be preserved.
                </p>
 
                <button
                  onClick={handleResetClick}
                  className="mt-4 rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive/90"
                >
                  Reset Database
                </button>
              </div>
            </div>
          ) : null}
        </div>
      </main>
 
      {/* Delete Profile Modal */}
      {showDeleteModal && deletePreview && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div
            className="absolute inset-0 bg-black/50"
            onClick={handleCancelDelete}
          />
          <div className="relative w-full max-w-md rounded-lg border border-border bg-card p-6 shadow-lg">
            <div className="flex items-center gap-2 text-destructive">
              <AlertTriangle className="h-5 w-5" />
              <h3 className="text-lg font-medium">Delete Profile?</h3>
            </div>
 
            <div className="mt-4 space-y-4">
              {/* Profile info */}
              <div className="flex items-center gap-3">
                <div
                  className="h-12 w-12 rounded-full"
                  style={{ backgroundColor: deletePreview.profile.avatar_color }}
                />
                <div>
                  <div className="font-medium text-foreground">{deletePreview.profile.name}</div>
                  <div className="text-sm text-muted-foreground">
                    Created {formatDate(deletePreview.profile.created_at)}
                  </div>
                </div>
              </div>
 
              {/* Data summary */}
              <div className="rounded-lg border border-border bg-muted/50 p-3">
                <div className="mb-2 text-sm font-medium text-foreground">Data to be deleted:</div>
                <ul className="space-y-1 text-sm text-muted-foreground">
                  {deletePreview.data_to_delete.remixes > 0 && (
                    <li>• {deletePreview.data_to_delete.remixes} remixed recipe{deletePreview.data_to_delete.remixes !== 1 ? 's' : ''} ({deletePreview.data_to_delete.remix_images} images)</li>
                  )}
                  {deletePreview.data_to_delete.favorites > 0 && (
                    <li>• {deletePreview.data_to_delete.favorites} favorite{deletePreview.data_to_delete.favorites !== 1 ? 's' : ''}</li>
                  )}
                  {deletePreview.data_to_delete.collections > 0 && (
                    <li>• {deletePreview.data_to_delete.collections} collection{deletePreview.data_to_delete.collections !== 1 ? 's' : ''} ({deletePreview.data_to_delete.collection_items} items)</li>
                  )}
                  {deletePreview.data_to_delete.view_history > 0 && (
                    <li>• {deletePreview.data_to_delete.view_history} view history entries</li>
                  )}
                  {(deletePreview.data_to_delete.scaling_cache > 0 || deletePreview.data_to_delete.discover_cache > 0) && (
                    <li>• Cached AI data</li>
                  )}
                  {deletePreview.data_to_delete.remixes === 0 &&
                   deletePreview.data_to_delete.favorites === 0 &&
                   deletePreview.data_to_delete.collections === 0 &&
                   deletePreview.data_to_delete.view_history === 0 &&
                   deletePreview.data_to_delete.scaling_cache === 0 &&
                   deletePreview.data_to_delete.discover_cache === 0 && (
                    <li>• No associated data</li>
                  )}
                </ul>
              </div>
 
              {/* Warning */}
              <div className="text-sm text-destructive">
                This action cannot be undone. All data will be permanently deleted.
              </div>
            </div>
 
            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={handleCancelDelete}
                className="rounded-lg border border-border bg-background px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-muted"
              >
                Cancel
              </button>
              <button
                onClick={handleConfirmDelete}
                disabled={deleting}
                className="flex items-center gap-2 rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive/90 disabled:cursor-not-allowed disabled:opacity-50"
              >
                {deleting ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Trash2 className="h-4 w-4" />
                )}
                Delete Profile
              </button>
            </div>
          </div>
        </div>
      )}
 
      {/* Database Reset Modal */}
      {showResetModal && resetPreview && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div
            className="absolute inset-0 bg-black/50"
            onClick={handleCancelReset}
          />
          <div className="relative w-full max-w-md rounded-lg border border-border bg-card p-6 shadow-lg">
            {resetStep === 1 ? (
              <>
                <div className="flex items-center gap-2 text-destructive">
                  <AlertTriangle className="h-5 w-5" />
                  <h3 className="text-lg font-medium">Reset Database?</h3>
                </div>
 
                <div className="mt-4 space-y-4">
                  <p className="text-sm text-foreground">
                    This will permanently delete ALL data from the application:
                  </p>
 
                  <div className="rounded-lg border border-border bg-muted/50 p-3">
                    <ul className="space-y-1 text-sm text-muted-foreground">
                      <li>• {resetPreview.data_counts.profiles} profiles</li>
                      <li>• {resetPreview.data_counts.recipes} recipes ({resetPreview.data_counts.recipe_images} images)</li>
                      <li>• {resetPreview.data_counts.favorites} favorites</li>
                      <li>• {resetPreview.data_counts.collections} collections</li>
                      <li>• {resetPreview.data_counts.view_history} view history entries</li>
                      <li>• {resetPreview.data_counts.ai_suggestions + resetPreview.data_counts.serving_adjustments} cached AI entries</li>
                    </ul>
                  </div>
 
                  <p className="text-sm font-medium text-destructive">
                    This action cannot be undone.
                  </p>
                </div>
 
                <div className="mt-6 flex justify-end gap-3">
                  <button
                    onClick={handleCancelReset}
                    className="rounded-lg border border-border bg-background px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-muted"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleResetContinue}
                    className="rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive/90"
                  >
                    I understand, continue
                  </button>
                </div>
              </>
            ) : (
              <>
                <div className="flex items-center gap-2 text-destructive">
                  <AlertTriangle className="h-5 w-5" />
                  <h3 className="text-lg font-medium">Confirm Reset</h3>
                </div>
 
                <div className="mt-4 space-y-4">
                  <p className="text-sm text-foreground">
                    Type <code className="rounded bg-muted px-1 font-mono">RESET</code> to confirm:
                  </p>
 
                  <input
                    type="text"
                    value={resetConfirmText}
                    onChange={(e) => setResetConfirmText(e.target.value)}
                    placeholder="Type RESET"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                  />
                </div>
 
                <div className="mt-6 flex justify-end gap-3">
                  <button
                    onClick={handleResetBack}
                    className="rounded-lg border border-border bg-background px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-muted"
                  >
                    Back
                  </button>
                  <button
                    onClick={handleConfirmReset}
                    disabled={resetConfirmText !== 'RESET' || resetting}
                    className="flex items-center gap-2 rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive/90 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    {resetting && <Loader2 className="h-4 w-4 animate-spin" />}
                    Reset Database
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
 
← Back to Dashboard