import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  Pressable,
  ActivityIndicator,
  Linking,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { Button, ButtonText } from '@/components/ui/button';
import { colors, typography, shadow, radius } from '@/constants/theme';
import {
  getUserProfile,
  getSubscriptionStatus,
  updateNotificationTime,
  updateUserProfile,
  type UserProfile,
  type SubscriptionStatus,
  type UserRole,
  type UnitType,
} from '@/lib/supabase';
// Same option sets the onboarding screens render, so a value chosen there and
// a value changed here can never be labelled differently.
import {
  ROLE_OPTIONS,
  UNIT_OPTIONS,
  roleLabel,
  unitLabel,
  type ProfileOption,
} from '@/constants/profileOptions';
import {
  checkProEntitlement,
  restoreProPurchases,
  presentProPaywall,
} from '@/lib/revenuecat';
import { applyNotificationSchedule, requestPushPermission } from '@/lib/onesignal';

// Hosted legal pages. Apple Guideline 3.1.2(c) requires both to be reachable
// from inside the app, not just from the App Store listing.
const TERMS_URL = 'https://vinay2214-cloud.github.io/preprounds/TERMS.html';
const PRIVACY_URL = 'https://vinay2214-cloud.github.io/preprounds/PRIVACY.html';

interface TimeOption {
  value: string | null;
  label: string;
  sublabel: string;
}

const TIME_OPTIONS: TimeOption[] = [
  {
    value: '07:00',
    label: '7:00 AM',
    sublabel: 'Before day shift huddle',
  },
  {
    value: '12:00',
    label: '12:00 PM',
    sublabel: 'Midday reset or break',
  },
  {
    value: '19:00',
    label: '7:00 PM',
    sublabel: 'Before night shift report',
  },
  {
    value: null,
    label: 'Paused',
    sublabel: 'Turn off daily practice reminders',
  },
];

/**
 * Settings Screen
 * 03-DESIGN-SYSTEM-AND-SCREENS.md §5.8 & AGENTS.md Step 11
 *
 * Requirements:
 * - Notification time picker (writes user_profiles.notification_time)
 * - "Restore purchases" button (calls Purchases.restorePurchases() via restoreProPurchases())
 * - Disclaimer text block: "PrepRounds is a communication-practice tool. It is not medical, legal, or HR advice."
 * - Brief inline confirmation for form-saves (no full-screen loading/error states)
 */
export default function SettingsScreen() {
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [subStatus, setSubStatus] = useState<SubscriptionStatus | null>(null);
  const [isPro, setIsPro] = useState<boolean>(false);
  const [selectedTime, setSelectedTime] = useState<string | null>('07:00');

  const [savingTime, setSavingTime] = useState<boolean>(false);
  const [timeConfirmation, setTimeConfirmation] = useState<string | null>(null);
  // Which profile row is expanded for editing, if any. Only one at a time —
  // this is a settings edit, not a re-onboarding flow.
  const [editingField, setEditingField] = useState<'role' | 'unit' | null>(null);
  const [savingProfile, setSavingProfile] = useState<boolean>(false);
  const [profileConfirmation, setProfileConfirmation] = useState<string | null>(null);

  const [restoring, setRestoring] = useState<boolean>(false);
  const [restoreMessage, setRestoreMessage] = useState<{
    text: string;
    isError: boolean;
  } | null>(null);

  // Load initial settings and subscription data
  useEffect(() => {
    async function loadSettings() {
      try {
        const [userProf, sub, proActive] = await Promise.all([
          getUserProfile(),
          getSubscriptionStatus(),
          checkProEntitlement(),
        ]);

        if (userProf) {
          setProfile(userProf);
          setSelectedTime(userProf.notification_time);
        }
        setSubStatus(sub);
        setIsPro(proActive);
      } catch (err) {
        console.error('[Settings] Error loading initial settings:', err);
      }
    }
    loadSettings();
  }, []);

  // Handle updating reminder time
  const handleSelectTime = async (time: string | null) => {
    if (savingTime || time === selectedTime) return;
    setSelectedTime(time);
    setSavingTime(true);
    setTimeConfirmation(null);

    try {
      await updateNotificationTime(time);

      // US-8 AC2: the change has to take effect without a reinstall, so the
      // picker drives OneSignal too — not just the Supabase column. A time
      // opts the push subscription in and re-tags the device into that
      // campaign's segment; "Paused" clears the tag and opts out, which is
      // what actually cancels the nudge.
      //
      // Someone who chose "Maybe later" during onboarding never saw the OS
      // dialog, so re-enabling here has to ask for permission before the
      // opt-in can mean anything.
      if (time) {
        await requestPushPermission();
      }
      await applyNotificationSchedule(time);

      const label = TIME_OPTIONS.find((t) => t.value === time)?.label ?? 'Updated';
      setTimeConfirmation(
        time ? `Daily practice reminder set to ${label}` : 'Daily practice reminders paused'
      );
      setTimeout(() => setTimeConfirmation(null), 3500);
    } catch (err) {
      console.error('[Settings] Error updating notification time:', err);
      setTimeConfirmation('Failed to update reminder. Please try again.');
      setTimeout(() => setTimeConfirmation(null), 3500);
    } finally {
      setSavingTime(false);
    }
  };

  // Handle changing role or clinical unit. Mirrors handleSelectTime: write
  // through, confirm inline, no modal.
  const handleSelectProfileValue = async (
    field: 'role' | 'unit',
    value: UserRole | UnitType
  ) => {
    if (savingProfile) return;

    const current = field === 'role' ? profile?.role : profile?.unit_type;
    if (current === value) {
      setEditingField(null);
      return;
    }

    setSavingProfile(true);
    setProfileConfirmation(null);

    try {
      const updated =
        field === 'role'
          ? await updateUserProfile({ role: value as UserRole })
          : await updateUserProfile({ unit_type: value as UnitType });

      setProfile(updated);
      setEditingField(null);
      setProfileConfirmation(
        field === 'role'
          ? `Role updated to ${roleLabel(updated.role)}`
          : `Clinical unit updated to ${unitLabel(updated.unit_type)}`
      );
      setTimeout(() => setProfileConfirmation(null), 3500);
    } catch (err) {
      console.error('[Settings] Error updating nurse profile:', err);
      // lib/retry.ts has already retried once on a dropped connection by the
      // time this runs, so a failure here is worth telling the user about.
      setProfileConfirmation("Couldn't save — check your connection and try again");
      setTimeout(() => setProfileConfirmation(null), 3500);
    } finally {
      setSavingProfile(false);
    }
  };

  // Opens the device mail client. No in-app form and no Supabase write —
  // the mail app is the whole feature. If the device has no mail client
  // configured, openURL rejects; log it rather than surfacing a modal.
  const handleSendFeedback = async () => {
    const url = 'mailto:vinayjanyavula256@gmail.com?subject=' +
      encodeURIComponent('PrepRounds Feedback');
    try {
      await Linking.openURL(url);
    } catch (err) {
      console.error('[Settings] Could not open mail client:', err);
    }
  };

  // Opens a hosted legal page in the system browser. Same failure handling as
  // handleSendFeedback: if no handler is available, log rather than modal.
  const handleOpenLegalLink = async (url: string) => {
    try {
      await Linking.openURL(url);
    } catch (err) {
      console.error('[Settings] Could not open legal link:', url, err);
    }
  };

  // Handle restoring purchases
  const handleRestorePurchases = async () => {
    if (restoring) return;
    setRestoring(true);
    setRestoreMessage(null);

    try {
      const proActive = await restoreProPurchases();
      setIsPro(proActive);
      if (proActive) {
        setRestoreMessage({
          text: 'Purchases restored. Pro subscription is active!',
          isError: false,
        });
      } else {
        setRestoreMessage({
          text: 'No active Pro subscription found for this Apple/Google account.',
          isError: false,
        });
      }
    } catch (err) {
      console.error('[Settings] Error restoring purchases:', err);
      setRestoreMessage({
        text: 'Unable to restore purchases. Please check your connection.',
        isError: true,
      });
    } finally {
      setRestoring(false);
      setTimeout(() => setRestoreMessage(null), 4000);
    }
  };

  // Handle manual upgrade trigger
  const handleUpgrade = async () => {
    const { purchased } = await presentProPaywall();
    if (purchased) {
      setIsPro(true);
      const sub = await getSubscriptionStatus();
      setSubStatus(sub);
    }
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
      <ScrollView
        className="flex-1 px-5"
        contentContainerStyle={{ paddingBottom: 40 }}
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View className="pt-3 pb-5">
          <Text
            style={{
              fontFamily: typography.h1.fontFamily,
              fontSize: 26,
              lineHeight: 32,
              color: colors.textPrimary,
            }}
          >
            Settings
          </Text>
          <Text
            style={{
              fontFamily: typography.body.fontFamily,
              fontSize: 14,
              color: colors.textSecondary,
              marginTop: 2,
            }}
          >
            Manage notifications, practice cadence, and subscription
          </Text>
        </View>

        {/* Section 1: Daily Practice Reminders */}
        <View className="mb-6">
          <Text
            style={{
              fontFamily: typography.h2.fontFamily,
              fontSize: 18,
              lineHeight: 24,
              color: colors.textPrimary,
              marginBottom: 4,
            }}
          >
            Daily Practice Reminder
          </Text>
          <Text
            style={{
              fontFamily: typography.body.fontFamily,
              fontSize: 14,
              lineHeight: 20,
              color: colors.textSecondary,
              marginBottom: 12,
            }}
          >
            Choose when you want a quiet nudge for your 3–5 minute scenario practice.
          </Text>

          {/* Inline Save Confirmation Banner */}
          {timeConfirmation && (
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: '#EDF5ED',
                borderWidth: 1,
                borderColor: colors.success,
                borderRadius: radius.md,
                paddingHorizontal: 12,
                paddingVertical: 8,
                marginBottom: 12,
              }}
              accessible={true}
              accessibilityRole="alert"
            >
              <Ionicons
                name="checkmark-circle"
                size={18}
                color={colors.success}
                style={{ marginRight: 8 }}
              />
              <Text
                style={{
                  fontFamily: typography.caption.fontFamily,
                  fontSize: 13,
                  color: colors.textPrimary,
                  flex: 1,
                }}
              >
                {timeConfirmation}
              </Text>
            </View>
          )}

          {/* Time Picker Radio Group */}
          <View className="gap-2.5">
            {TIME_OPTIONS.map((opt) => {
              const isSelected = selectedTime === opt.value;
              return (
                <Pressable
                  key={String(opt.value)}
                  onPress={() => handleSelectTime(opt.value)}
                  disabled={savingTime}
                  accessibilityRole="radio"
                  accessibilityState={{ selected: isSelected }}
                  accessibilityLabel={`${opt.label}, ${opt.sublabel}`}
                  style={[
                    {
                      minHeight: 52,
                      borderRadius: radius.md,
                      backgroundColor: colors.surface,
                      borderWidth: 1.5,
                      borderColor: isSelected ? colors.primary : colors.border,
                      paddingHorizontal: 16,
                      paddingVertical: 10,
                      flexDirection: 'row',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                    },
                    shadow.card,
                  ]}
                >
                  <View className="flex-1 pr-2">
                    <Text
                      style={{
                        fontFamily: typography.bodyBold.fontFamily,
                        fontSize: 15,
                        color: isSelected ? colors.primary : colors.textPrimary,
                      }}
                    >
                      {opt.label}
                    </Text>
                    <Text
                      style={{
                        fontFamily: typography.caption.fontFamily,
                        fontSize: 12,
                        color: colors.textSecondary,
                        marginTop: 1,
                      }}
                    >
                      {opt.sublabel}
                    </Text>
                  </View>

                  {/* Radio Dot Indicator */}
                  <View
                    style={{
                      width: 20,
                      height: 20,
                      borderRadius: 10,
                      borderWidth: 2,
                      borderColor: isSelected ? colors.primary : colors.disabled,
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    {isSelected && (
                      <View
                        style={{
                          width: 10,
                          height: 10,
                          borderRadius: 5,
                          backgroundColor: colors.primary,
                        }}
                      />
                    )}
                  </View>
                </Pressable>
              );
            })}
          </View>
        </View>

        {/* Section 2: Subscription & Purchases */}
        <View className="mb-6">
          <Text
            style={{
              fontFamily: typography.h2.fontFamily,
              fontSize: 18,
              lineHeight: 24,
              color: colors.textPrimary,
              marginBottom: 4,
            }}
          >
            Membership & Access
          </Text>

          <View
            style={[
              {
                backgroundColor: colors.surface,
                borderRadius: radius.lg,
                padding: 18,
                borderWidth: 1,
                borderColor: colors.border,
                marginBottom: 14,
              },
              shadow.card,
            ]}
          >
            {/* Membership Header */}
            <View className="flex-row items-center justify-between mb-2">
              <Text
                style={{
                  fontFamily: typography.bodyBold.fontFamily,
                  fontSize: 16,
                  color: colors.textPrimary,
                }}
              >
                Current Plan
              </Text>
              <View
                style={{
                  backgroundColor: isPro
                    ? 'rgba(31, 111, 99, 0.12)'
                    : 'rgba(224, 122, 95, 0.12)',
                  paddingHorizontal: 10,
                  paddingVertical: 3,
                  borderRadius: radius.pill,
                }}
              >
                <Text
                  style={{
                    fontFamily: typography.caption.fontFamily,
                    fontSize: 12,
                    fontWeight: '700',
                    color: isPro ? colors.primary : colors.accent,
                  }}
                >
                  {isPro ? 'Pro Unlimited' : 'Free Tier'}
                </Text>
              </View>
            </View>

            <Text
              style={{
                fontFamily: typography.caption.fontFamily,
                fontSize: 13,
                lineHeight: 18,
                color: colors.textSecondary,
                marginBottom: 16,
              }}
            >
              {isPro
                ? 'You have unlimited access to all scenario roleplays and structured debrief evaluations.'
                : `Free tier includes 3 total practice sessions across all scenarios (${
                    subStatus?.free_sessions_used ?? 0
                  } used).`}
            </Text>

            {/* Upgrade CTA if not Pro */}
            {!isPro && (
              <Button
                size="default"
                onPress={handleUpgrade}
                accessibilityRole="button"
                accessibilityLabel="Upgrade to Pro unlimited"
                style={{
                  minHeight: 44,
                  borderRadius: radius.pill,
                  backgroundColor: colors.primary,
                  marginBottom: 12,
                }}
              >
                <ButtonText
                  style={{
                    fontFamily: typography.bodyBold.fontFamily,
                    fontSize: 14,
                    color: '#FFFFFF',
                  }}
                >
                  Upgrade to Pro
                </ButtonText>
              </Button>
            )}

            {/* Restore Purchases Button per §5.8 */}
            <Button
              size="default"
              onPress={handleRestorePurchases}
              disabled={restoring}
              accessibilityRole="button"
              accessibilityLabel="Restore purchases"
              style={{
                minHeight: 44,
                borderRadius: radius.pill,
                backgroundColor: 'transparent',
                borderWidth: 1,
                borderColor: colors.border,
              }}
            >
              {restoring ? (
                <ActivityIndicator size="small" color={colors.primary} />
              ) : (
                <ButtonText
                  style={{
                    fontFamily: typography.body.fontFamily,
                    fontSize: 14,
                    color: colors.textPrimary,
                  }}
                >
                  Restore Purchases
                </ButtonText>
              )}
            </Button>
          </View>

          {/* Restore Feedback Banner */}
          {restoreMessage && (
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: restoreMessage.isError ? '#FFF4E5' : '#EDF5ED',
                borderWidth: 1,
                borderColor: restoreMessage.isError ? colors.alert : colors.success,
                borderRadius: radius.md,
                paddingHorizontal: 12,
                paddingVertical: 10,
              }}
              accessible={true}
              accessibilityRole="alert"
            >
              <Ionicons
                name={restoreMessage.isError ? 'alert-circle' : 'checkmark-circle'}
                size={18}
                color={restoreMessage.isError ? colors.alert : colors.success}
                style={{ marginRight: 8 }}
              />
              <Text
                style={{
                  fontFamily: typography.caption.fontFamily,
                  fontSize: 13,
                  color: colors.textPrimary,
                  flex: 1,
                }}
              >
                {restoreMessage.text}
              </Text>
            </View>
          )}
        </View>

        {/* Section 3: Nurse Profile (editable) */}
        {profile && (
          <View className="mb-6">
            <Text
              style={{
                fontFamily: typography.h2.fontFamily,
                fontSize: 18,
                lineHeight: 24,
                color: colors.textPrimary,
                marginBottom: 2,
              }}
            >
              Nurse Profile
            </Text>
            <Text
              style={{
                fontFamily: typography.caption.fontFamily,
                fontSize: 13,
                color: colors.textSecondary,
                marginBottom: 10,
              }}
            >
              Keep this current if you change roles or transfer units. Past sessions
              and their debriefs stay exactly as they were.
            </Text>

            {profileConfirmation && (
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  backgroundColor: '#EDF5ED',
                  borderWidth: 1,
                  borderColor: colors.success,
                  borderRadius: radius.md,
                  paddingHorizontal: 12,
                  paddingVertical: 8,
                  marginBottom: 12,
                }}
                accessible={true}
                accessibilityRole="alert"
              >
                <Ionicons
                  name="checkmark-circle"
                  size={18}
                  color={colors.success}
                  style={{ marginRight: 8 }}
                />
                <Text
                  style={{
                    fontFamily: typography.caption.fontFamily,
                    fontSize: 13,
                    color: colors.textPrimary,
                    flex: 1,
                  }}
                >
                  {profileConfirmation}
                </Text>
              </View>
            )}

            <View
              style={[
                {
                  backgroundColor: colors.surface,
                  borderRadius: radius.lg,
                  padding: 16,
                  borderWidth: 1,
                  borderColor: colors.border,
                },
                shadow.card,
              ]}
            >
              {(
                [
                  {
                    field: 'role' as const,
                    rowLabel: 'Role',
                    current: roleLabel(profile.role),
                    options: ROLE_OPTIONS as ProfileOption<UserRole | UnitType>[],
                    selected: profile.role as UserRole | UnitType,
                  },
                  {
                    field: 'unit' as const,
                    rowLabel: 'Clinical Unit',
                    current: unitLabel(profile.unit_type),
                    options: UNIT_OPTIONS as ProfileOption<UserRole | UnitType>[],
                    selected: profile.unit_type as UserRole | UnitType,
                  },
                ]
              ).map((row, rowIndex) => {
                const isOpen = editingField === row.field;

                return (
                  <View
                    key={row.field}
                    style={{
                      borderTopWidth: rowIndex === 0 ? 0 : 1,
                      borderTopColor: colors.border,
                      paddingTop: rowIndex === 0 ? 0 : 10,
                      marginTop: rowIndex === 0 ? 0 : 10,
                    }}
                  >
                    <Pressable
                      onPress={() => setEditingField(isOpen ? null : row.field)}
                      disabled={savingProfile}
                      accessibilityRole="button"
                      accessibilityState={{ expanded: isOpen }}
                      accessibilityLabel={`${row.rowLabel}: ${row.current}. Tap to change.`}
                      hitSlop={{ top: 6, bottom: 6, left: 6, right: 6 }}
                      style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        minHeight: 32,
                      }}
                    >
                      <Text
                        style={{
                          fontFamily: typography.caption.fontFamily,
                          fontSize: 13,
                          color: colors.textSecondary,
                        }}
                      >
                        {row.rowLabel}
                      </Text>

                      <View style={{ flexDirection: 'row', alignItems: 'center', flexShrink: 1 }}>
                        <Text
                          numberOfLines={1}
                          style={{
                            fontFamily: typography.bodyBold.fontFamily,
                            fontSize: 13,
                            color: isOpen ? colors.primary : colors.textPrimary,
                            marginRight: 6,
                          }}
                        >
                          {row.current}
                        </Text>
                        <Ionicons
                          name={isOpen ? 'chevron-up' : 'chevron-down'}
                          size={16}
                          color={isOpen ? colors.primary : colors.textSecondary}
                        />
                      </View>
                    </Pressable>

                    {isOpen && (
                      <View className="gap-2" style={{ marginTop: 10 }}>
                        {row.options.map((opt) => {
                          const isSelected = row.selected === opt.value;
                          return (
                            <Pressable
                              key={String(opt.value)}
                              onPress={() => handleSelectProfileValue(row.field, opt.value)}
                              disabled={savingProfile}
                              accessibilityRole="radio"
                              accessibilityState={{ selected: isSelected }}
                              accessibilityLabel={opt.label}
                              accessibilityHint={opt.description}
                              style={{
                                minHeight: 52,
                                borderRadius: radius.md,
                                backgroundColor: colors.background,
                                borderWidth: 1.5,
                                borderColor: isSelected ? colors.primary : colors.border,
                                paddingHorizontal: 12,
                                paddingVertical: 10,
                                flexDirection: 'row',
                                alignItems: 'center',
                                justifyContent: 'space-between',
                                opacity: savingProfile ? 0.6 : 1,
                              }}
                            >
                              <View className="flex-1 pr-2">
                                <Text
                                  style={{
                                    fontFamily: typography.bodyBold.fontFamily,
                                    fontSize: 15,
                                    color: isSelected ? colors.primary : colors.textPrimary,
                                  }}
                                >
                                  {opt.label}
                                </Text>
                                <Text
                                  numberOfLines={2}
                                  style={{
                                    fontFamily: typography.caption.fontFamily,
                                    fontSize: 12,
                                    color: colors.textSecondary,
                                    marginTop: 1,
                                  }}
                                >
                                  {opt.description}
                                </Text>
                              </View>

                              <View
                                style={{
                                  width: 20,
                                  height: 20,
                                  borderRadius: 10,
                                  borderWidth: 2,
                                  borderColor: isSelected ? colors.primary : colors.disabled,
                                  alignItems: 'center',
                                  justifyContent: 'center',
                                }}
                              >
                                {isSelected && (
                                  <View
                                    style={{
                                      width: 10,
                                      height: 10,
                                      borderRadius: 5,
                                      backgroundColor: colors.primary,
                                    }}
                                  />
                                )}
                              </View>
                            </Pressable>
                          );
                        })}
                      </View>
                    )}
                  </View>
                );
              })}
            </View>
          </View>
        )}

        {/* Section 4: Send Feedback */}
        <View className="mb-6">
          <Pressable
            onPress={handleSendFeedback}
            accessibilityRole="button"
            accessibilityLabel="Send feedback"
            accessibilityHint="Opens your mail app with a message to the PrepRounds team"
            style={[
              {
                backgroundColor: colors.surface,
                borderRadius: radius.lg,
                paddingHorizontal: 16,
                paddingVertical: 14,
                borderWidth: 1,
                borderColor: colors.border,
                flexDirection: 'row',
                alignItems: 'center',
                minHeight: 52,
              },
              shadow.card,
            ]}
          >
            <Ionicons
              name="mail-outline"
              size={18}
              color={colors.primary}
              style={{ marginRight: 10 }}
            />
            <View className="flex-1 pr-2">
              <Text
                style={{
                  fontFamily: typography.bodyBold.fontFamily,
                  fontSize: 15,
                  color: colors.textPrimary,
                }}
              >
                Send Feedback
              </Text>
              <Text
                style={{
                  fontFamily: typography.caption.fontFamily,
                  fontSize: 12,
                  color: colors.textSecondary,
                  marginTop: 1,
                }}
              >
                Tell us what is working or what is not
              </Text>
            </View>
            <Ionicons name="chevron-forward" size={16} color={colors.textSecondary} />
          </Pressable>
        </View>

        {/* Section 5: How PrepRounds Coaches */}
        <View className="mb-6">
          <Text
            style={{
              fontFamily: typography.h2.fontFamily,
              fontSize: 18,
              lineHeight: 24,
              color: colors.textPrimary,
              marginBottom: 2,
            }}
          >
            How PrepRounds Coaches
          </Text>
          <Text
            style={{
              fontFamily: typography.caption.fontFamily,
              fontSize: 13,
              color: colors.textSecondary,
              marginBottom: 10,
            }}
          >
            Where the scenarios and feedback come from.
          </Text>

          <View
            style={[
              {
                backgroundColor: colors.surface,
                borderRadius: radius.lg,
                padding: 16,
                borderWidth: 1,
                borderColor: colors.border,
              },
              shadow.card,
            ]}
          >
            <Text
              style={{
                fontFamily: typography.body.fontFamily,
                fontSize: 14,
                lineHeight: 21,
                color: colors.textPrimary,
              }}
            >
              The scenarios you practise and the feedback you get back are built on
              established nursing leadership and communication frameworks — the AACN
              communication competency standards, the AONL Nurse Leader Core
              Competencies, and the TeamSTEPPS communication tools from AHRQ, including
              DESC and CUS.
            </Text>

            <Text
              style={{
                fontFamily: typography.body.fontFamily,
                fontSize: 14,
                lineHeight: 21,
                color: colors.textPrimary,
                marginTop: 12,
              }}
            >
              In practice that means the personas push back the way real colleagues do,
              and the debrief looks at the things those frameworks care about: whether
              you acknowledged the other person, how clearly you named the issue, how
              you handled resistance, and whether the conversation reached a concrete
              next step.
            </Text>

            <View
              style={{
                borderTopWidth: 1,
                borderTopColor: colors.border,
                marginTop: 14,
                paddingTop: 12,
              }}
            >
              <Text
                style={{
                  fontFamily: typography.body.fontFamily,
                  fontSize: 14,
                  lineHeight: 21,
                  color: colors.textPrimary,
                }}
              >
                This is not a certification, and it does not replace your
                organisation's policy, your own clinical judgement, or mentorship from
                someone who knows your unit. It is a private space to rehearse the
                human side of a hard conversation before you have it for real.
              </Text>
            </View>
          </View>
        </View>

        {/* Section 6: Legal (Apple Guideline 3.1.2(c)) */}
        <View className="mb-6">
          {(
            [
              {
                key: 'terms' as const,
                url: TERMS_URL,
                icon: 'document-text-outline' as const,
                title: 'Terms of Use',
                subtitle: 'The agreement you practise under',
              },
              {
                key: 'privacy' as const,
                url: PRIVACY_URL,
                icon: 'lock-closed-outline' as const,
                title: 'Privacy Policy',
                subtitle: 'What we store and what we never do',
              },
            ]
          ).map((row, rowIndex) => (
            <Pressable
              key={row.key}
              onPress={() => handleOpenLegalLink(row.url)}
              accessibilityRole="link"
              accessibilityLabel={row.title}
              accessibilityHint="Opens in your browser"
              style={[
                {
                  backgroundColor: colors.surface,
                  borderRadius: radius.lg,
                  paddingHorizontal: 16,
                  paddingVertical: 14,
                  borderWidth: 1,
                  borderColor: colors.border,
                  flexDirection: 'row',
                  alignItems: 'center',
                  minHeight: 52,
                  marginTop: rowIndex === 0 ? 0 : 10,
                },
                shadow.card,
              ]}
            >
              <Ionicons
                name={row.icon}
                size={18}
                color={colors.primary}
                style={{ marginRight: 10 }}
              />
              <View className="flex-1 pr-2">
                <Text
                  style={{
                    fontFamily: typography.bodyBold.fontFamily,
                    fontSize: 15,
                    color: colors.textPrimary,
                  }}
                >
                  {row.title}
                </Text>
                <Text
                  style={{
                    fontFamily: typography.caption.fontFamily,
                    fontSize: 12,
                    color: colors.textSecondary,
                    marginTop: 1,
                  }}
                >
                  {row.subtitle}
                </Text>
              </View>
              <Ionicons name="chevron-forward" size={16} color={colors.textSecondary} />
            </Pressable>
          ))}
        </View>

        {/* Section 7: Mandatory Disclaimer Block per §5.8 */}
        <View
          style={{
            backgroundColor: 'rgba(38, 49, 58, 0.04)',
            borderRadius: radius.md,
            padding: 16,
            borderWidth: 1,
            borderColor: colors.border,
            marginTop: 4,
          }}
          accessible={true}
          accessibilityRole="text"
        >
          <View className="flex-row items-start">
            <Ionicons
              name="information-circle-outline"
              size={18}
              color={colors.textSecondary}
              style={{ marginRight: 8, marginTop: 1 }}
            />
            <Text
              style={{
                fontFamily: typography.caption.fontFamily,
                fontSize: 12,
                lineHeight: 18,
                color: colors.textSecondary,
                flex: 1,
              }}
            >
              PrepRounds is a communication-practice tool. It is not medical, legal, or HR advice.
            </Text>
          </View>
        </View>

        {/* Version Footer */}
        <View className="items-center mt-6">
          <Text
            style={{
              fontFamily: typography.caption.fontFamily,
              fontSize: 11,
              color: colors.disabled,
            }}
          >
            PrepRounds v1.0.0 · RevenueCat Shipaton 2026
          </Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}
