import { useEffect, useMemo, useRef, useState } from 'react';

type GoogleCredentialResponse = {
  credential?: string;
};

type GoogleAccountsIdApi = {
  initialize: (options: { client_id: string; callback: (response: GoogleCredentialResponse) => void }) => void;
  renderButton: (
    parent: HTMLElement,
    options: {
      theme?: 'outline' | 'filled_blue' | 'filled_black';
      size?: 'large' | 'medium' | 'small';
      text?: 'signin_with' | 'signup_with' | 'continue_with';
      shape?: 'rectangular' | 'pill' | 'circle' | 'square';
      logo_alignment?: 'left' | 'center';
      width?: string;
    },
  ) => void;
};

declare global {
  interface Window {
    google?: {
      accounts: {
        id: GoogleAccountsIdApi;
      };
    };
  }
}

type SavingsPlanKey = 'Daily' | 'Weekly' | 'Monthly' | 'Flexible';
type ActivityType = 'Deposit' | 'Buy Gold' | 'Sell Gold' | 'Withdraw' | 'Transfer';
type SectionKey =
  | 'dashboard'
  | 'savings'
  | 'investment'
  | 'wallet'
  | 'transactions'
  | 'verification'
  | 'support'
  | 'marketplace'
  | 'portfolio'
  | 'myInvestments'
  | 'roiPayments'
  | 'reinvestmentHistory'
  | 'escrow'
  | 'reports'
  | 'messages'
  | 'supportCenter'
  | 'settings';
type PaymentMethod = 'Mobile Money' | 'Visa Card' | 'Mastercard';
type AuthMode = 'signup' | 'login';

type Activity = {
  id: number;
  label: string;
  detail: string;
  amount: string;
  type: ActivityType;
  time: string;
};

type Listing = {
  seller: string;
  country: string;
  purity: string;
  quantity: string;
  price: string;
  delivery: string;
  verification: string;
};

type ChatMessage = {
  id: number;
  role: 'user' | 'assistant';
  text: string;
  time: string;
};

type Profile = {
  fullName: string;
  email: string;
  phone: string;
  country: string;
  role: string;
  avatarUrl?: string;
};

type Account = {
  id: string;
  name: string;
  createdAt: string;
  profile: Profile;
  walletCash: number;
  pendingBalance: number;
  goldGrams: number;
  selectedPlan: SavingsPlanKey;
  activities: Activity[];
  selectedFunding: 'Mobile Money' | 'Bank Account';
  chatMessages: ChatMessage[];
};

type AppState = {
  activeAccountId: string;
  accounts: Account[];
};

type ServerNotification = {
  id: string;
  type: string;
  message: string;
  read: boolean;
  createdAt: string;
};

type SecurityEmail = {
  id: string;
  subject: string;
  body: string;
  createdAt: string;
};

type ServerTransaction = {
  id: string;
  type: string;
  amount: number;
  status: string;
  method?: string;
  channel?: string;
  destination?: string;
  account?: string;
  createdAt: string;
};

type ServerOrder = {
  id: string;
  type: string;
  status: string;
  amount: number;
  reference?: string;
  createdAt: string;
};

type VerificationSnapshot = {
  phoneVerification: {
    status: string;
    phone: string;
    lastSentAt: string | null;
    verifiedAt: string | null;
  };
  documents: {
    status: string;
    submittedAt: string | null;
    idCardFront: string | null;
    idCardBack: string | null;
    passport: string | null;
  };
  antiFraud: {
    status: string;
    score: number;
    flags: string[];
    reviewedAt: string | null;
  };
  kyc: {
    status: string;
    submittedAt: string | null;
    verifiedAt: string | null;
    notes: string;
  };
};

type InvestmentRoiPayment = {
  id: string;
  month: number;
  amount: number;
  paidAt: string;
  paymentDate: string;
  transactionReference: string;
};

type InvestmentJourney = {
  id: string;
  productName: string;
  status: string;
  minimumInvestment: number;
  validationPeriodDays: number;
  contractDurationMonths: number;
  contractDurationLabel: string;
  investmentCertificateNumber: string;
  investmentStartDate: string | null;
  registrationCompletedAt: string | null;
  kycStatus: string;
  kycCompletedAt: string | null;
  applicationStatus: string;
  applicationSubmittedAt: string | null;
  validationStatus: string;
  validatedAt: string | null;
  agreementStatus: string;
  agreementSignedAt: string | null;
  fundingStatus: string;
  fundedAt: string | null;
  maturityStatus: string;
  maturityReachedAt: string | null;
  maturityDecision: string | null;
  maturityDecidedAt: string | null;
  validationEndsAt: string | null;
  nextRoiPaymentDate: string | null;
  investmentMaturityDate: string | null;
  principal: number;
  currency: string;
  monthlyDistribution: number;
  termMonths: number;
  monthsElapsed: number;
  monthlyRoiRate: number;
  roiPayments: InvestmentRoiPayment[];
  totalRoiPaid: number;
  applicant: Profile;
};

type DashboardSnapshot = {
  profile: Profile;
  wallet: {
    cash: number;
    pending: number;
    goldGrams: number;
  };
  storage: {
    insured: boolean;
    provider: string;
    coverage: string;
  };
  verification: VerificationSnapshot;
  twoFactor?: {
    enabled: boolean;
    method: 'email' | 'sms';
    lastVerifiedAt: string | null;
  };
  securityStandards?: Array<{ name: string; status: string; detail: string }>;
  transactionStorage?: {
    model: string;
    location: string;
    retention: string;
    integrity: string;
  };
  backupStatus?: {
    retention: number;
    location: string;
    lastBackupAt: string | null;
    lastBackupFile: string | null;
  };
  securityEmails: SecurityEmail[];
  notifications: ServerNotification[];
  transactions: ServerTransaction[];
  orders: ServerOrder[];
  investmentJourney: InvestmentJourney;
  price: {
    goldOunce: number;
    updatedAt: string;
    source: string;
  };
  insuredStorageNote: string;
};

type AuthDraft = {
  fullName: string;
  email: string;
  password: string;
  phone: string;
  country: string;
  role: string;
};

const savingsPlans: Array<{
  name: SavingsPlanKey;
  cadence: string;
  target: string;
  description: string;
}> = [
  {
    name: 'Daily',
    cadence: 'GHS 25 - GHS 150',
    target: 'Fast builders',
    description: 'Perfect for disciplined, low-friction accumulation.',
  },
  {
    name: 'Weekly',
    cadence: 'GHS 100 - GHS 750',
    target: 'Households and traders',
    description: 'A balanced rhythm for ongoing gold accumulation.',
  },
  {
    name: 'Monthly',
    cadence: 'GHS 250 - GHS 2,500',
    target: 'Salaried workers',
    description: 'Turn part of each pay cycle into investment-grade gold.',
  },
  {
    name: 'Flexible',
    cadence: 'Anytime top-ups',
    target: 'Businesses and families',
    description: 'Add funds whenever liquidity is available.',
  },
];

const quickActions = [
  { label: 'Deposit', hint: 'Add money' },
  { label: 'Withdraw', hint: 'To bank or MoMo' },
  { label: 'Transfer', hint: 'Send money' },
  { label: 'Buy Gold', hint: 'Lock in grams' },
  { label: 'Cash Out', hint: 'Sell instantly' },
] as const;

const listings: Listing[] = [
  { seller: 'Ashanti Gold Ltd.', country: 'Ghana', purity: '99.99%', quantity: '1,000 oz', price: '$2,425.00', delivery: 'CIF', verification: 'Corporate' },
  { seller: 'Birimian Mines', country: 'Ghana', purity: '24K', quantity: '500 oz', price: '$2,410.00', delivery: 'FOB', verification: 'Gold' },
  { seller: 'Nordic Refinery AS', country: 'Switzerland', purity: '99.99%', quantity: '2,000 oz', price: '$2,430.00', delivery: 'CIF', verification: 'Corporate' },
  { seller: 'Emirates Gold DMCC', country: 'UAE', purity: '22K', quantity: '750 oz', price: '$2,400.00', delivery: 'CIF', verification: 'Gold' },
];

const supportPrompts = [
  'How do I save for gold?',
  'Show me my wallet balance',
  'How do I sell gold instantly?',
  'What documents do I need to register?',
];

const createDefaultVerificationSnapshot = (phone = ''): VerificationSnapshot => ({
  phoneVerification: {
    status: 'not_started',
    phone,
    lastSentAt: null,
    verifiedAt: null,
  },
  documents: {
    status: 'missing',
    submittedAt: null,
    idCardFront: null,
    idCardBack: null,
    passport: null,
  },
  antiFraud: {
    status: 'pending',
    score: 0,
    flags: [],
    reviewedAt: null,
  },
  kyc: {
    status: 'not_started',
    submittedAt: null,
    verifiedAt: null,
    notes: '',
  },
});

const defaultProfile: Profile = {
  fullName: '',
  email: '',
  phone: '',
  country: 'Ghana',
  role: 'Gold Saver',
  avatarUrl: '',
};

const createDefaultInvestmentJourney = (profile: Profile): InvestmentJourney => ({
  id: 'local-investment-preview',
  productName: 'HKKO Gold Growth Plan',
  status: 'draft',
  minimumInvestment: 100000,
  validationPeriodDays: 14,
  contractDurationMonths: 12,
  contractDurationLabel: '12 Months + 1 Day',
  investmentCertificateNumber: 'HKKO-LOCAL-PREVIEW',
  investmentStartDate: null,
  registrationCompletedAt: null,
  kycStatus: 'not_started',
  kycCompletedAt: null,
  applicationStatus: 'not_submitted',
  applicationSubmittedAt: null,
  validationStatus: 'pending',
  validatedAt: null,
  agreementStatus: 'not_signed',
  agreementSignedAt: null,
  fundingStatus: 'unfunded',
  fundedAt: null,
  maturityStatus: 'not_started',
  maturityReachedAt: null,
  maturityDecision: null,
  maturityDecidedAt: null,
  validationEndsAt: null,
  nextRoiPaymentDate: null,
  investmentMaturityDate: null,
  principal: 0,
  currency: 'USD',
  monthlyDistribution: 0,
  termMonths: 12,
  monthsElapsed: 0,
  monthlyRoiRate: 0.0125,
  roiPayments: [],
  totalRoiPaid: 0,
  applicant: profile,
});

const emptyActivities: Activity[] = [];

const emptyChatMessages: ChatMessage[] = [
  {
    id: 1,
    role: 'assistant',
    text: 'Welcome to HKKO AI. I can help with savings plans, wallet actions, verification, and instant gold buyback.',
    time: 'Now',
  },
];

function createAccountId() {
  return globalThis.crypto?.randomUUID?.() ?? `acct-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}

function createAccount(profileOverrides: Partial<Profile> = {}): Account {
  const profile = {
    ...defaultProfile,
    ...profileOverrides,
  };

  return {
    id: createAccountId(),
    name: profile.fullName || 'New Account',
    profile,
    walletCash: 0,
    pendingBalance: 0,
    goldGrams: 0,
    selectedPlan: 'Monthly',
    activities: emptyActivities,
    selectedFunding: 'Mobile Money',
    chatMessages: emptyChatMessages,
    createdAt: new Date().toISOString(),
  };
}

function loadAppState(): AppState {
  if (typeof window === 'undefined') {
    const seededAccount = createAccount();
    return { accounts: [seededAccount], activeAccountId: seededAccount.id };
  }

  const savedState = window.localStorage.getItem('hkko-app-state');

  if (savedState) {
    try {
      const parsedState = JSON.parse(savedState) as AppState;

      if (parsedState.accounts?.length && parsedState.activeAccountId) {
        const isLegacySeed = parsedState.accounts.length === 1
          && normalizeEmail(parsedState.accounts[0].profile.email) === 'henry.opoku@example.com'
          && parsedState.accounts[0].profile.fullName.trim().toLowerCase() === 'henry k. opoku';

        if (isLegacySeed) {
          window.localStorage.removeItem('hkko-app-state');
        } else {
          return parsedState;
        }
      }
    } catch {
      window.localStorage.removeItem('hkko-app-state');
    }
  }

  const seededAccount = createAccount();

  return { accounts: [seededAccount], activeAccountId: seededAccount.id };
}

function normalizeEmail(value: string) {
  return value.trim().toLowerCase();
}

function readFileAsDataUrl(file: File) {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result ?? ''));
    reader.onerror = () => reject(new Error('Unable to read the selected file.'));
    reader.readAsDataURL(file);
  });
}

function App() {
  const [activeSection, setActiveSection] = useState<SectionKey>('dashboard');
  const [searchQuery, setSearchQuery] = useState('');
  const [appState, setAppState] = useState<AppState>(() => loadAppState());
  const [sessionUser, setSessionUser] = useState<null | { id: string; email: string; verified: boolean; profile: Profile }>(null);
  const [authMode, setAuthMode] = useState<AuthMode>('signup');
  const [authBusy, setAuthBusy] = useState(false);
  const [authError, setAuthError] = useState<string | null>(null);
  const [authSuccess, setAuthSuccess] = useState<string | null>(null);
  const [pendingLogin2fa, setPendingLogin2fa] = useState<null | { email: string; challengeId: string; method: 'email' | 'sms'; demoCode?: string }>(null);
  const [login2faCode, setLogin2faCode] = useState('');
  const [twoFactorSetupCode, setTwoFactorSetupCode] = useState('');
  const [twoFactorSetupChallengeId, setTwoFactorSetupChallengeId] = useState('');
  const [authDraft, setAuthDraft] = useState<AuthDraft>({
    fullName: defaultProfile.fullName,
    email: defaultProfile.email,
    password: '',
    phone: defaultProfile.phone,
    country: defaultProfile.country,
    role: defaultProfile.role,
  });
  const [dashboardSnapshot, setDashboardSnapshot] = useState<DashboardSnapshot | null>(null);
  const [investmentDraft, setInvestmentDraft] = useState({
    productName: 'HKKO Gold Growth Plan',
    principal: '100000',
    termMonths: '12',
    monthlyRoiRate: '1.25',
  });
  const [investmentBusy, setInvestmentBusy] = useState(false);
  const [investmentError, setInvestmentError] = useState<string | null>(null);
  const [investmentSuccess, setInvestmentSuccess] = useState<string | null>(null);
  const [draftProfile, setDraftProfile] = useState<Profile>(defaultProfile);
  const [newAccountDraft, setNewAccountDraft] = useState<Profile>({
    fullName: '',
    email: '',
    phone: '',
    country: 'Ghana',
    role: 'Gold Saver',
  });
  const [assistantOpen, setAssistantOpen] = useState(false);
  const [chatInput, setChatInput] = useState('');
  const [toast, setToast] = useState<string | null>(null);
  const [paymentOpen, setPaymentOpen] = useState(false);
  const [paymentAmount, setPaymentAmount] = useState(0);
  const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>('Mobile Money');
  const [paymentPhone, setPaymentPhone] = useState('');
  const [paymentNetwork, setPaymentNetwork] = useState('MTN');
  const [paymentCardName, setPaymentCardName] = useState('');
  const [paymentCardNumber, setPaymentCardNumber] = useState('');
  const [paymentExpiry, setPaymentExpiry] = useState('');
  const [paymentCvv, setPaymentCvv] = useState('');
  const [paymentError, setPaymentError] = useState<string | null>(null);
  const [paymentBusy, setPaymentBusy] = useState(false);
  const [assistantExpanded, setAssistantExpanded] = useState(false);
  const [verificationCode, setVerificationCode] = useState('');
  const [verificationBusy, setVerificationBusy] = useState(false);
  const [verificationError, setVerificationError] = useState<string | null>(null);
  const [verificationSuccess, setVerificationSuccess] = useState<string | null>(null);
  const [idCardFrontFile, setIdCardFrontFile] = useState<File | null>(null);
  const [idCardBackFile, setIdCardBackFile] = useState<File | null>(null);
  const [passportFile, setPassportFile] = useState<File | null>(null);
  const googleButtonHostRef = useRef<HTMLDivElement | null>(null);
  const authDraftRef = useRef<AuthDraft>(authDraft);
  const googleClientId = ((import.meta.env.VITE_GOOGLE_CLIENT_ID as string | undefined) ?? '').trim();

  const [liveGoldPrice, setLiveGoldPrice] = useState(2425.0);
  const [liveGoldUpdatedAt, setLiveGoldUpdatedAt] = useState<string | null>(null);
  const buyBackPrice = 2368.0;
  const toastTimeoutRef = useRef<number | null>(null);
  const activeAccount = appState.accounts.find((account) => account.id === appState.activeAccountId) ?? appState.accounts[0];
  const profile = activeAccount?.profile ?? defaultProfile;
  const hasProfileIdentity = Boolean(profile.fullName.trim() || profile.email.trim() || profile.phone.trim());
  const profileHeading = hasProfileIdentity ? profile.fullName : 'Guest Investor';
  const profileSubheading = hasProfileIdentity ? `${profile.role} · Verified Account` : 'Create Profile to activate your live account';
  const profileCountryLabel = hasProfileIdentity ? profile.country : 'Create Profile';
  const profileActionLabel = hasProfileIdentity ? 'Edit Profile' : 'Create Profile';
  const priceUpdatedLabel = liveGoldUpdatedAt
    ? new Date(liveGoldUpdatedAt).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' })
    : 'Syncing...';
  const walletCash = activeAccount?.walletCash ?? 0;
  const pendingBalance = activeAccount?.pendingBalance ?? 0;
  const goldGrams = activeAccount?.goldGrams ?? 0;
  const selectedPlan = activeAccount?.selectedPlan ?? 'Monthly';
  const activities = activeAccount?.activities ?? emptyActivities;
  const selectedFunding = activeAccount?.selectedFunding ?? 'Mobile Money';
  const chatMessages = activeAccount?.chatMessages ?? emptyChatMessages;
  const goldValue = goldGrams * liveGoldPrice;
  const totalWalletBalance = walletCash + pendingBalance + goldValue;
  const targetGrams = 10;
  const progress = Math.min((goldGrams / targetGrams) * 100, 100);
  const accountCount = appState.accounts.length;

  const verificationSteps = ['KYC identity verification', 'ID card and passport uploads', 'Phone-number verification', 'Anti-fraud checks'];

  const plan = savingsPlans.find((entry) => entry.name === selectedPlan) ?? savingsPlans[0];
  const normalizedQuery = searchQuery.trim().toLowerCase();
  const filteredListings = listings.filter((listing) => matchesQuery(listing, normalizedQuery));
  const filteredActivities = activities.filter((activity) => matchesQuery(activity, normalizedQuery));
  const serverNotifications = dashboardSnapshot?.notifications ?? [];
  const securityEmails = dashboardSnapshot?.securityEmails ?? [];
  const twoFactorStatus = dashboardSnapshot?.twoFactor ?? { enabled: false, method: 'email' as const, lastVerifiedAt: null };
  const securityStandards = dashboardSnapshot?.securityStandards ?? [];
  const transactionStorage = dashboardSnapshot?.transactionStorage ?? {
    model: 'append-only event log',
    location: 'server/data/db.json',
    retention: 'Configured by backend',
    integrity: 'Integrity metadata not available yet',
  };
  const backupStatus = dashboardSnapshot?.backupStatus ?? {
    retention: 0,
    location: 'server/data/backups',
    lastBackupAt: null,
    lastBackupFile: null,
  };
  const serverOrders = dashboardSnapshot?.orders ?? [];
  const serverStorage = dashboardSnapshot?.storage ?? {
    insured: true,
    provider: 'HKKO Insured Vault',
    coverage: 'Vault assets are insured while held in storage.',
  };
  const verificationState = dashboardSnapshot?.verification ?? createDefaultVerificationSnapshot(profile.phone);
  const verificationChecklist = [
    { label: 'Phone Verification', complete: verificationState.phoneVerification.status === 'verified' },
    { label: 'KYC Review', complete: verificationState.kyc.status === 'verified' },
    { label: 'Document Submission', complete: verificationState.documents.status === 'submitted' || verificationState.documents.status === 'verified' },
    { label: 'Anti-Fraud Screening', complete: verificationState.antiFraud.status === 'approved' },
  ];
  const verificationCompletionCount = verificationChecklist.filter((entry) => entry.complete).length;
  const verificationCompletionPercent = Math.round((verificationCompletionCount / verificationChecklist.length) * 100);
  const investmentJourney = dashboardSnapshot?.investmentJourney ?? createDefaultInvestmentJourney(profile);
  const investmentCalendar = buildMonthlyRoiCalendar(investmentJourney);
  const investmentPrincipal = investmentJourney.principal || Number(investmentDraft.principal);
  const investmentStartDate = investmentJourney.investmentStartDate ?? investmentJourney.fundedAt ?? investmentJourney.registrationCompletedAt;
  const investmentValidationDeadline = investmentJourney.validationEndsAt ?? (investmentJourney.registrationCompletedAt ? addDaysIso(investmentJourney.registrationCompletedAt, investmentJourney.validationPeriodDays) : null);
  const investmentMaturityDate = investmentJourney.investmentMaturityDate ?? (investmentStartDate ? addDaysIso(addMonthsIso(investmentStartDate, investmentJourney.contractDurationMonths), 1) : null);
  const investmentNextRoiPaymentDate = investmentJourney.nextRoiPaymentDate ?? (investmentStartDate ? addMonthsIso(investmentStartDate, investmentJourney.monthsElapsed + 1) : null);
  const remainingRoiPayments = Math.max(0, investmentJourney.termMonths - investmentJourney.monthsElapsed);
  const nextPaymentAmount = investmentJourney.monthlyDistribution || Number((investmentPrincipal * investmentJourney.monthlyRoiRate).toFixed(2));
  const roiReceivedToDate = investmentJourney.totalRoiPaid;
  const totalInvestmentPortfolio = investmentPrincipal + roiReceivedToDate;
  const serverActivities: Activity[] = (dashboardSnapshot?.transactions ?? []).map((transaction) => ({
    id: Number(new Date(transaction.createdAt).getTime()),
    label:
      transaction.type === 'deposit'
        ? 'Deposit'
        : transaction.type === 'withdrawal'
          ? 'Withdrawal'
          : transaction.type === 'buy'
            ? 'Buy Gold'
            : transaction.type === 'sell'
              ? 'Sell Gold'
              : 'Transfer',
    detail: transaction.channel ?? transaction.method ?? transaction.destination ?? transaction.status,
    amount: `${transaction.amount >= 0 ? '+' : '-'}GHS ${Math.abs(transaction.amount).toFixed(2)}`,
    type:
      transaction.type === 'deposit'
        ? 'Deposit'
        : transaction.type === 'withdrawal'
          ? 'Withdraw'
          : transaction.type === 'buy'
            ? 'Buy Gold'
            : transaction.type === 'sell'
              ? 'Sell Gold'
              : 'Transfer',
    time: new Date(transaction.createdAt).toLocaleTimeString(),
  }));
  const visibleActivities = dashboardSnapshot ? serverActivities.filter((activity) => matchesQuery(activity, normalizedQuery)) : filteredActivities;

  const marketOverview = useMemo(
    () => [
      { label: 'Top Selling Country', value: 'Ghana', stat: 'GHS 65.42M' },
      { label: 'Top Buying Country', value: 'UAE', stat: 'GHS 42.18M' },
      { label: 'Most Traded Purity', value: '99.99%', stat: 'GHS 78.35M' },
      { label: 'Average Trade Size', value: '845 oz', stat: '30 Days' },
    ],
    [],
  );

  const currencyBalances = [
    { code: 'GHS', value: walletCash.toFixed(2), accent: 'burgundy' },
    { code: 'USD', value: '798.45', accent: 'gold' },
    { code: 'EUR', value: '8,450.00', accent: 'teal' },
    { code: 'AED', value: '18,230.00', accent: 'emerald' },
  ];
  const investmentRoiTotal = roiReceivedToDate;
  const investmentMaturityProgress = Math.min((investmentJourney.monthsElapsed / Math.max(1, investmentJourney.termMonths)) * 100, 100);
  const investmentMonthlyRoi = Number((investmentJourney.principal * investmentJourney.monthlyRoiRate).toFixed(2));
  const reportTransactions = dashboardSnapshot?.transactions ?? [];
  const reportNetFlow = reportTransactions.reduce((sum, transaction) => sum + Number(transaction.amount || 0), 0);
  const reportPositiveFlow = reportTransactions.reduce((sum, transaction) => sum + (transaction.amount > 0 ? transaction.amount : 0), 0);
  const reportNegativeFlow = reportTransactions.reduce((sum, transaction) => sum + (transaction.amount < 0 ? Math.abs(transaction.amount) : 0), 0);
  const reportTransactionCount = reportTransactions.length;
  const reportOrderCount = serverOrders.length;

  useEffect(() => {
    authDraftRef.current = authDraft;
  }, [authDraft]);

  const addActivity = (activity: Omit<Activity, 'id' | 'time'>) => {
    const nextEntry: Activity = {
      ...activity,
      id: Date.now(),
      time: 'Just now',
    };

    setAppState((currentState) => ({
      ...currentState,
      accounts: currentState.accounts.map((account) => {
        if (account.id !== currentState.activeAccountId) {
          return account;
        }

        return {
          ...account,
          activities: [nextEntry, ...account.activities].slice(0, 6),
        };
      }),
    }));
  };

  const updateActiveAccount = (updater: (account: Account) => Account) => {
    setAppState((currentState) => ({
      ...currentState,
      accounts: currentState.accounts.map((account) => (account.id === currentState.activeAccountId ? updater(account) : account)),
    }));
  };

  const setActiveAccountId = (accountId: string) => {
    setAppState((currentState) => ({
      ...currentState,
      activeAccountId: accountId,
    }));
  };

  useEffect(() => {
    if (typeof window === 'undefined') {
      return;
    }

    window.localStorage.setItem('hkko-app-state', JSON.stringify(appState));
  }, [appState]);

  useEffect(() => {
    setDraftProfile(profile);
    setNewAccountDraft((currentDraft) => ({
      ...currentDraft,
      country: profile.country,
    }));
  }, [appState.activeAccountId]);

  useEffect(() => {
    void refreshServerState();
  }, []);

  useEffect(() => {
    let isMounted = true;

    const syncLiveGoldPrice = async () => {
      const applyPrice = (price: DashboardSnapshot['price']) => {
        if (!isMounted) {
          return;
        }

        setLiveGoldPrice(price.goldOunce);
        setLiveGoldUpdatedAt(price.updatedAt);
      };

      try {
        const response = await apiRequest<{ price: DashboardSnapshot['price'] }>('/api/pricing/latest');
        applyPrice(response.price);
        return;
      } catch {
        // Preview mode does not proxy /api, so fallback directly to the local backend.
      }

      try {
        const response = await fetch('http://127.0.0.1:8787/api/pricing/latest');
        if (!response.ok) {
          return;
        }

        const payload = (await response.json()) as { price?: DashboardSnapshot['price'] };
        if (payload.price) {
          applyPrice(payload.price);
        }
      } catch {
        // Keep the last known market quote instead of generating synthetic values.
      }
    };

    void syncLiveGoldPrice();
    const priceTimer = window.setInterval(() => {
      void syncLiveGoldPrice();
    }, 5000);

    return () => {
      isMounted = false;
      window.clearInterval(priceTimer);
    };
  }, []);

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

  const openSection = (section: SectionKey) => {
    setActiveSection(section);
    window.scrollTo({ top: 0, behavior: 'smooth' });
    if (section !== 'dashboard') {
      notify(`Opened ${labelForSection(section).toLowerCase()}.`);
    }
  };

  const cycleAccount = () => {
    if (accountCount < 2) {
      openSection('settings');
      return;
    }

    const activeIndex = appState.accounts.findIndex((account) => account.id === appState.activeAccountId);
    const nextIndex = (activeIndex + 1) % appState.accounts.length;
    setActiveAccountId(appState.accounts[nextIndex].id);
    notify(`Switched to ${appState.accounts[nextIndex].name}.`);
  };

  const updateAccountPreferences = (updates: Partial<Pick<Account, 'selectedPlan' | 'selectedFunding'>>) => {
    updateActiveAccount((account) => ({
      ...account,
      ...updates,
    }));
  };

  const notify = (message: string) => {
    setToast(message);

    if (toastTimeoutRef.current) {
      window.clearTimeout(toastTimeoutRef.current);
    }

    toastTimeoutRef.current = window.setTimeout(() => {
      setToast(null);
    }, 2600);
  };

  const apiRequest = async <T,>(path: string, init: RequestInit = {}) => {
    const response = await fetch(path, {
      ...init,
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        ...(init.headers ?? {}),
      },
    });

    const data = (await response.json().catch(() => ({}))) as T & { message?: string };

    if (!response.ok) {
      throw new Error(data.message ?? 'Request failed.');
    }

    return data;
  };

  const hydrateFromDashboard = (snapshot: DashboardSnapshot) => {
    const email = normalizeEmail(snapshot.profile.email);

    setAppState((currentState) => {
      const existingAccount = currentState.accounts.find((account) => normalizeEmail(account.profile.email) === email);

      if (existingAccount) {
        return {
          ...currentState,
          activeAccountId: existingAccount.id,
          accounts: currentState.accounts.map((account) => {
            if (account.id !== existingAccount.id) {
              return account;
            }

            return {
              ...account,
              name: snapshot.profile.fullName || account.name,
              profile: snapshot.profile,
              walletCash: snapshot.wallet.cash,
              pendingBalance: snapshot.wallet.pending,
              goldGrams: snapshot.wallet.goldGrams,
            };
          }),
        };
      }

      const newAccount = {
        ...createAccount(snapshot.profile),
        name: snapshot.profile.fullName || 'New Account',
        walletCash: snapshot.wallet.cash,
        pendingBalance: snapshot.wallet.pending,
        goldGrams: snapshot.wallet.goldGrams,
      };

      return {
        ...currentState,
        activeAccountId: newAccount.id,
        accounts: [newAccount, ...currentState.accounts],
      };
    });
  };

  const refreshServerState = async () => {
    try {
      const meResponse = await apiRequest<{ user: { id: string; email: string; verified: boolean; profile: Profile } }>('/api/me');
      setSessionUser(meResponse.user);

      const dashboardResponse = await apiRequest<DashboardSnapshot>('/api/dashboard');
      setDashboardSnapshot(dashboardResponse);
      hydrateFromDashboard(dashboardResponse);
      setDraftProfile(dashboardResponse.profile);
      setLiveGoldPrice(dashboardResponse.price.goldOunce);
      setLiveGoldUpdatedAt(dashboardResponse.price.updatedAt);
      setAuthError(null);
    } catch {
      setSessionUser(null);
      setDashboardSnapshot(null);
    }
  };

  const runInvestmentStep = async (action: 'register' | 'kyc' | 'application' | 'validation' | 'agreement' | 'fund' | 'roi' | 'maturity', payload: Record<string, unknown> = {}) => {
    if (investmentBusy) {
      return;
    }

    setInvestmentBusy(true);
    setInvestmentError(null);
    setInvestmentSuccess(null);

    try {
      const response = await apiRequest<{ message?: string }>('/api/investment/step', {
        method: 'POST',
        body: JSON.stringify({ action, payload }),
      });

      await refreshServerState();
      setInvestmentSuccess(response.message ?? 'Investment step completed.');
      notify(response.message ?? 'Investment step completed.');
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Investment update failed.';
      setInvestmentError(message);
      notify(message);
    } finally {
      setInvestmentBusy(false);
    }
  };

  const registerInvestment = () => {
    const principal = Number(investmentDraft.principal);
    const termMonths = Number(investmentDraft.termMonths);
    const monthlyRoiRate = Number(investmentDraft.monthlyRoiRate) / 100;

    void runInvestmentStep('register', {
      productName: investmentDraft.productName,
      principal,
      termMonths,
      monthlyRoiRate,
      fullName: profile.fullName,
      email: profile.email,
      phone: profile.phone,
      country: profile.country,
      role: profile.role,
    });
  };

  const completeInvestmentKyc = () => {
    void runInvestmentStep('kyc', {
      fullName: profile.fullName,
      email: profile.email,
      phone: profile.phone,
      country: profile.country,
      role: profile.role,
    });
  };

  const submitInvestmentApplication = () => {
    void runInvestmentStep('application', {
      applicationReference: investmentJourney.id,
      productName: investmentJourney.productName,
    });
  };

  const validateInvestment = () => {
    void runInvestmentStep('validation', {
      applicationReference: investmentJourney.id,
    });
  };

  const signInvestmentAgreement = () => {
    void runInvestmentStep('agreement', {
      signerName: profile.fullName,
      productName: investmentJourney.productName,
    });
  };

  const fundInvestment = () => {
    void runInvestmentStep('fund', {
      amount: investmentJourney.principal || Number(investmentDraft.principal),
    });
  };

  const recordMonthlyRoi = () => {
    void runInvestmentStep('roi', {
      productName: investmentJourney.productName,
    });
  };

  const decideInvestmentMaturity = (decision: 'reinvest' | 'redeem') => {
    void runInvestmentStep('maturity', {
      decision,
      productName: investmentJourney.productName,
    });
  };

  const requestPhoneVerificationCode = async () => {
    if (verificationBusy) {
      return;
    }

    setVerificationBusy(true);
    setVerificationError(null);
    setVerificationSuccess(null);

    try {
      const response = await apiRequest<{ message?: string; demoCode?: string }>('/api/verification/phone/send', {
        method: 'POST',
        body: JSON.stringify({ phone: draftProfile.phone || profile.phone }),
      });
      await refreshServerState();
      const demoSuffix = response.demoCode ? ` Demo code: ${response.demoCode}` : '';
      setVerificationSuccess(`${response.message ?? 'Verification code sent.'}${demoSuffix}`);
      notify(response.message ?? 'Verification code sent.');
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Unable to send phone verification code.';
      setVerificationError(message);
      notify(message);
    } finally {
      setVerificationBusy(false);
    }
  };

  const confirmPhoneVerificationCode = async () => {
    if (verificationBusy) {
      return;
    }

    setVerificationBusy(true);
    setVerificationError(null);
    setVerificationSuccess(null);

    try {
      const response = await apiRequest<{ message?: string }>('/api/verification/phone/confirm', {
        method: 'POST',
        body: JSON.stringify({ code: verificationCode }),
      });
      await refreshServerState();
      setVerificationSuccess(response.message ?? 'Phone verification completed.');
      notify(response.message ?? 'Phone verification completed.');
      setVerificationCode('');
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Phone verification failed.';
      setVerificationError(message);
      notify(message);
    } finally {
      setVerificationBusy(false);
    }
  };

  const submitKycDocuments = async () => {
    if (verificationBusy) {
      return;
    }

    if (!idCardFrontFile || !idCardBackFile || !passportFile) {
      const message = 'Upload ID card front, ID card back, and passport files before submitting KYC.';
      setVerificationError(message);
      notify(message);
      return;
    }

    setVerificationBusy(true);
    setVerificationError(null);
    setVerificationSuccess(null);

    try {
      const [idFrontDataUrl, idBackDataUrl, passportDataUrl] = await Promise.all([
        readFileAsDataUrl(idCardFrontFile),
        readFileAsDataUrl(idCardBackFile),
        readFileAsDataUrl(passportFile),
      ]);

      const response = await apiRequest<{ message?: string }>('/api/verification/kyc/submit', {
        method: 'POST',
        body: JSON.stringify({
          idCardFront: {
            name: idCardFrontFile.name,
            type: idCardFrontFile.type,
            size: idCardFrontFile.size,
            dataUrl: idFrontDataUrl,
          },
          idCardBack: {
            name: idCardBackFile.name,
            type: idCardBackFile.type,
            size: idCardBackFile.size,
            dataUrl: idBackDataUrl,
          },
          passport: {
            name: passportFile.name,
            type: passportFile.type,
            size: passportFile.size,
            dataUrl: passportDataUrl,
          },
        }),
      });

      await refreshServerState();
      setVerificationSuccess(response.message ?? 'KYC documents submitted.');
      notify(response.message ?? 'KYC documents submitted.');
    } catch (error) {
      const message = error instanceof Error ? error.message : 'KYC document submission failed.';
      setVerificationError(message);
      notify(message);
    } finally {
      setVerificationBusy(false);
    }
  };

  const submitAuthForm = async () => {
    if (authBusy) {
      return;
    }

    setAuthBusy(true);
    setAuthError(null);
    setAuthSuccess(null);

    try {
      if (authMode === 'signup') {
        const response = await apiRequest<{ message?: string; activationLink?: string }>('/api/auth/signup', {
          method: 'POST',
          body: JSON.stringify({
            fullName: authDraft.fullName,
            email: authDraft.email,
            password: authDraft.password,
            phone: authDraft.phone,
            country: authDraft.country,
            role: authDraft.role,
          }),
        });

        setAuthMode('login');
        setAuthDraft((current) => ({ ...current, password: '' }));
        setAuthSuccess(response.activationLink ? `${response.message ?? 'Account created.'} Activation link sent.` : response.message ?? 'Account created.');
        notify('Account created. Verify your email, then log in.');
      } else {
        const response = await apiRequest<{ message?: string; requiresTwoFactor?: boolean; challengeId?: string; email?: string; method?: 'email' | 'sms'; demoCode?: string }>('/api/auth/login', {
          method: 'POST',
          body: JSON.stringify({
            email: authDraft.email,
            password: authDraft.password,
          }),
        });

        if (response.requiresTwoFactor && response.challengeId && response.email) {
          setPendingLogin2fa({
            email: response.email,
            challengeId: response.challengeId,
            method: response.method ?? 'email',
            demoCode: response.demoCode,
          });
          setAuthSuccess(response.message ?? 'Two-factor verification required.');
          notify('Enter your 2FA code to complete login.');
          return;
        }

        await refreshServerState();
        setAuthDraft((current) => ({ ...current, password: '' }));
        setPendingLogin2fa(null);
        setAuthSuccess('Logged in successfully.');
        notify('Logged in. Your live wallet is synchronized.');
      }
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : 'Authentication failed.');
    } finally {
      setAuthBusy(false);
    }
  };

  const logoutLiveSession = async () => {
    if (authBusy) {
      return;
    }

    setAuthBusy(true);
    setAuthError(null);
    setAuthSuccess(null);

    try {
      await apiRequest<{ message?: string }>('/api/auth/logout', { method: 'POST' });
      setSessionUser(null);
      setDashboardSnapshot(null);
      setAuthDraft((current) => ({ ...current, password: '' }));
      setAuthSuccess('Logged out.');
      notify('Live session ended.');
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : 'Logout failed.');
    } finally {
      setAuthBusy(false);
    }
  };

  const markNotificationsRead = async () => {
    try {
      await apiRequest<{ message?: string }>('/api/notifications/read', { method: 'POST' });
      await refreshServerState();
      notify('Notifications marked as read.');
    } catch (error) {
      notify(error instanceof Error ? error.message : 'Unable to mark notifications as read.');
    }
  };

  const deleteLiveAccount = async () => {
    if (!sessionUser) {
      notify('Log in to a live account first.');
      return;
    }

    if (!window.confirm('Delete this live account permanently? This cannot be undone.')) {
      return;
    }

    setAuthBusy(true);
    try {
      await apiRequest<{ message?: string }>('/api/account', { method: 'DELETE' });
      setSessionUser(null);
      setDashboardSnapshot(null);
      setAuthSuccess('Account deleted successfully.');
      setAuthError(null);
      notify('Live account deleted successfully.');
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Account deletion failed.';
      setAuthError(message);
      notify(message);
    } finally {
      setAuthBusy(false);
    }
  };

  const continueWithGoogle = async (credential: string) => {
    if (!credential || authBusy) {
      return;
    }

    setAuthBusy(true);
    setAuthError(null);
    setAuthSuccess(null);

    try {
      const draft = authDraftRef.current;
      const response = await apiRequest<{ message?: string; requiresTwoFactor?: boolean; challengeId?: string; email?: string; method?: 'email' | 'sms'; demoCode?: string }>('/api/auth/google', {
        method: 'POST',
        body: JSON.stringify({
          credential,
          country: draft.country,
          role: draft.role,
          phone: draft.phone,
        }),
      });

      if (response.requiresTwoFactor && response.challengeId && response.email) {
        setPendingLogin2fa({
          email: response.email,
          challengeId: response.challengeId,
          method: response.method ?? 'email',
          demoCode: response.demoCode,
        });
        setAuthSuccess(response.message ?? 'Two-factor verification required.');
        notify('Enter your 2FA code to complete login.');
        return;
      }

      await refreshServerState();
      setAuthDraft((current) => ({ ...current, password: '' }));
      setPendingLogin2fa(null);
      setAuthSuccess('Google sign-in successful.');
      notify('Google account connected and logged in.');
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : 'Google sign-in failed.');
    } finally {
      setAuthBusy(false);
    }
  };

  const completeLoginTwoFactor = async () => {
    if (!pendingLogin2fa || authBusy) {
      return;
    }

    setAuthBusy(true);
    setAuthError(null);

    try {
      await apiRequest<{ message?: string }>('/api/auth/2fa/verify', {
        method: 'POST',
        body: JSON.stringify({
          email: pendingLogin2fa.email,
          challengeId: pendingLogin2fa.challengeId,
          code: login2faCode,
        }),
      });
      await refreshServerState();
      setPendingLogin2fa(null);
      setLogin2faCode('');
      setAuthSuccess('2FA verification successful. Logged in.');
      notify('Two-factor verification successful.');
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : '2FA verification failed.');
    } finally {
      setAuthBusy(false);
    }
  };

  const sendTwoFactorSetupCode = async (method: 'email' | 'sms') => {
    if (!sessionUser) {
      notify('Log in first to manage 2FA.');
      return;
    }

    setVerificationBusy(true);
    setVerificationError(null);
    setVerificationSuccess(null);
    try {
      const response = await apiRequest<{ message?: string; challengeId?: string; demoCode?: string }>('/api/auth/2fa/setup/send', {
        method: 'POST',
        body: JSON.stringify({ method }),
      });
      setTwoFactorSetupChallengeId(response.challengeId ?? '');
      const demoSuffix = response.demoCode ? ` Demo code: ${response.demoCode}` : '';
      setVerificationSuccess(`${response.message ?? '2FA setup code sent.'}${demoSuffix}`);
    } catch (error) {
      setVerificationError(error instanceof Error ? error.message : 'Unable to send 2FA setup code.');
    } finally {
      setVerificationBusy(false);
    }
  };

  const confirmTwoFactorSetup = async () => {
    if (!twoFactorSetupChallengeId) {
      setVerificationError('Request a 2FA setup code first.');
      return;
    }

    setVerificationBusy(true);
    setVerificationError(null);
    try {
      const response = await apiRequest<{ message?: string }>('/api/auth/2fa/setup/confirm', {
        method: 'POST',
        body: JSON.stringify({ challengeId: twoFactorSetupChallengeId, code: twoFactorSetupCode }),
      });
      await refreshServerState();
      setTwoFactorSetupCode('');
      setTwoFactorSetupChallengeId('');
      setVerificationSuccess(response.message ?? '2FA enabled successfully.');
      notify(response.message ?? '2FA enabled successfully.');
    } catch (error) {
      setVerificationError(error instanceof Error ? error.message : 'Unable to enable 2FA.');
    } finally {
      setVerificationBusy(false);
    }
  };

  const disableTwoFactor = async () => {
    setVerificationBusy(true);
    setVerificationError(null);
    try {
      const response = await apiRequest<{ message?: string }>('/api/auth/2fa/disable', { method: 'POST' });
      await refreshServerState();
      setVerificationSuccess(response.message ?? '2FA disabled.');
      notify(response.message ?? '2FA disabled.');
    } catch (error) {
      setVerificationError(error instanceof Error ? error.message : 'Unable to disable 2FA.');
    } finally {
      setVerificationBusy(false);
    }
  };

  useEffect(() => {
    if (!googleClientId || !googleButtonHostRef.current) {
      return;
    }

    let isCancelled = false;

    const renderGoogleButton = () => {
      if (isCancelled || !googleButtonHostRef.current || !window.google?.accounts?.id) {
        return;
      }

      window.google.accounts.id.initialize({
        client_id: googleClientId,
        callback: (response) => {
          if (response.credential) {
            void continueWithGoogle(response.credential);
          }
        },
      });

      googleButtonHostRef.current.innerHTML = '';
      window.google.accounts.id.renderButton(googleButtonHostRef.current, {
        theme: 'outline',
        size: 'large',
        text: authMode === 'signup' ? 'signup_with' : 'signin_with',
        shape: 'pill',
        logo_alignment: 'left',
        width: '320',
      });
    };

    if (window.google?.accounts?.id) {
      renderGoogleButton();
      return () => {
        isCancelled = true;
      };
    }

    const existingScript = document.querySelector<HTMLScriptElement>('script[data-google-identity="true"]');

    if (existingScript) {
      existingScript.addEventListener('load', renderGoogleButton, { once: true });
    } else {
      const script = document.createElement('script');
      script.src = 'https://accounts.google.com/gsi/client';
      script.async = true;
      script.defer = true;
      script.dataset.googleIdentity = 'true';
      script.addEventListener('load', renderGoogleButton, { once: true });
      document.head.appendChild(script);
    }

    return () => {
      isCancelled = true;
    };
  }, [authMode, googleClientId]);

  const depositFunds = (amount: number, channel?: string) => {
    updateActiveAccount((account) => ({
      ...account,
      walletCash: account.walletCash + amount,
    }));
    notify(`Added ${formatMoney(amount)} to your wallet.`);
    addActivity({
      label: 'Deposit',
      detail: `${channel ?? selectedFunding} top-up into HKKO Pay Wallet`,
      amount: `+GHS ${amount.toFixed(2)}`,
      type: 'Deposit',
    });
  };

  const resetPaymentFields = () => {
    setPaymentPhone('');
    setPaymentNetwork('MTN');
    setPaymentCardName('');
    setPaymentCardNumber('');
    setPaymentExpiry('');
    setPaymentCvv('');
    setPaymentError(null);
  };

  const closePayment = () => {
    setPaymentOpen(false);
    resetPaymentFields();
  };

  const startPayment = (amount: number) => {
    setPaymentAmount(amount);
    setPaymentMethod('Mobile Money');
    setPaymentError(null);
    setPaymentOpen(true);
  };

  const completePayment = async () => {
    if (paymentBusy) {
      return;
    }

    if (paymentAmount <= 0) {
      notify('Invalid payment amount.');
      return;
    }

    let paymentChannel: string = paymentMethod;

    if (paymentMethod === 'Mobile Money') {
      const momoDigits = paymentPhone.replace(/\D/g, '');
      const validMomo = /^(?:\+?233|0)?\d{9}$/.test(paymentPhone.trim()) || /^\d{9}$/.test(momoDigits);

      if (!validMomo) {
        notify('Enter a valid Mobile Money number.');
        return;
      }
      paymentChannel = `${paymentMethod} (${paymentNetwork})`;
    }

    const cardDigits = paymentCardNumber.replace(/\D/g, '');
    const cvvDigits = paymentCvv.replace(/\D/g, '');
    const validExpiry = /^\d{2}\/\d{2}$/.test(paymentExpiry.trim());

    if (paymentMethod !== 'Mobile Money' && (!paymentCardName.trim() || cardDigits.length < 12 || !validExpiry || cvvDigits.length < 3)) {
      notify('Enter complete card details.');
      return;
    }

    setPaymentBusy(true);
    setPaymentError(null);

    try {
      const payload = {
        amount: paymentAmount,
        currency: 'GHS',
        method: paymentMethod,
        channel: paymentChannel,
        customer: {
          name: profile.fullName,
          email: profile.email,
          phone: paymentMethod === 'Mobile Money' ? paymentPhone : profile.phone,
        },
        metadata: {
          accountId: activeAccount?.id,
          network: paymentNetwork,
          cardLast4: paymentMethod === 'Mobile Money' ? undefined : cardDigits.slice(-4),
        },
      };

      const result = await apiRequest<{ checkoutUrl?: string; reference?: string; message?: string }>('/api/wallet/deposit/initiate', {
        method: 'POST',
        body: JSON.stringify(payload),
      });

      if (!result.checkoutUrl) {
        throw new Error(result.message ?? 'Gateway did not return a checkout URL.');
      }

      updateActiveAccount((account) => ({
        ...account,
        pendingBalance: account.pendingBalance + paymentAmount,
      }));

      addActivity({
        label: 'Deposit',
        detail: `${paymentChannel} payment initiated${result.reference ? ` • Ref ${result.reference}` : ''}`,
        amount: `Pending ${formatMoney(paymentAmount)}`,
        type: 'Deposit',
      });

      notify('Payment initialized. Complete payment with your provider to settle funds.');
      closePayment();
      window.location.assign(result.checkoutUrl);
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Payment initialization failed.';
      setPaymentError(message);
      notify('Payment failed to initialize. Nothing was charged.');
    } finally {
      setPaymentBusy(false);
    }
  };

  const buyGold = () => {
    if (walletCash < liveGoldPrice) {
      notify('Add more cash before buying gold.');
      return;
    }

    updateActiveAccount((account) => ({
      ...account,
      walletCash: account.walletCash - liveGoldPrice,
      goldGrams: account.goldGrams + 1,
    }));
    notify('Gold purchased and added to your vault.');
    addActivity({
      label: 'Buy Gold',
      detail: '1.00 g secured in the HKKO vault',
      amount: `-${formatMoney(liveGoldPrice)}`,
      type: 'Buy Gold',
    });
  };

  const sellGold = () => {
    if (goldGrams < 1) {
      notify('No gold available to sell yet.');
      return;
    }

    updateActiveAccount((account) => ({
      ...account,
      goldGrams: account.goldGrams - 1,
      walletCash: account.walletCash + buyBackPrice,
    }));
    notify('Gold sold and cash returned instantly.');
    addActivity({
      label: 'Sell Gold',
      detail: '1.00 g sold at instant buy-back price',
      amount: `+${formatMoney(buyBackPrice)}`,
      type: 'Sell Gold',
    });
  };

  const transferToVault = () => {
    if (walletCash < 500) {
      notify('You need at least GHS 500 to move into the vault.');
      return;
    }

    updateActiveAccount((account) => ({
      ...account,
      walletCash: account.walletCash - 500,
      goldGrams: account.goldGrams + 0.206,
    }));
    notify('Funds moved into gold vault holdings.');
    addActivity({
      label: 'Vault Transfer',
      detail: 'Converted GHS 500 into gold reserve',
      amount: '-GHS 500.00',
      type: 'Transfer',
    });
  };

  const sendChatMessage = (rawText: string) => {
    const trimmedText = rawText.trim();

    if (!trimmedText) {
      return;
    }

    const userMessage: ChatMessage = {
      id: Date.now(),
      role: 'user',
      text: trimmedText,
      time: 'Now',
    };

    const assistantMessage: ChatMessage = {
      id: Date.now() + 1,
      role: 'assistant',
      text: buildAssistantReply(trimmedText, { walletCash, goldGrams, liveGoldPrice, buyBackPrice }),
      time: 'Now',
    };

    updateActiveAccount((account) => ({
      ...account,
      chatMessages: [assistantMessage, userMessage, ...account.chatMessages].slice(0, 12),
    }));
  };

  const clearAssistantChat = () => {
    updateActiveAccount((account) => ({
      ...account,
      chatMessages: emptyChatMessages,
    }));
    notify('Chat history cleared.');
  };

  const saveProfile = () => {
    void apiRequest<{ message?: string; user?: { profile: Profile } }>('/api/profile', {
      method: 'POST',
      body: JSON.stringify({ profile: draftProfile }),
    }).catch(() => null);

    updateActiveAccount((account) => ({
      ...account,
      profile: draftProfile,
      name: draftProfile.fullName || account.name,
    }));
    notify('Profile saved locally.');
    addActivity({
      label: 'Profile Updated',
      detail: `${draftProfile.fullName} profile saved to HKKO Gold`,
      amount: '+Profile',
      type: 'Deposit',
    });
    openSection('settings');
  };

  const updateProfilePicture = async (file: File | null) => {
    if (!file) {
      return;
    }

    const dataUrl = await readFileAsDataUrl(file);
    setDraftProfile((current) => ({
      ...current,
      avatarUrl: dataUrl,
    }));
  };

  const createLiveAccount = () => {
    if (!newAccountDraft.fullName.trim() || !newAccountDraft.email.trim()) {
      notify('Add a name and email to create a new account.');
      return;
    }

    const newAccount = createAccount(newAccountDraft);

    setAppState((currentState) => ({
      accounts: [newAccount, ...currentState.accounts],
      activeAccountId: newAccount.id,
    }));
    setDraftProfile(newAccount.profile);
    notify(`${newAccount.profile.fullName} account created and set active.`);
    setActiveSection('settings');
  };

  const exportReportStatement = (title: string) => {
    if (typeof window === 'undefined') {
      return;
    }

    const rows = [
      ['Statement', title],
      ['Account Name', profile.fullName || 'Guest Investor'],
      ['Generated At', new Date().toISOString()],
      ['Transaction Count', String(reportTransactionCount)],
      ['Net Flow', reportNetFlow.toFixed(2)],
      ['Total Inflow', reportPositiveFlow.toFixed(2)],
      ['Total Outflow', reportNegativeFlow.toFixed(2)],
      [''],
      ['Type', 'Detail', 'Amount', 'Time'],
      ...visibleActivities.slice(0, 50).map((activity) => [activity.type, activity.detail, activity.amount, activity.time]),
    ];

    const csv = rows
      .map((row) => row.map((cell) => `"${String(cell ?? '').replaceAll('"', '""')}"`).join(','))
      .join('\n');

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const fileName = `${title.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-${new Date().toISOString().slice(0, 10)}.csv`;
    const url = URL.createObjectURL(blob);
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = fileName;
    document.body.append(anchor);
    anchor.click();
    anchor.remove();
    URL.revokeObjectURL(url);
    notify(`${title} exported.`);
  };

  const dashboardNavItems: Array<{ label: string; key: SectionKey; icon: string }> = [
    { label: 'Dashboard', key: 'dashboard', icon: '⌂' },
    { label: 'Marketplace', key: 'marketplace', icon: '◫' },
    { label: 'My Portfolio', key: 'portfolio', icon: '◍' },
    { label: 'Gold Monetization Program', key: 'investment', icon: '◎' },
    { label: 'My Investments', key: 'myInvestments', icon: '◈' },
    { label: 'ROI Payments', key: 'roiPayments', icon: '◌' },
    { label: 'Reinvestment History', key: 'reinvestmentHistory', icon: '↺' },
    { label: 'Wallet', key: 'wallet', icon: '◉' },
    { label: 'Escrow (HKKO GOLD Pay)', key: 'escrow', icon: '▣' },
    { label: 'Transactions', key: 'transactions', icon: '▦' },
    { label: 'KYC Verification', key: 'verification', icon: '✓' },
    { label: 'Reports & Statements', key: 'reports', icon: '▤' },
    { label: 'Messages', key: 'messages', icon: '✉' },
    { label: 'Support Center', key: 'supportCenter', icon: '?' },
    { label: 'Settings', key: 'settings', icon: '⚙' },
  ];
  const scheduleRows = investmentCalendar.slice(0, 6);
  const timelineRows = [
    { label: 'Application Submitted', date: investmentJourney.applicationSubmittedAt, complete: Boolean(investmentJourney.applicationSubmittedAt) },
    { label: 'KYC / AML Verification', date: investmentJourney.kycCompletedAt, complete: Boolean(investmentJourney.kycCompletedAt) },
    { label: 'Validation Completed', date: investmentJourney.validatedAt, complete: Boolean(investmentJourney.validatedAt) },
    { label: 'Investment Funded', date: investmentJourney.fundedAt, complete: Boolean(investmentJourney.fundedAt) },
    { label: 'Monthly ROI Disbursement', date: investmentNextRoiPaymentDate, complete: investmentJourney.monthsElapsed > 0 },
    { label: 'Maturity', date: investmentMaturityDate, complete: Boolean(investmentJourney.maturityReachedAt || investmentJourney.maturityDecision) },
  ];
  const dashboardDocuments = [
    'Investment Agreement',
    'Risk Disclosure Statement',
    'Investment Certificate',
    'KYC & AML Compliance',
  ];

  return (
    <div className="app-shell">
      <aside className="sidebar panel">
        <button className="brand-lockup brand-lockup-button" type="button" onClick={() => openSection('dashboard')}>
          <div className="brand-mark">HKKO</div>
          <div>
            <p className="eyebrow">Gold Savings Program</p>
            <h1>Secure wealth in gold.</h1>
          </div>
        </button>

        <nav className="side-nav" aria-label="Primary">
          {dashboardNavItems.map((item) => (
            <button
              key={`${item.label}-${item.key}`}
              className={`nav-item ${activeSection === item.key ? 'active' : ''}`}
              type="button"
              onClick={() => openSection(item.key)}
            >
              <span className="nav-icon" aria-hidden="true">{item.icon}</span>
              <span>{item.label}</span>
              <span className="nav-dot" />
            </button>
          ))}
        </nav>

      </aside>

      <main className="main-stage">
        {activeSection === 'dashboard' ? (
          <section className="reference-dashboard" id="dashboard">
            <header className="reference-topbar">
              <article className="panel ref-price-card">
                <p>Gold Price (LBMA)</p>
                <strong>{formatMoney(liveGoldPrice)} /oz</strong>
                <span className={liveGoldPrice >= 2425 ? 'positive' : 'negative'}>
                  {liveGoldPrice >= 2425 ? '+' : ''}{((liveGoldPrice - 2425) / 2425 * 100).toFixed(2)}% ({formatPriceDelta(liveGoldPrice - 2425)})
                </span>
                <small>Updated {priceUpdatedLabel}</small>
              </article>

              <article className="panel ref-program-banner">
                <div className="ref-banner-coin" aria-hidden="true">◉</div>
                <div>
                  <p className="eyebrow">Gold Monetization Program</p>
                  <h3>Invest in gold. Earn {Number(investmentJourney.monthlyRoiRate * 100).toFixed(1)}% monthly ROI for {investmentJourney.contractDurationLabel}.</h3>
                </div>
                <button className="ghost-button" type="button" onClick={() => openSection('investment')}>Learn More</button>
              </article>

              <article className="panel ref-user-wallet">
                <div className="profile-chip compact-profile-chip">
                  <div className="avatar">
                    {profile.avatarUrl ? <img src={profile.avatarUrl} alt={profileHeading} /> : getInitials(profileHeading)}
                  </div>
                  <div>
                    <strong>{profileHeading}</strong>
                    <p className="subtle">{hasProfileIdentity ? profile.role : 'Create Profile'}</p>
                  </div>
                </div>
                <div className="ref-wallet-box">
                  <p>Wallet Balance</p>
                  <strong>{formatMoney(totalWalletBalance)}</strong>
                  <button className="mini-button" type="button" onClick={() => startPayment(500)}>Fund Wallet</button>
                </div>
              </article>
            </header>

            <section className="reference-stat-row">
              <article className="panel ref-stat-card"><p>Total Investment Portfolio</p><strong>{formatMoney(totalInvestmentPortfolio)}</strong><span>{investmentJourney.status}</span></article>
              <article className="panel ref-stat-card"><p>Total ROI Received</p><strong>{formatMoney(roiReceivedToDate)}</strong><span>{investmentJourney.roiPayments.length} Payments</span></article>
              <article className="panel ref-stat-card"><p>Next ROI Payment</p><strong>{formatMoney(nextPaymentAmount)}</strong><span>{formatDateLabel(investmentNextRoiPaymentDate)}</span></article>
              <article className="panel ref-stat-card"><p>Maturity Date</p><strong>{formatDateLabel(investmentMaturityDate)}</strong><span>{investmentJourney.contractDurationLabel}</span></article>
              <article className="panel ref-stat-card"><p>Program Status</p><strong className="positive">{investmentJourney.fundingStatus === 'funded' ? 'Active' : 'Pending'}</strong><span>{investmentJourney.validationStatus}</span></article>
            </section>

            <section className="reference-main-grid">
              <div className="reference-left-column">
                <article className="panel ref-overview-card">
                  <h3>Investment Overview</h3>
                  <div className="ref-overview-grid">
                    <p>Investment ID <strong>{investmentJourney.id}</strong></p>
                    <p>Investment Start Date <strong>{formatDateLabel(investmentStartDate)}</strong></p>
                    <p>Validation Completed <strong>{formatDateLabel(investmentJourney.validatedAt)}</strong></p>
                    <p>Contract Duration <strong>{investmentJourney.contractDurationLabel}</strong></p>
                    <p>Maturity Date <strong>{formatDateLabel(investmentMaturityDate)}</strong></p>
                    <p>Certificate No. <strong>{investmentJourney.investmentCertificateNumber}</strong></p>
                  </div>
                </article>

                <article className="panel ref-table-card">
                  <h3>Monthly ROI Payment Schedule</h3>
                  <div className="ref-table-head">
                    <span>No.</span><span>Due Date</span><span>Amount</span><span>Status</span><span>Reference</span>
                  </div>
                  {scheduleRows.map((row) => (
                    <div key={row.month} className="ref-table-row">
                      <span>{row.month}</span>
                      <span>{formatDateLabel(row.paymentDate)}</span>
                      <span>{formatMoney(row.amountPaid)}</span>
                      <span className={row.paymentStatus === 'Paid' ? 'positive' : ''}>{row.paymentStatus}</span>
                      <span>{row.transactionReference}</span>
                    </div>
                  ))}
                </article>
              </div>

              <div className="reference-middle-column">
                <article className="panel ref-portfolio-card">
                  <h3>Investment Portfolio</h3>
                  <div className="ref-portfolio-body">
                    <div className="ref-ring" style={{ ['--ring-progress' as string]: `${investmentMaturityProgress}%` }}>
                      <span>{investmentMaturityProgress.toFixed(0)}%</span>
                    </div>
                    <div className="ref-portfolio-list">
                      <p>Principal Amount <strong>{formatMoney(investmentJourney.principal)}</strong></p>
                      <p>ROI Received to Date <strong>{formatMoney(roiReceivedToDate)}</strong></p>
                      <p>Remaining ROI Payments <strong>{remainingRoiPayments} of {investmentJourney.termMonths}</strong></p>
                      <p>Next Payment Amount <strong>{formatMoney(nextPaymentAmount)}</strong></p>
                      <p>Total ROI (12 Months) <strong>{formatMoney(investmentJourney.monthlyDistribution * investmentJourney.termMonths)}</strong></p>
                      <p>Total Return <strong>{formatMoney(totalInvestmentPortfolio)}</strong></p>
                    </div>
                  </div>
                </article>

                <article className="panel ref-timeline-card">
                  <h3>Investment Progress Timeline</h3>
                  <div className="ref-timeline-list">
                    {timelineRows.map((step, index) => (
                      <div key={step.label} className={`ref-timeline-item ${step.complete ? 'complete' : ''}`}>
                        <span>{index + 1}</span>
                        <div>
                          <strong>{step.label}</strong>
                          <p>{formatDateLabel(step.date)}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </article>
              </div>

              <aside className="reference-right-column">
                <article className="panel ref-maturity-card">
                  <h3>Maturity Options</h3>
                  <button className="ghost-button full-width" type="button" onClick={() => decideInvestmentMaturity('reinvest')}>Reinvest Principal</button>
                  <button className="ghost-button full-width" type="button" onClick={() => decideInvestmentMaturity('redeem')}>Redeem Principal</button>
                  <button className="mini-button full-width" type="button" onClick={() => openSection('investment')}>View Maturity Instructions</button>
                </article>

                <article className="panel ref-docs-card">
                  <div className="panel-header">
                    <h3>Important Documents</h3>
                    <button className="text-button" type="button" onClick={() => openSection('transactions')}>View All</button>
                  </div>
                  <div className="ref-doc-list">
                    {dashboardDocuments.map((entry) => (
                      <p key={entry}>{entry} <span>PDF</span></p>
                    ))}
                  </div>
                </article>

                <article className="panel ref-manager-card">
                  <h3>Your Relationship Manager</h3>
                  <strong>Diana Mensah</strong>
                  <p>Senior Relationship Manager</p>
                  <p>+233 24 123 4567</p>
                  <p>diana.mensah@hkkogold.com</p>
                  <button className="mini-button full-width" type="button" onClick={() => openSection('messages')}>Send Message</button>
                </article>
              </aside>
            </section>

            <footer className="footer-note">
              <p>© 2026 HKKO Investment Limited. Licensed & Regulated. AML/KYC Compliant. Secure 256-bit SSL Encryption.</p>
            </footer>
          </section>
        ) : null}
      </main>

      {paymentOpen ? (
        <div className="payment-backdrop" onClick={closePayment}>
          <section className="payment-panel panel" onClick={(event) => event.stopPropagation()}>
            <div className="section-page-header">
              <div>
                <p className="eyebrow">Wallet Top Up</p>
                <h3>Choose your payment method</h3>
              </div>
              <button className="ghost-button" type="button" onClick={closePayment}>
                Close
              </button>
            </div>

            <div className="payment-methods" role="tablist" aria-label="Payment methods">
              {(['Mobile Money', 'Visa Card', 'Mastercard'] as PaymentMethod[]).map((method) => (
                <button
                  key={method}
                  className={`method-tab ${paymentMethod === method ? 'active' : ''}`}
                  type="button"
                  onClick={() => setPaymentMethod(method)}
                >
                  {method}
                </button>
              ))}
            </div>

            <div className="payment-summary">
              <span>Amount to top up</span>
              <strong>{formatMoney(paymentAmount)}</strong>
            </div>

            {paymentError ? <p className="payment-note error">{paymentError}</p> : null}

            {paymentMethod === 'Mobile Money' ? (
              <div className="payment-form">
                <label>
                  Mobile Money Number
                  <input
                    placeholder="e.g. 0241234567"
                    value={paymentPhone}
                    onChange={(event) => setPaymentPhone(event.target.value)}
                  />
                </label>
                <label>
                  Provider
                  <select value={paymentNetwork} onChange={(event) => setPaymentNetwork(event.target.value)}>
                    <option value="MTN">MTN</option>
                    <option value="Telecel">Telecel</option>
                    <option value="AirtelTigo">AirtelTigo</option>
                  </select>
                </label>
              </div>
            ) : (
              <div className="payment-form">
                <label>
                  Cardholder Name
                  <input value={paymentCardName} onChange={(event) => setPaymentCardName(event.target.value)} />
                </label>
                <label>
                  Card Number
                  <input
                    placeholder="xxxx xxxx xxxx xxxx"
                    value={paymentCardNumber}
                    onChange={(event) => setPaymentCardNumber(event.target.value)}
                  />
                </label>
                <div className="payment-inline-fields">
                  <label>
                    Expiry
                    <input placeholder="MM/YY" value={paymentExpiry} onChange={(event) => setPaymentExpiry(event.target.value)} />
                  </label>
                  <label>
                    CVV
                    <input placeholder="***" value={paymentCvv} onChange={(event) => setPaymentCvv(event.target.value)} />
                  </label>
                </div>
              </div>
            )}

            <div className="profile-actions">
              <button className="primary-button" type="button" onClick={completePayment} disabled={paymentBusy}>
                {paymentBusy ? 'Initializing Payment...' : 'Pay and Top Up'}
              </button>
              <button className="ghost-button" type="button" onClick={closePayment} disabled={paymentBusy}>
                Cancel
              </button>
            </div>
          </section>
        </div>
      ) : null}

      <section className="assistant-dock" aria-label="HKKO AI assistant">
        <button className="assistant-pill" type="button" onClick={() => setAssistantOpen((current) => !current)}>
          <span className="assistant-dot" />
          <strong>Ask HKKO AI</strong>
        </button>

        {assistantOpen ? (
          <article className={`assistant-panel ${assistantExpanded ? 'expanded' : ''}`}>
            <header className="assistant-panel-header">
              <h3>HKKO AI Assistant</h3>
              <div className="assistant-panel-actions">
                <button
                  className="assistant-size-toggle"
                  type="button"
                  aria-pressed={assistantExpanded}
                  onClick={() => setAssistantExpanded((current) => !current)}
                >
                  {assistantExpanded ? 'Smaller' : 'Bigger'}
                </button>
                <button className="assistant-clear" type="button" onClick={clearAssistantChat}>
                  Clear
                </button>
                <button className="assistant-close" type="button" onClick={() => setAssistantOpen(false)}>
                  ×
                </button>
              </div>
            </header>

            <div className="assistant-body">
              <div className={`chat-window assistant-chat-window ${assistantExpanded ? 'expanded' : ''}`}>
                {chatMessages.slice(0, 5).map((message) => (
                  <div key={message.id} className={`chat-message ${message.role}`}>
                    <p>{message.text}</p>
                    <span>{message.time}</span>
                  </div>
                ))}
              </div>

              <div className="chat-prompts">
                {supportPrompts.map((prompt) => (
                  <button key={prompt} className="prompt-chip" type="button" onClick={() => sendChatMessage(prompt)}>
                    {prompt}
                  </button>
                ))}
              </div>

              <form
                className="chat-form assistant-chat-form"
                onSubmit={(event) => {
                  event.preventDefault();
                  sendChatMessage(chatInput);
                  setChatInput('');
                }}
              >
                <input
                  aria-label="Chat with HKKO AI assistant"
                  placeholder="Ask about savings, wallet, or verification..."
                  value={chatInput}
                  onChange={(event) => setChatInput(event.target.value)}
                />
                <button className="primary-button" type="submit">
                  Send
                </button>
              </form>
            </div>
          </article>
        ) : null}
      </section>

      {toast ? <div className="toast">{toast}</div> : null}

      {activeSection !== 'dashboard' ? (
        <section className="section-page panel" aria-labelledby="section-title">
          <div className="section-page-header">
            <div>
              <p className="eyebrow">{labelForSection(activeSection)}</p>
              <h3 id="section-title">{modalTitleForSection(activeSection)}</h3>
              <p className="subtle">{profile.fullName} · {profile.role}</p>
            </div>
            <div className="section-topbar-actions">
              <div className="price-chip compact">
                <p>Live Gold Price</p>
                <strong>{formatMoney(liveGoldPrice)} /oz</strong>
                <span className={liveGoldPrice >= 2425 ? 'positive' : 'negative'}>
                  {liveGoldPrice >= 2425 ? '+' : ''}{((liveGoldPrice - 2425) / 2425 * 100).toFixed(2)}%
                </span>
                <p className="subtle">Updated {priceUpdatedLabel}</p>
              </div>
              <button className="ghost-button" type="button" onClick={() => openSection('dashboard')}>
                Back to Dashboard
              </button>
            </div>
          </div>

          {activeSection === 'savings' ? (
            <div className="section-page-body">
              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Savings Plan</p>
                    <h3>{plan.name} accumulation</h3>
                  </div>
                  <span className="pill">{plan.cadence}</span>
                </div>
                <div className="plan-tabs modal-tabs">
                  {savingsPlans.map((entry) => (
                    <button
                      key={entry.name}
                      className={`plan-tab ${selectedPlan === entry.name ? 'active' : ''}`}
                      onClick={() => updateAccountPreferences({ selectedPlan: entry.name })}
                      type="button"
                    >
                      <strong>{entry.name}</strong>
                      <span>{entry.cadence}</span>
                    </button>
                  ))}
                </div>
                <div className="plan-details">
                  <div>
                    <p className="eyebrow">Current plan</p>
                    <h4>{plan.target}</h4>
                  </div>
                  <p>{plan.description}</p>
                </div>
                <div className="vault-progress">
                  <div className="progress-heading">
                    <span>Gold vault progress</span>
                    <strong>{progress.toFixed(0)}%</strong>
                  </div>
                  <div className="progress-track">
                    <div className="progress-fill" style={{ width: `${progress}%` }} />
                  </div>
                  <div className="progress-summary">
                    <span>{goldGrams.toFixed(3)} g secured</span>
                    <span>{targetGrams} g goal</span>
                  </div>
                </div>
              </article>

              <div className="security-card">
                <div>
                  <strong>Insured storage</strong>
                  <p>{serverStorage.coverage}</p>
                </div>
                <div>
                  <strong>Recommended rhythm</strong>
                  <p>Use the plan that matches your cash flow and deposit consistently.</p>
                </div>
                <div>
                  <strong>Settlement status</strong>
                  <p>Deposits stay pending until the backend confirms the payment gateway callback.</p>
                </div>
              </div>
            </div>
          ) : null}

          {activeSection === 'investment' ? (
            <div className="section-page-body investment-modal-body">
              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Investment Workflow</p>
                    <h3>{investmentJourney.productName}</h3>
                  </div>
                  <span className="pill">{investmentJourney.status}</span>
                </div>

                <div className="profile-form investment-form-grid">
                  <label>
                    Product name
                    <input value={investmentDraft.productName} onChange={(event) => setInvestmentDraft({ ...investmentDraft, productName: event.target.value })} />
                  </label>
                  <label>
                    Principal (GHS)
                    <input value={investmentDraft.principal} onChange={(event) => setInvestmentDraft({ ...investmentDraft, principal: event.target.value })} />
                  </label>
                  <label>
                    Term months
                    <input value={investmentDraft.termMonths} onChange={(event) => setInvestmentDraft({ ...investmentDraft, termMonths: event.target.value })} />
                  </label>
                  <label>
                    Monthly ROI rate (%)
                    <input value={investmentDraft.monthlyRoiRate} onChange={(event) => setInvestmentDraft({ ...investmentDraft, monthlyRoiRate: event.target.value })} />
                  </label>
                </div>

                {investmentError ? <p className="payment-note error">{investmentError}</p> : null}
                {investmentSuccess ? <p className="payment-note warning">{investmentSuccess}</p> : null}

                <div className="investment-step-grid">
                  <div className="investment-step-card">
                    <strong>1. Register account</strong>
                    <p>Create the live investment profile.</p>
                    <button className="primary-button" type="button" onClick={registerInvestment} disabled={investmentBusy}>
                      Register Account
                    </button>
                  </div>
                  <div className="investment-step-card">
                    <strong>2. Complete KYC / AML</strong>
                    <p>Verify identity before application review.</p>
                    <button className="ghost-button" type="button" onClick={completeInvestmentKyc} disabled={investmentBusy}>
                      Complete KYC / AML
                    </button>
                  </div>
                  <div className="investment-step-card">
                    <strong>3. Submit application</strong>
                    <p>Send the application for review.</p>
                    <button className="ghost-button" type="button" onClick={submitInvestmentApplication} disabled={investmentBusy}>
                      Submit Application
                    </button>
                  </div>
                  <div className="investment-step-card">
                    <strong>4. Pass validation</strong>
                    <p>Approval confirms the investment can proceed.</p>
                    <button className="ghost-button" type="button" onClick={validateInvestment} disabled={investmentBusy}>
                      Pass Validation
                    </button>
                  </div>
                  <div className="investment-step-card">
                    <strong>5. Sign agreement</strong>
                    <p>Sign the investment agreement before funding.</p>
                    <button className="ghost-button" type="button" onClick={signInvestmentAgreement} disabled={investmentBusy}>
                      Sign Agreement
                    </button>
                  </div>
                  <div className="investment-step-card">
                    <strong>6. Fund investment</strong>
                    <p>Move principal from wallet into the live investment.</p>
                    <button className="ghost-button" type="button" onClick={fundInvestment} disabled={investmentBusy}>
                      Fund Investment
                    </button>
                  </div>
                </div>

                <div className="profile-actions">
                  <button className="primary-button" type="button" onClick={recordMonthlyRoi} disabled={investmentBusy || investmentJourney.fundingStatus !== 'funded'}>
                    Track Monthly ROI
                  </button>
                  <button className="ghost-button" type="button" onClick={() => decideInvestmentMaturity('reinvest')} disabled={investmentBusy || investmentJourney.monthsElapsed < investmentJourney.termMonths}>
                    Reinvest at Maturity
                  </button>
                  <button className="ghost-button" type="button" onClick={() => decideInvestmentMaturity('redeem')} disabled={investmentBusy || investmentJourney.monthsElapsed < investmentJourney.termMonths}>
                    Redeem Principal
                  </button>
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Live Status</p>
                    <h3>Track every milestone in one place</h3>
                  </div>
                </div>

                <div className="security-card investment-status-card">
                  <div>
                    <strong>Registration</strong>
                    <p>{investmentJourney.registrationCompletedAt ? 'Completed' : 'Pending'}</p>
                  </div>
                  <div>
                    <strong>KYC / AML</strong>
                    <p>{investmentJourney.kycStatus}</p>
                  </div>
                  <div>
                    <strong>Validation</strong>
                    <p>{investmentJourney.validationStatus}</p>
                  </div>
                  <div>
                    <strong>Agreement</strong>
                    <p>{investmentJourney.agreementStatus}</p>
                  </div>
                  <div>
                    <strong>Funding</strong>
                    <p>{investmentJourney.fundingStatus}</p>
                  </div>
                  <div>
                    <strong>Maturity</strong>
                    <p>{investmentJourney.maturityDecision ? getInvestmentDecisionLabel(investmentJourney) : investmentJourney.maturityStatus}</p>
                  </div>
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">ROI Ledger</p>
                    <h3>Monthly ROI payments</h3>
                  </div>
                </div>
                <div className="activity-list modal-list investment-ledger-list">
                  {investmentJourney.roiPayments.length ? investmentJourney.roiPayments.map((payment) => (
                    <div key={payment.id} className="activity-item">
                      <div className="activity-badge" data-type="Deposit">
                        %
                      </div>
                      <div className="activity-copy">
                        <strong>Month {payment.month}</strong>
                        <p>{new Date(payment.paidAt).toLocaleDateString()}</p>
                      </div>
                      <div className="activity-meta">
                        <strong className="positive">+{formatMoney(payment.amount)}</strong>
                        <span>ROI</span>
                      </div>
                    </div>
                  )) : <p className="empty-state">No ROI payments recorded yet.</p>}
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'wallet' ? (
            <div className="section-page-body wallet-modal-body">
              <article className="panel section-card">
                <div className="wallet-summary">
                  <div>
                    <p>Total Wallet Balance</p>
                    <strong>{formatMoney(totalWalletBalance)}</strong>
                    <span>Cash + gold vault value</span>
                  </div>
                  <div className="wallet-art">HKKO PAY</div>
                </div>
                <div className="wallet-actions modal-actions">
                  <button className="ghost-button" type="button" onClick={() => startPayment(250)}>
                    Deposit GHS 250
                  </button>
                  <button className="ghost-button" type="button" onClick={transferToVault}>
                    Move to Gold Vault
                  </button>
                  <button className="ghost-button" type="button" onClick={sellGold}>
                    Sell Gold Now
                  </button>
                </div>
              </article>

              <div className="security-card">
                <div>
                  <strong>Wallet security protocols</strong>
                  <p>Deposits route through the backend and only settle after payment verification.</p>
                </div>
                <div>
                  <strong>Mobile money withdrawals</strong>
                  <p>Withdrawal requests are queued server-side and require processing before release.</p>
                </div>
                <div>
                  <strong>Insured storage</strong>
                  <p>{serverStorage.provider}</p>
                </div>
              </div>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Recent Wallet Activity</p>
                    <h3>Deposits, withdrawals, and settlement events</h3>
                  </div>
                </div>
                <div className="activity-list modal-list">
                  {visibleActivities.slice(0, 5).map((activity) => (
                    <div key={activity.id} className="activity-item">
                      <div className="activity-badge" data-type={activity.type as ActivityType}>
                        {iconFor(activity.type as ActivityType)}
                      </div>
                      <div className="activity-copy">
                        <strong>{activity.label}</strong>
                        <p>{activity.detail}</p>
                      </div>
                      <div className="activity-meta">
                        <strong className={String(activity.amount).startsWith('+') ? 'positive' : 'negative'}>{activity.amount}</strong>
                        <span>{activity.time}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'marketplace' ? (
            <div className="section-page-body">
              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Marketplace</p>
                    <h3>Verified live gold listings</h3>
                  </div>
                </div>
                <div className="table-shell">
                  <div className="table-head table-row">
                    <span>Seller</span>
                    <span>Country</span>
                    <span>Purity</span>
                    <span>Quantity</span>
                    <span>Price / oz</span>
                    <span>Delivery</span>
                    <span>Verification</span>
                    <span />
                  </div>
                  {filteredListings.map((row) => (
                    <div key={row.seller} className="table-row">
                      <span>{row.seller}</span>
                      <span>{row.country}</span>
                      <span>{row.purity}</span>
                      <span>{row.quantity}</span>
                      <span>{row.price}</span>
                      <span>{row.delivery}</span>
                      <span>{row.verification}</span>
                      <button className="table-button" type="button" onClick={buyGold}>
                        Buy
                      </button>
                    </div>
                  ))}
                  {!filteredListings.length ? <p className="empty-state">No marketplace listings matched your search.</p> : null}
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Market Overview</p>
                    <h3>Country and purity highlights</h3>
                  </div>
                </div>
                <div className="market-list">
                  {marketOverview.map((item) => (
                    <div key={item.label} className="market-item">
                      <div>
                        <span>{item.label}</span>
                        <strong>{item.value}</strong>
                      </div>
                      <p>{item.stat}</p>
                    </div>
                  ))}
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'portfolio' ? (
            <div className="section-page-body">
              <section className="stats-grid">
                <MetricCard label="Total Portfolio" value={formatMoney(totalInvestmentPortfolio)} note="Principal + ROI received" tone="gold" />
                <MetricCard label="Gold Holdings" value={`${goldGrams.toFixed(3)} g`} note={`≈ ${formatMoney(goldValue)}`} tone="emerald" />
                <MetricCard label="Cash Balance" value={formatMoney(walletCash)} note="Available in wallet" tone="burgundy" />
                <MetricCard label="Portfolio Progress" value={`${investmentMaturityProgress.toFixed(0)}%`} note="Investment maturity" tone="amber" />
              </section>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">My Portfolio</p>
                    <h3>Allocation and growth summary</h3>
                  </div>
                </div>
                <div className="security-card">
                  <div>
                    <strong>Active product</strong>
                    <p>{investmentJourney.productName}</p>
                  </div>
                  <div>
                    <strong>Principal</strong>
                    <p>{formatMoney(investmentJourney.principal)}</p>
                  </div>
                  <div>
                    <strong>Total ROI Paid</strong>
                    <p>{formatMoney(roiReceivedToDate)}</p>
                  </div>
                  <div>
                    <strong>Current plan</strong>
                    <p>{plan.name} ({plan.cadence})</p>
                  </div>
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'myInvestments' ? (
            <div className="section-page-body investment-modal-body">
              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">My Investments</p>
                    <h3>{investmentJourney.productName}</h3>
                  </div>
                  <span className="pill">{investmentJourney.status}</span>
                </div>
                <div className="security-card investment-status-card">
                  <div><strong>Registration</strong><p>{investmentJourney.registrationCompletedAt ? 'Completed' : 'Pending'}</p></div>
                  <div><strong>KYC / AML</strong><p>{investmentJourney.kycStatus}</p></div>
                  <div><strong>Application</strong><p>{investmentJourney.applicationStatus}</p></div>
                  <div><strong>Validation</strong><p>{investmentJourney.validationStatus}</p></div>
                  <div><strong>Funding</strong><p>{investmentJourney.fundingStatus}</p></div>
                  <div><strong>Maturity</strong><p>{investmentJourney.maturityDecision ? getInvestmentDecisionLabel(investmentJourney) : investmentJourney.maturityStatus}</p></div>
                </div>
                <div className="profile-actions">
                  <button className="primary-button" type="button" onClick={() => openSection('investment')}>Open Investment Workflow</button>
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'roiPayments' ? (
            <div className="section-page-body">
              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">ROI Payments</p>
                    <h3>Monthly payout ledger</h3>
                  </div>
                </div>
                <div className="activity-list modal-list investment-ledger-list">
                  {investmentJourney.roiPayments.length ? investmentJourney.roiPayments.map((payment) => (
                    <div key={payment.id} className="activity-item">
                      <div className="activity-badge" data-type="Deposit">%</div>
                      <div className="activity-copy">
                        <strong>Month {payment.month}</strong>
                        <p>{new Date(payment.paidAt).toLocaleDateString()}</p>
                      </div>
                      <div className="activity-meta">
                        <strong className="positive">+{formatMoney(payment.amount)}</strong>
                        <span>{payment.transactionReference}</span>
                      </div>
                    </div>
                  )) : <p className="empty-state">No ROI payments recorded yet.</p>}
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'reinvestmentHistory' ? (
            <div className="section-page-body">
              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Reinvestment History</p>
                    <h3>Maturity decisions and rollover events</h3>
                  </div>
                </div>
                <div className="activity-list modal-list">
                  {investmentJourney.maturityDecision ? (
                    <div className="activity-item">
                      <div className="activity-badge" data-type="Transfer">↺</div>
                      <div className="activity-copy">
                        <strong>{getInvestmentDecisionLabel(investmentJourney)}</strong>
                        <p>{investmentJourney.productName}</p>
                      </div>
                      <div className="activity-meta">
                        <strong>{formatDateLabel(investmentJourney.maturityDecidedAt)}</strong>
                        <span>Maturity decision</span>
                      </div>
                    </div>
                  ) : (
                    <p className="empty-state">No reinvestment history yet. Decisions appear here at maturity.</p>
                  )}
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'escrow' ? (
            <div className="section-page-body wallet-modal-body">
              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Escrow (HKKO GOLD Pay)</p>
                    <h3>Funds under settlement protection</h3>
                  </div>
                </div>
                <div className="security-card">
                  <div>
                    <strong>Pending balance</strong>
                    <p>{formatMoney(pendingBalance)}</p>
                  </div>
                  <div>
                    <strong>Insured vault status</strong>
                    <p>{serverStorage.coverage}</p>
                  </div>
                  <div>
                    <strong>Settlement model</strong>
                    <p>Gateway validation before release into available wallet cash.</p>
                  </div>
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'reports' ? (
            <div className="section-page-body reports-page">
              <article className="panel section-card reports-hero-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Reports & Statements</p>
                    <h3>Compliance, statements, and audit trail</h3>
                    <p className="subtle">Download account records, track settlement movement, and review storage controls from one screen.</p>
                  </div>
                  <span className="pill">Audit Ready</span>
                </div>

                <section className="reports-kpi-grid">
                  <div className="reports-kpi-card">
                    <p>Total Transactions</p>
                    <strong>{reportTransactionCount}</strong>
                    <span>Ledger events recorded</span>
                  </div>
                  <div className="reports-kpi-card">
                    <p>Net Flow</p>
                    <strong className={reportNetFlow >= 0 ? 'positive' : 'negative'}>{formatMoney(reportNetFlow)}</strong>
                    <span>Inflow minus outflow</span>
                  </div>
                  <div className="reports-kpi-card">
                    <p>Total Inflow</p>
                    <strong>{formatMoney(reportPositiveFlow)}</strong>
                    <span>Credits to account</span>
                  </div>
                  <div className="reports-kpi-card">
                    <p>Total Outflow</p>
                    <strong>{formatMoney(reportNegativeFlow)}</strong>
                    <span>Debits and settlements</span>
                  </div>
                  <div className="reports-kpi-card">
                    <p>Order Requests</p>
                    <strong>{reportOrderCount}</strong>
                    <span>Payment and wallet requests</span>
                  </div>
                </section>
              </article>

              <section className="reports-main-grid">
                <article className="panel section-card">
                  <div className="panel-header">
                    <div>
                      <p className="eyebrow">Statement Exports</p>
                      <h3>Available report packs</h3>
                    </div>
                  </div>

                  <div className="reports-statement-list">
                    {[
                      'Monthly account statement',
                      'Wallet inflow and outflow report',
                      'Gold holdings and valuation statement',
                      'Compliance and KYC status summary',
                    ].map((title) => (
                      <div key={title} className="reports-statement-item">
                        <div>
                          <strong>{title}</strong>
                          <p className="subtle">Prepared in PDF and CSV export format.</p>
                        </div>
                        <button className="ghost-button" type="button" onClick={() => exportReportStatement(title)}>Export</button>
                      </div>
                    ))}
                  </div>
                </article>

                <aside className="panel section-card reports-compliance-card">
                  <div className="panel-header">
                    <div>
                      <p className="eyebrow">Compliance Snapshot</p>
                      <h3>Storage and retention controls</h3>
                    </div>
                  </div>
                  <div className="security-card verification-status-cards">
                    <div>
                      <strong>Transaction model</strong>
                      <p>{transactionStorage.model}</p>
                    </div>
                    <div>
                      <strong>Integrity</strong>
                      <p>{transactionStorage.integrity}</p>
                    </div>
                    <div>
                      <strong>Retention</strong>
                      <p>{transactionStorage.retention}</p>
                    </div>
                    <div>
                      <strong>Storage location</strong>
                      <p>{transactionStorage.location}</p>
                    </div>
                    <div>
                      <strong>Backup file</strong>
                      <p>{backupStatus.lastBackupFile ?? 'None yet'}</p>
                    </div>
                    <div>
                      <strong>Last backup</strong>
                      <p>{backupStatus.lastBackupAt ? formatDateLabel(backupStatus.lastBackupAt) : 'No backup metadata yet'}</p>
                    </div>
                  </div>
                </aside>
              </section>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Recent Ledger Events</p>
                    <h3>Latest transaction and order records</h3>
                  </div>
                </div>

                <div className="activity-list modal-list">
                  {(visibleActivities.length ? visibleActivities.slice(0, 6) : []).map((activity) => (
                    <div key={activity.id} className="activity-item">
                      <div className="activity-badge" data-type={activity.type}>
                        {iconFor(activity.type)}
                      </div>
                      <div className="activity-copy">
                        <strong>{activity.label}</strong>
                        <p>{activity.detail}</p>
                      </div>
                      <div className="activity-meta">
                        <strong className={activity.amount.startsWith('+') ? 'positive' : 'negative'}>{activity.amount}</strong>
                        <span>{activity.time}</span>
                      </div>
                    </div>
                  ))}
                  {!visibleActivities.length ? <p className="empty-state">No ledger activity is available yet for this account.</p> : null}
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'messages' ? (
            <div className="section-page-body">
              <article className="panel section-card chat-panel">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Messages</p>
                    <h3>Conversation center</h3>
                  </div>
                </div>
                <div className="chat-window">
                  {chatMessages.map((message) => (
                    <div key={message.id} className={`chat-message ${message.role}`}>
                      <p>{message.text}</p>
                      <span>{message.time}</span>
                    </div>
                  ))}
                </div>

                <div className="chat-prompts">
                  {supportPrompts.map((prompt) => (
                    <button key={prompt} className="prompt-chip" type="button" onClick={() => sendChatMessage(prompt)}>
                      {prompt}
                    </button>
                  ))}
                </div>

                <form
                  className="chat-form"
                  onSubmit={(event) => {
                    event.preventDefault();
                    sendChatMessage(chatInput);
                    setChatInput('');
                  }}
                >
                  <input
                    aria-label="Message input"
                    placeholder="Type a message..."
                    value={chatInput}
                    onChange={(event) => setChatInput(event.target.value)}
                  />
                  <button className="primary-button" type="submit">
                    Send
                  </button>
                </form>
              </article>
            </div>
          ) : null}

          {activeSection === 'supportCenter' ? (
            <div className="section-page-body support-center-page">
              <article className="panel section-card support-center-hero">
                <div>
                  <p className="eyebrow">Support Center</p>
                  <h3>Premium customer care for every account stage</h3>
                  <p className="subtle">
                    Get portfolio assistance, payment support, verification help, and escalation coverage from the HKKO team.
                  </p>
                </div>
                <div className="support-hero-badges">
                  <span className="pill">Avg. response: 8 minutes</span>
                  <span className="pill muted">24/7 account monitoring</span>
                  <span className="pill">Priority for verified users</span>
                </div>
              </article>

              <div className="support-center-grid">
                <article className="panel section-card">
                  <div className="panel-header">
                    <div>
                      <p className="eyebrow">Relationship Manager</p>
                      <h3>Diana Mensah</h3>
                    </div>
                  </div>

                  <div className="support-profile-card">
                    <div className="support-manager-avatar">DM</div>
                    <div>
                      <strong>Senior Relationship Manager</strong>
                      <p className="subtle">Institutional portfolios, onboarding, and settlement guidance.</p>
                    </div>
                  </div>

                  <div className="support-contact-list">
                    <div>
                      <span>Direct line</span>
                      <strong>+233 24 123 4567</strong>
                    </div>
                    <div>
                      <span>Email</span>
                      <strong>diana.mensah@hkkogold.com</strong>
                    </div>
                    <div>
                      <span>Service window</span>
                      <strong>Mon - Sun, 24 Hours</strong>
                    </div>
                  </div>

                  <div className="profile-actions support-actions-row">
                    <button className="primary-button" type="button" onClick={() => openSection('messages')}>
                      Message Manager
                    </button>
                    <button className="ghost-button" type="button" onClick={() => openSection('wallet')}>
                      Payment Help
                    </button>
                  </div>
                </article>

                <article className="panel section-card">
                  <div className="panel-header">
                    <div>
                      <p className="eyebrow">Quick Help</p>
                      <h3>Popular support requests</h3>
                    </div>
                  </div>

                  <div className="support-topic-grid">
                    <button className="support-topic" type="button" onClick={() => openSection('verification')}>
                      <strong>KYC Verification</strong>
                      <p>Upload documents, confirm phone OTP, and track review status.</p>
                    </button>
                    <button className="support-topic" type="button" onClick={() => openSection('reports')}>
                      <strong>Statements & Reports</strong>
                      <p>Review transaction logs, retention policy, and backup metadata.</p>
                    </button>
                    <button className="support-topic" type="button" onClick={() => openSection('escrow')}>
                      <strong>Escrow Settlements</strong>
                      <p>Check pending deposits and settlement workflows.</p>
                    </button>
                    <button className="support-topic" type="button" onClick={() => openSection('settings')}>
                      <strong>Profile & Security</strong>
                      <p>Update account profile, enable 2FA, and manage authentication.</p>
                    </button>
                  </div>

                  <div className="support-faq">
                    <h4>Frequently Asked Questions</h4>
                    <details>
                      <summary>How fast are wallet deposits reflected?</summary>
                      <p>Deposits appear in pending balance instantly and move to available cash after gateway confirmation.</p>
                    </details>
                    <details>
                      <summary>How do I recover access if I fail 2FA?</summary>
                      <p>Open Settings, request a new 2FA setup code, and verify through your registered email or phone.</p>
                    </details>
                    <details>
                      <summary>Where do I find ROI and maturity records?</summary>
                      <p>Open ROI Payments and Reinvestment History from the sidebar to view monthly payouts and maturity decisions.</p>
                    </details>
                  </div>
                </article>
              </div>

              <article className="panel section-card support-cta-bar">
                <div>
                  <p className="eyebrow">Need immediate help?</p>
                  <h4>Open live messages to chat with support and AI in one thread.</h4>
                </div>
                <div className="profile-actions">
                  <button className="primary-button" type="button" onClick={() => openSection('messages')}>
                    Open Messages
                  </button>
                  <button className="ghost-button" type="button" onClick={() => openSection('dashboard')}>
                    Return to Dashboard
                  </button>
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'transactions' ? (
            <div className="section-page-body">
              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Transaction History</p>
                    <h3>All wallet and asset events</h3>
                  </div>
                </div>
                <div className="activity-list modal-list">
                  {visibleActivities.slice(0, 8).map((activity) => (
                    <div key={activity.id} className="activity-item">
                      <div className="activity-badge" data-type={activity.type}>
                        {iconFor(activity.type)}
                      </div>
                      <div className="activity-copy">
                        <strong>{activity.label}</strong>
                        <p>{activity.detail}</p>
                      </div>
                      <div className="activity-meta">
                        <strong className={activity.amount.startsWith('+') ? 'positive' : 'negative'}>{activity.amount}</strong>
                        <span>{activity.time}</span>
                      </div>
                    </div>
                  ))}
                  {!visibleActivities.length ? <p className="empty-state">No transactions yet for this account.</p> : null}
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Order History</p>
                    <h3>Payment requests and account actions</h3>
                  </div>
                </div>
                <div className="activity-list modal-list">
                  {(serverOrders.length ? serverOrders : [{ id: 'empty', type: 'wallet', status: 'No orders yet', amount: 0, createdAt: new Date().toISOString() }]).map((order) => (
                    <div key={order.id} className="activity-item">
                      <div className="activity-badge" data-type="Transfer">
                        ◉
                      </div>
                      <div className="activity-copy">
                        <strong>{order.type}</strong>
                        <p>{order.status}</p>
                      </div>
                      <div className="activity-meta">
                        <strong>{formatMoney(order.amount)}</strong>
                        <span>{new Date(order.createdAt).toLocaleDateString()}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'verification' ? (
            <div className="section-page-body">
              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Verification Center</p>
                    <h3>Identity and compliance status</h3>
                  </div>
                </div>
                <div className="security-card">
                  {verificationSteps.map((step) => (
                    <div key={step}>
                      <strong>{step}</strong>
                      <p>Required before a customer can hold or redeem gold through HKKO.</p>
                    </div>
                  ))}
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Phone Verification</p>
                    <h3>Send and confirm your one-time code</h3>
                  </div>
                </div>

                <div className="verification-grid">
                  <label>
                    Phone number
                    <input value={draftProfile.phone} onChange={(event) => setDraftProfile({ ...draftProfile, phone: event.target.value })} placeholder="+233241234567" />
                  </label>
                  <label>
                    6-digit OTP code
                    <input value={verificationCode} onChange={(event) => setVerificationCode(event.target.value)} placeholder="Enter code" />
                  </label>
                </div>

                <div className="profile-actions">
                  <button className="primary-button" type="button" onClick={requestPhoneVerificationCode} disabled={verificationBusy}>
                    Send Code
                  </button>
                  <button className="ghost-button" type="button" onClick={confirmPhoneVerificationCode} disabled={verificationBusy}>
                    Confirm Code
                  </button>
                </div>

                <div className="security-card verification-status-cards">
                  <div>
                    <strong>Phone status</strong>
                    <p>{verificationState.phoneVerification.status}</p>
                  </div>
                  <div>
                    <strong>Last code sent</strong>
                    <p>{verificationState.phoneVerification.lastSentAt ? formatDateLabel(verificationState.phoneVerification.lastSentAt) : 'Not sent yet'}</p>
                  </div>
                  <div>
                    <strong>Verified at</strong>
                    <p>{verificationState.phoneVerification.verifiedAt ? formatDateLabel(verificationState.phoneVerification.verifiedAt) : 'Pending verification'}</p>
                  </div>
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">KYC Documents</p>
                    <h3>Upload ID card and passport files</h3>
                  </div>
                </div>

                <div className="verification-grid verification-upload-grid">
                  <label>
                    ID card (front)
                    <input
                      type="file"
                      accept="image/png,image/jpeg,image/webp,application/pdf"
                      onChange={(event) => setIdCardFrontFile(event.target.files?.[0] ?? null)}
                    />
                  </label>
                  <label>
                    ID card (back)
                    <input
                      type="file"
                      accept="image/png,image/jpeg,image/webp,application/pdf"
                      onChange={(event) => setIdCardBackFile(event.target.files?.[0] ?? null)}
                    />
                  </label>
                  <label>
                    Passport
                    <input
                      type="file"
                      accept="image/png,image/jpeg,image/webp,application/pdf"
                      onChange={(event) => setPassportFile(event.target.files?.[0] ?? null)}
                    />
                  </label>
                </div>

                <div className="profile-actions">
                  <button className="primary-button" type="button" onClick={submitKycDocuments} disabled={verificationBusy}>
                    Submit KYC Documents
                  </button>
                </div>

                <div className="security-card verification-status-cards">
                  <div>
                    <strong>Documents status</strong>
                    <p>{verificationState.documents.status}</p>
                  </div>
                  <div>
                    <strong>KYC status</strong>
                    <p>{verificationState.kyc.status}</p>
                  </div>
                  <div>
                    <strong>Submitted at</strong>
                    <p>{verificationState.documents.submittedAt ? formatDateLabel(verificationState.documents.submittedAt) : 'Not submitted yet'}</p>
                  </div>
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Anti-Fraud Checks</p>
                    <h3>Automated risk screening results</h3>
                  </div>
                </div>

                <div className="security-card verification-status-cards">
                  <div>
                    <strong>Fraud status</strong>
                    <p>{verificationState.antiFraud.status}</p>
                  </div>
                  <div>
                    <strong>Risk score</strong>
                    <p>{verificationState.antiFraud.score}</p>
                  </div>
                  <div>
                    <strong>Reviewed at</strong>
                    <p>{verificationState.antiFraud.reviewedAt ? formatDateLabel(verificationState.antiFraud.reviewedAt) : 'Awaiting checks'}</p>
                  </div>
                </div>

                {verificationState.antiFraud.flags.length ? (
                  <div className="activity-list">
                    {verificationState.antiFraud.flags.map((flag) => (
                      <div key={flag} className="activity-item">
                        <div className="activity-badge" data-type="Withdraw">
                          !
                        </div>
                        <div className="activity-copy">
                          <strong>Flag</strong>
                          <p>{flag}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="empty-state">No fraud flags detected so far.</p>
                )}
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Security Standards</p>
                    <h3>Compliance and controls overview</h3>
                  </div>
                </div>
                <div className="activity-list">
                  {securityStandards.map((standard) => (
                    <div key={standard.name} className="activity-item">
                      <div className="activity-badge" data-type="Deposit">
                        ✓
                      </div>
                      <div className="activity-copy">
                        <strong>{standard.name}</strong>
                        <p>{standard.detail}</p>
                      </div>
                      <div className="activity-meta">
                        <strong>{standard.status}</strong>
                      </div>
                    </div>
                  ))}
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Backup & Recovery</p>
                    <h3>Data backup and disaster recovery</h3>
                  </div>
                </div>
                <div className="security-card verification-status-cards">
                  <div>
                    <strong>Backup retention</strong>
                    <p>{backupStatus.retention || 0} snapshots</p>
                  </div>
                  <div>
                    <strong>Last backup</strong>
                    <p>{backupStatus.lastBackupAt ? formatDateLabel(backupStatus.lastBackupAt) : 'No backup metadata yet'}</p>
                  </div>
                  <div>
                    <strong>Latest file</strong>
                    <p>{backupStatus.lastBackupFile ?? 'None yet'}</p>
                  </div>
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Transaction Storage</p>
                    <h3>How transaction records are stored</h3>
                  </div>
                </div>
                <div className="security-card verification-status-cards">
                  <div>
                    <strong>Model</strong>
                    <p>{transactionStorage.model}</p>
                  </div>
                  <div>
                    <strong>Integrity</strong>
                    <p>{transactionStorage.integrity}</p>
                  </div>
                  <div>
                    <strong>Location</strong>
                    <p>{transactionStorage.location}</p>
                  </div>
                  <div>
                    <strong>Retention</strong>
                    <p>{transactionStorage.retention}</p>
                  </div>
                </div>
              </article>

              {verificationError ? <p className="payment-note error">{verificationError}</p> : null}
              {verificationSuccess ? <p className="payment-note warning">{verificationSuccess}</p> : null}

              <div className="security-card">
                <div>
                  <strong>Insured storage</strong>
                  <p>{serverStorage.coverage}</p>
                </div>
                <div>
                  <strong>Notifications center</strong>
                  <p>{serverNotifications.length ? `${serverNotifications.length} unread or recent notices available.` : 'No security notices yet.'}</p>
                </div>
                <div>
                  <strong>Account status</strong>
                  <p>{sessionUser?.verified ? 'Verified and active' : 'Verification pending'}</p>
                </div>
              </div>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Notifications</p>
                    <h3>Security and system updates</h3>
                  </div>
                  <button className="ghost-button" type="button" onClick={markNotificationsRead}>
                    Mark All Read
                  </button>
                </div>
                <div className="activity-list modal-list">
                  {(serverNotifications.length ? serverNotifications : [{ id: 'empty', type: 'info', message: 'No notifications yet.', read: true, createdAt: new Date().toISOString() }]).map((notification) => (
                    <div key={notification.id} className="activity-item">
                      <div className="activity-badge" data-type="Deposit">
                        !
                      </div>
                      <div className="activity-copy">
                        <strong>{notification.type}</strong>
                        <p>{notification.message}</p>
                      </div>
                      <div className="activity-meta">
                        <strong className={notification.read ? 'positive' : 'negative'}>{notification.read ? 'Read' : 'New'}</strong>
                        <span>{new Date(notification.createdAt).toLocaleTimeString()}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </article>

              <article className="panel section-card">
                <div className="panel-header">
                  <div>
                    <p className="eyebrow">Security Emails</p>
                    <h3>Login alerts and account emails</h3>
                  </div>
                </div>
                <div className="activity-list modal-list">
                  {(securityEmails.length ? securityEmails : [{ id: 'empty', subject: 'No security emails yet.', body: 'Security alerts are sent after successful logins.', createdAt: new Date().toISOString() }]).map((entry) => (
                    <div key={entry.id} className="activity-item">
                      <div className="activity-badge" data-type="Transfer">
                        @
                      </div>
                      <div className="activity-copy">
                        <strong>{entry.subject}</strong>
                        <p>{entry.body}</p>
                      </div>
                      <div className="activity-meta">
                        <strong>Sent</strong>
                        <span>{new Date(entry.createdAt).toLocaleString()}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </article>
            </div>
          ) : null}

          {activeSection === 'settings' || activeSection === 'support' ? (
            <div className="section-page-body support-modal-body">
                <div className="profile-form">
                  <label className="profile-picture-field">
                    Profile picture
                    <input
                      type="file"
                      accept="image/*"
                      onChange={(event) => {
                        void updateProfilePicture(event.target.files?.[0] ?? null);
                        event.currentTarget.value = '';
                      }}
                    />
                  </label>
                  <div className="profile-picture-preview">
                    {draftProfile.avatarUrl ? <img src={draftProfile.avatarUrl} alt={`${draftProfile.fullName} profile preview`} /> : <span>{getInitials(draftProfile.fullName || profile.fullName)}</span>}
                  </div>
                  <label>
                    Full name
                    <input value={draftProfile.fullName} onChange={(event) => setDraftProfile({ ...draftProfile, fullName: event.target.value })} />
                  </label>
                  <label>
                    Email
                    <input value={draftProfile.email} onChange={(event) => setDraftProfile({ ...draftProfile, email: event.target.value })} />
                  </label>
                  <label>
                    Phone
                    <input value={draftProfile.phone} onChange={(event) => setDraftProfile({ ...draftProfile, phone: event.target.value })} />
                  </label>
                  <label>
                    Country
                    <input value={draftProfile.country} onChange={(event) => setDraftProfile({ ...draftProfile, country: event.target.value })} />
                  </label>
                  <label>
                    Account type
                    <input value={draftProfile.role} onChange={(event) => setDraftProfile({ ...draftProfile, role: event.target.value })} />
                  </label>
                </div>

                <div className="profile-actions">
                  <button className="primary-button" type="button" onClick={saveProfile}>
                    Save Profile
                  </button>
                  <button className="ghost-button" type="button" onClick={() => setDraftProfile(profile)}>
                    Reset Draft
                  </button>
                </div>

                <article className="auth-card">
                  <div className="panel-header compact-header">
                    <div>
                      <p className="eyebrow">Live Account Access</p>
                      <h4>Create or sign in to your real HKKO account</h4>
                    </div>
                  </div>

                  <div className="auth-mode-tabs" role="tablist" aria-label="Authentication mode">
                    <button className={authMode === 'signup' ? 'active' : ''} type="button" onClick={() => setAuthMode('signup')}>
                      Sign up
                    </button>
                    <button className={authMode === 'login' ? 'active' : ''} type="button" onClick={() => setAuthMode('login')}>
                      Log in
                    </button>
                  </div>

                  <div className="profile-form auth-form-grid">
                    {authMode === 'signup' ? (
                      <label>
                        Full name
                        <input value={authDraft.fullName} onChange={(event) => setAuthDraft({ ...authDraft, fullName: event.target.value })} />
                      </label>
                    ) : null}

                    <label>
                      Email
                      <input value={authDraft.email} onChange={(event) => setAuthDraft({ ...authDraft, email: event.target.value })} />
                    </label>

                    <label>
                      Password
                      <input
                        type="password"
                        placeholder={authMode === 'signup' ? 'Minimum 8 characters' : 'Enter your password'}
                        value={authDraft.password}
                        onChange={(event) => setAuthDraft({ ...authDraft, password: event.target.value })}
                      />
                    </label>

                    {authMode === 'signup' ? (
                      <>
                        <label>
                          Phone
                          <input value={authDraft.phone} onChange={(event) => setAuthDraft({ ...authDraft, phone: event.target.value })} />
                        </label>
                        <label>
                          Country
                          <input value={authDraft.country} onChange={(event) => setAuthDraft({ ...authDraft, country: event.target.value })} />
                        </label>
                        <label>
                          Account type
                          <input value={authDraft.role} onChange={(event) => setAuthDraft({ ...authDraft, role: event.target.value })} />
                        </label>
                      </>
                    ) : null}
                  </div>

                  {authError ? <p className="payment-note error">{authError}</p> : null}
                  {authSuccess ? <p className="payment-note warning">{authSuccess}</p> : null}

                  {pendingLogin2fa ? (
                    <div className="security-card verification-status-cards">
                      <div>
                        <strong>Two-Factor Required</strong>
                        <p>Enter the 6-digit code sent via {pendingLogin2fa.method.toUpperCase()}.</p>
                        {pendingLogin2fa.demoCode ? <p className="subtle">Demo code: {pendingLogin2fa.demoCode}</p> : null}
                      </div>
                      <label>
                        2FA code
                        <input value={login2faCode} onChange={(event) => setLogin2faCode(event.target.value)} placeholder="Enter 6-digit code" />
                      </label>
                      <button className="primary-button" type="button" onClick={completeLoginTwoFactor} disabled={authBusy}>
                        Verify 2FA and Log In
                      </button>
                    </div>
                  ) : null}

                  <div className="profile-actions">
                    <button className="primary-button" type="button" onClick={submitAuthForm} disabled={authBusy}>
                      {authBusy ? 'Please wait...' : authMode === 'signup' ? 'Create Live Account' : 'Log In to Live Account'}
                    </button>
                    {sessionUser ? (
                      <button className="ghost-button" type="button" onClick={logoutLiveSession} disabled={authBusy}>
                        Log Out Live Session
                      </button>
                    ) : null}
                    {sessionUser ? (
                      <button className="ghost-button" type="button" onClick={deleteLiveAccount} disabled={authBusy}>
                        Delete Live Account
                      </button>
                    ) : null}
                  </div>

                  {sessionUser ? (
                    <div className="security-card verification-status-cards">
                      <div>
                        <strong>Two-Factor Authentication</strong>
                        <p>{twoFactorStatus.enabled ? `Enabled (${twoFactorStatus.method.toUpperCase()})` : 'Disabled'}</p>
                      </div>
                      <div className="profile-actions">
                        <button className="ghost-button" type="button" onClick={() => sendTwoFactorSetupCode('email')} disabled={verificationBusy}>
                          Send Email 2FA Code
                        </button>
                        <button className="ghost-button" type="button" onClick={() => sendTwoFactorSetupCode('sms')} disabled={verificationBusy}>
                          Send SMS 2FA Code
                        </button>
                        {twoFactorStatus.enabled ? (
                          <button className="ghost-button" type="button" onClick={disableTwoFactor} disabled={verificationBusy}>
                            Disable 2FA
                          </button>
                        ) : null}
                      </div>
                      <label>
                        Setup code
                        <input value={twoFactorSetupCode} onChange={(event) => setTwoFactorSetupCode(event.target.value)} placeholder="Enter setup code" />
                      </label>
                      <button className="primary-button" type="button" onClick={confirmTwoFactorSetup} disabled={verificationBusy}>
                        Confirm and Enable 2FA
                      </button>
                    </div>
                  ) : null}

                  <div className="google-auth-stack">
                    <span className="eyebrow">or continue with Google</span>
                    {googleClientId ? (
                      <div className="google-button-host" ref={googleButtonHostRef} />
                    ) : (
                      <p className="subtle">Add VITE_GOOGLE_CLIENT_ID to your environment to enable Google sign-in.</p>
                    )}
                  </div>
                </article>

                <div className="account-center">
                  <div className="panel-header compact-header">
                    <div>
                      <p className="eyebrow">Live Accounts</p>
                      <h4>Switch between customer accounts</h4>
                    </div>
                    <button className="ghost-button" type="button" onClick={cycleAccount}>
                      Switch Account
                    </button>
                  </div>

                  <div className="account-list">
                    {appState.accounts.map((account) => (
                      <button
                        key={account.id}
                        className={`account-card ${account.id === appState.activeAccountId ? 'active' : ''}`}
                        type="button"
                        onClick={() => setActiveAccountId(account.id)}
                      >
                        <div>
                          <strong>{account.name}</strong>
                          <span>{account.profile.email}</span>
                        </div>
                        <small>{formatMoney(account.walletCash)}</small>
                      </button>
                    ))}
                  </div>

                  <div className="create-account-card">
                    <div className="panel-header compact-header">
                      <div>
                        <p className="eyebrow">Create Account</p>
                        <h4>Open a new live HKKO account</h4>
                      </div>
                    </div>

                    <div className="profile-form">
                      <label>
                        Full name
                        <input value={newAccountDraft.fullName} onChange={(event) => setNewAccountDraft({ ...newAccountDraft, fullName: event.target.value })} />
                      </label>
                      <label>
                        Email
                        <input value={newAccountDraft.email} onChange={(event) => setNewAccountDraft({ ...newAccountDraft, email: event.target.value })} />
                      </label>
                      <label>
                        Phone
                        <input value={newAccountDraft.phone} onChange={(event) => setNewAccountDraft({ ...newAccountDraft, phone: event.target.value })} />
                      </label>
                      <label>
                        Country
                        <input value={newAccountDraft.country} onChange={(event) => setNewAccountDraft({ ...newAccountDraft, country: event.target.value })} />
                      </label>
                      <label>
                        Account type
                        <input value={newAccountDraft.role} onChange={(event) => setNewAccountDraft({ ...newAccountDraft, role: event.target.value })} />
                      </label>
                    </div>

                    <div className="profile-actions">
                      <button className="primary-button" type="button" onClick={createLiveAccount}>
                        Create Live Account
                      </button>
                      <button
                        className="ghost-button"
                        type="button"
                        onClick={() =>
                          setNewAccountDraft({
                            fullName: '',
                            email: '',
                            phone: '',
                            country: 'Ghana',
                            role: 'Gold Saver',
                              avatarUrl: '',
                          })
                        }
                      >
                        Clear Draft
                      </button>
                    </div>
                  </div>
                </div>

                <div className={`chat-window ${assistantExpanded ? 'expanded' : ''}`}>
                  {chatMessages.map((message) => (
                    <div key={message.id} className={`chat-message ${message.role}`}>
                      <p>{message.text}</p>
                      <span>{message.time}</span>
                    </div>
                  ))}
                </div>

                <div className="assistant-panel-actions assistant-panel-actions-inline">
                  <button
                    className="assistant-size-toggle"
                    type="button"
                    aria-pressed={assistantExpanded}
                    onClick={() => setAssistantExpanded((current) => !current)}
                  >
                    {assistantExpanded ? 'Smaller' : 'Bigger'}
                  </button>
                </div>

                <div className="chat-prompts">
                  {supportPrompts.map((prompt) => (
                    <button key={prompt} className="prompt-chip" type="button" onClick={() => sendChatMessage(prompt)}>
                      {prompt}
                    </button>
                  ))}
                </div>

                <form
                  className="chat-form"
                  onSubmit={(event) => {
                    event.preventDefault();
                    sendChatMessage(chatInput);
                    setChatInput('');
                  }}
                >
                  <input
                    aria-label="Chat with HKKO AI"
                    placeholder="Type a question for HKKO AI..."
                    value={chatInput}
                    onChange={(event) => setChatInput(event.target.value)}
                  />
                  <button className="primary-button" type="submit">
                    Send
                  </button>
                </form>
              </div>
            ) : null}
        </section>
      ) : null}
    </div>
  );
}

function MetricCard({ label, value, note, tone }: { label: string; value: string; note: string; tone: string }) {
  return (
    <article className="panel metric-card">
      <span className={`metric-tone ${tone}`} />
      <p>{label}</p>
      <strong>{value}</strong>
      <span>{note}</span>
    </article>
  );
}

function Badge({ label }: { label: string }) {
  return <span className="badge">{label}</span>;
}

function getInitials(name: string) {
  return name
    .split(' ')
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? '')
    .join('');
}

function addMonthsIso(baseIso: string, months: number) {
  const date = new Date(baseIso);
  date.setMonth(date.getMonth() + months);
  return date.toISOString();
}

function addDaysIso(baseIso: string, days: number) {
  const date = new Date(baseIso);
  date.setDate(date.getDate() + days);
  return date.toISOString();
}

function formatDateLabel(value: string | null | undefined) {
  if (!value) {
    return 'Pending';
  }

  return new Date(value).toLocaleDateString(undefined, {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  });
}

function buildMonthlyRoiCalendar(journey: InvestmentJourney) {
  const baseDate = journey.investmentStartDate ?? journey.fundedAt ?? journey.registrationCompletedAt ?? new Date().toISOString();

  return Array.from({ length: journey.termMonths }, (_entry, index) => {
    const month = index + 1;
    const payment = journey.roiPayments.find((record) => record.month === month);
    const expectedDate = addMonthsIso(baseDate, month);
    const status = payment ? 'Paid' : new Date(expectedDate).getTime() <= Date.now() ? 'Due' : 'Pending';

    return {
      month,
      paymentDate: payment?.paymentDate ?? expectedDate,
      paymentStatus: status,
      amountPaid: payment?.amount ?? journey.monthlyDistribution,
      transactionReference: payment?.transactionReference ?? `ROI-${journey.id.slice(0, 8).toUpperCase()}-${String(month).padStart(2, '0')}`,
    };
  });
}

function getInvestmentDecisionLabel(journey: InvestmentJourney) {
  if (journey.maturityDecision === 'reinvest') {
    return 'Reinvested';
  }

  if (journey.maturityDecision === 'redeem') {
    return 'Redeemed';
  }

  return 'Pending';
}

function labelForSection(section: SectionKey) {
  switch (section) {
    case 'marketplace':
      return 'Marketplace';
    case 'portfolio':
      return 'My Portfolio';
    case 'myInvestments':
      return 'My Investments';
    case 'roiPayments':
      return 'ROI Payments';
    case 'reinvestmentHistory':
      return 'Reinvestment History';
    case 'escrow':
      return 'Escrow';
    case 'reports':
      return 'Reports & Statements';
    case 'messages':
      return 'Messages';
    case 'supportCenter':
      return 'Support Center';
    case 'settings':
      return 'Settings';
    case 'savings':
      return 'Savings Plan';
    case 'investment':
      return 'Investment';
    case 'wallet':
      return 'Wallet';
    case 'transactions':
      return 'Transactions';
    case 'verification':
      return 'Verification';
    case 'support':
      return 'Support';
    default:
      return 'Dashboard';
  }
}

function modalTitleForSection(section: SectionKey) {
  switch (section) {
    case 'marketplace':
      return 'Market listings';
    case 'portfolio':
      return 'Portfolio overview';
    case 'myInvestments':
      return 'Investment tracking';
    case 'roiPayments':
      return 'ROI payment history';
    case 'reinvestmentHistory':
      return 'Maturity and reinvestment log';
    case 'escrow':
      return 'Escrow settlement center';
    case 'reports':
      return 'Reports and statements';
    case 'messages':
      return 'Messages and chat';
    case 'supportCenter':
      return 'Support help center';
    case 'settings':
      return 'Profile and account settings';
    case 'savings':
      return 'Choose a savings plan';
    case 'investment':
      return 'Investment workflow';
    case 'wallet':
      return 'HKKO Pay Wallet';
    case 'transactions':
      return 'Recent activity';
    case 'verification':
      return 'Verification Center';
    case 'support':
      return 'Profile and AI support';
    default:
      return 'Dashboard overview';
  }
}

function matchesQuery(input: Record<string, unknown>, query: string) {
  if (!query) {
    return true;
  }

  return Object.values(input).some((value) => String(value).toLowerCase().includes(query));
}

function buildAssistantReply(
  message: string,
  context: { walletCash: number; goldGrams: number; liveGoldPrice: number; buyBackPrice: number },
) {
  const normalizedMessage = message.toLowerCase();

  if (normalizedMessage.includes('profile') || normalizedMessage.includes('register')) {
    return 'Open Support to create your profile, then save your details. Your account stays ready for KYC and wallet setup.';
  }

  if (normalizedMessage.includes('wallet') || normalizedMessage.includes('balance')) {
    return `Your available cash is ${formatMoney(context.walletCash)} and your vault holds ${context.goldGrams.toFixed(3)} g of gold.`;
  }

  if (normalizedMessage.includes('save') || normalizedMessage.includes('savings')) {
    return 'Choose Daily, Weekly, Monthly, or Flexible savings, then use deposits to build gold by grams over time.';
  }

  if (normalizedMessage.includes('sell') || normalizedMessage.includes('cash out')) {
    return `You can sell gold back instantly at about ${formatMoney(context.buyBackPrice)} per gram in this dashboard.`;
  }

  if (normalizedMessage.includes('buy')) {
    return `HKKO uses the live gold price of ${formatMoney(context.liveGoldPrice)} per ounce in the market header. Use Buy Gold to lock grams into storage.`;
  }

  if (normalizedMessage.includes('verify') || normalizedMessage.includes('kyc')) {
    return 'Verification includes identity, address, business, and AML/KYC checks before your account is fully activated.';
  }

  return 'I can help with savings plans, wallet actions, verification, profile setup, and instant gold resale. Try one of the suggested prompts.';
}

function formatMoney(amount: number) {
  return new Intl.NumberFormat('en-GH', {
    style: 'currency',
    currency: 'GHS',
    maximumFractionDigits: 2,
  }).format(amount);
}

function formatPriceDelta(amount: number) {
  const sign = amount >= 0 ? '+' : '-';

  return `${sign}GHS ${Math.abs(amount).toFixed(2)}`;
}

function iconFor(type: ActivityType) {
  switch (type) {
    case 'Deposit':
      return '↓';
    case 'Buy Gold':
      return '◈';
    case 'Sell Gold':
      return '↗';
    case 'Withdraw':
      return '⇣';
    case 'Transfer':
      return '⇄';
    default:
      return '•';
  }
}

export default App;
