"use client";

import {
  ArrowRight,
  BadgeDollarSign,
  Banknote,
  BriefcaseBusiness,
  Building2,
  Calculator,
  CarFront,
  Check,
  ChevronDown,
  ChevronRight,
  CircleDollarSign,
  Clock3,
  CreditCard,
  Camera,
  ExternalLink,
  FileText,
  Headphones,
  HeartHandshake,
  Home,
  Globe2,
  KeyRound,
  Landmark,
  LockKeyhole,
  Mail,
  MapPin,
  Menu,
  MessageCircle,
  PiggyBank,
  Search,
  ShieldCheck,
  Smartphone,
  TrendingUp,
  UserRound,
  WalletCards,
  X,
  Play,
} from "lucide-react";
import { FormEvent, useEffect, useMemo, useState } from "react";
import AccountOpeningForm from "./AccountOpeningForm";
import { DICTIONARY, LANGUAGES, Language, detectBrowserLanguage } from "@/lib/i18n";

const products = [
  {
    icon: WalletCards,
    title: "Checking",
    text: "Simple, flexible accounts made for everyday life—with no monthly maintenance fee options.",
    link: "Explore checking",
  },
  {
    icon: PiggyBank,
    title: "Savings",
    text: "Build your safety net and reach every milestone faster with competitive dividends.",
    link: "Explore savings",
  },
  {
    icon: Globe2,
    title: "Offshore Account",
    text: "Hold and manage funds across USD, GBP, EUR and CNY with one multi-currency account.",
    link: "Open offshore account",
  },
  {
    icon: CreditCard,
    title: "Credit Cards",
    text: "Earn rewards your way, enjoy low rates and keep more of what you earn.",
    link: "Compare cards",
  },
  {
    icon: CarFront,
    title: "Auto Loans",
    text: "Get on the road with fast decisions, flexible terms and rates designed around you.",
    link: "Shop auto loans",
  },
  {
    icon: Home,
    title: "Home Loans",
    text: "From first keys to forever homes, local experts are ready to guide your next move.",
    link: "View mortgages",
  },
  {
    icon: BriefcaseBusiness,
    title: "Business Banking",
    text: "Accounts, lending and treasury tools built to help local businesses move forward.",
    link: "Grow your business",
  },
];

const rates = [
  { name: "Auto loans", rate: "5.24%", detail: "APR as low as", action: "Get pre-approved" },
  { name: "Home equity", rate: "6.75%", detail: "APR as low as", action: "Use your equity" },
  { name: "12-month certificate", rate: "4.10%", detail: "APY", action: "Start saving" },
  { name: "Rewards credit card", rate: "12.49%", detail: "Variable APR as low as", action: "Compare cards" },
];

const quickLinks = [
  [MapPin, "Find a location"],
  [Calculator, "Financial calculators"],
  [CreditCard, "Make a loan payment"],
  [FileText, "Forms & disclosures"],
  [Headphones, "Contact us"],
];

const navItems = ["Bank", "Borrow", "Business", "Plan", "Why Trust World"];

const DEPOSIT_APPLICATION_URL = "https://access.meridianlink.com/pos/alabamacu_231226/deposit-accounts/new/getting-started?__hstc=152908262.20677da28ec26c67271a70ad6f01f357.1792231198394.1792231198394.1792231198394.1&__hssc=152908262.2.1792231198394&__hsfp=7b00c7bb125ef1ed73748f949c84bbc6&_gl=1*7cbqa0*_gcl_au*MTc1MzEyNTYzNi4xNzkyMjMxMTk2*_ga*MTU4NTMxMTg2Ni4xNzkyMjMxMTc1*_ga_T176JPJF4S*czE3OTIyMzExNzUkbzEkZzEkdDE3OTIyMzEyNjkkajMwJGwwJGgw";

type DepositAccount = "Checking" | "Savings" | "Offshore Account";

function Brand({ light = false }: { light?: boolean }) {
  return (
    <a href="#top" className="brand" aria-label="Trust World Bank home">
      <span className={`brand-mark ${light ? "light" : ""}`} aria-hidden="true">
        <span>TW</span>
      </span>
      <span className={`brand-copy ${light ? "text-white" : ""}`}>
        <b>TRUST WORLD</b>
        <small>BANK</small>
      </span>
    </a>
  );
}

function ModalShell({ children, onClose, label }: { children: React.ReactNode; onClose: () => void; label: string }) {
  return (
    <div className="modal-backdrop" role="dialog" aria-modal="true" aria-label={label} onMouseDown={onClose}>
      <div className={`modal-card ${label === "Open a deposit account" ? "wide-modal" : ""}`} onMouseDown={(event) => event.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close dialog"><X size={22} /></button>
        {children}
      </div>
    </div>
  );
}

export default function TrustBankHome() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [loginOpen, setLoginOpen] = useState(false);
  const [applyOpen, setApplyOpen] = useState(false);
  const [depositOpen, setDepositOpen] = useState(false);
  const [depositAccount, setDepositAccount] = useState<DepositAccount>("Checking");
  const [depositCurrency, setDepositCurrency] = useState("USD");
  const [lang, setLang] = useState<Language>("en");
  const [langOpen, setLangOpen] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState("Personal Checking");
  const [activeFaq, setActiveFaq] = useState<number | null>(0);
  const [loanAmount, setLoanAmount] = useState(30000);
  const [term, setTerm] = useState(60);
  const [status, setStatus] = useState<{ type: "idle" | "sending" | "success" | "error"; message?: string }>({ type: "idle" });
  const [loginStatus, setLoginStatus] = useState("");
  const [loginAtmosphere, setLoginAtmosphere] = useState({ time: "day", season: "summer", greeting: "Good afternoon" });
  const [loginCountdown, setLoginCountdown] = useState(5);
  const [signedInAccount, setSignedInAccount] = useState<{ name: string; accountNumber: string; accountType: string; currency: string; balance: string; status: string; accessLevel: "full" | "status_only"; locked: boolean; restricted: boolean } | null>(null);
  const [forgotPasswordOpen, setForgotPasswordOpen] = useState(false);
  const [forgotStep, setForgotStep] = useState<1 | 2 | 3>(1);
  const [forgotToken, setForgotToken] = useState("");
  const [forgotMaskedEmail, setForgotMaskedEmail] = useState("");
  const [forgotError, setForgotError] = useState("");
  const [forgotSuccess, setForgotSuccess] = useState("");
  const [forgotBusy, setForgotBusy] = useState(false);

  const t = DICTIONARY[lang] || DICTIONARY.en;

  function updateAtmosphere() {
    const now = new Date();
    const hour = now.getHours();
    const month = now.getMonth();
    // Accurately determine time of day:
    // 5 AM - 11:59 AM: morning
    // 12 PM - 4:59 PM: afternoon / day
    // 5 PM (17:00) - 8:59 PM: evening (at 6 PM it is evening!)
    // 9 PM (21:00) - 4:59 AM: night
    const time = hour >= 5 && hour < 12 ? "morning" : hour >= 12 && hour < 17 ? "day" : hour >= 17 && hour < 21 ? "evening" : "night";
    const season = month >= 2 && month <= 4 ? "spring" : month >= 5 && month <= 7 ? "summer" : month >= 8 && month <= 10 ? "autumn" : "winter";
    const greeting = time === "morning" ? t.loginMorning : time === "day" ? t.loginAfternoon : time === "evening" ? t.loginEvening : t.loginNight;
    setLoginAtmosphere({ time, season, greeting });
  }

  useEffect(() => {
    const detected = detectBrowserLanguage();
    setLang(detected);
  }, []);

  useEffect(() => {
    updateAtmosphere();
    const timer = window.setInterval(updateAtmosphere, 10000);
    return () => window.clearInterval(timer);
  }, [lang]);

  function switchLanguage(newLang: Language) {
    setLang(newLang);
    try { window.localStorage.setItem("twb_lang", newLang); } catch {}
    setLangOpen(false);
  }

  useEffect(() => {
    if (!signedInAccount) return;
    if (loginCountdown <= 0) { window.location.href = "/online-banking"; return; }
    const timer = window.setTimeout(() => setLoginCountdown((value) => value - 1), 1000);
    return () => window.clearTimeout(timer);
  }, [signedInAccount, loginCountdown]);

  const payment = useMemo(() => {
    const monthlyRate = 0.0524 / 12;
    return (loanAmount * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -term));
  }, [loanAmount, term]);

  function openApplication(product = "Personal Checking") {
    setSelectedProduct(product);
    setStatus({ type: "idle" });
    setApplyOpen(true);
  }

  function openDepositApplication(account: DepositAccount = "Checking") {
    setDepositAccount(account);
    setDepositCurrency("USD");
    setDepositOpen(true);
  }

  async function submitLogin(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setLoginStatus("Signing in…");
    const data = Object.fromEntries(new FormData(event.currentTarget).entries());
    const response = await fetch("/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: data.userId, password: data.password }) });
    const result = await response.json();
    if (response.ok) { setSignedInAccount(result.account); setLoginCountdown(5); setLoginStatus(""); }
    else setLoginStatus(result.message ?? "Unable to sign in.");
  }

  async function handleRequestRecoveryOtp(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setForgotBusy(true);
    setForgotError("");
    const data = Object.fromEntries(new FormData(event.currentTarget).entries());
    try {
      const response = await fetch("/api/auth/forgot-password/request-otp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      const result = await response.json();
      setForgotBusy(false);
      if (response.ok) {
        setForgotToken(result.resetToken);
        setForgotMaskedEmail(result.maskedEmail);
        setForgotStep(2);
      } else {
        setForgotError(result.message || "Failed to verify account details.");
      }
    } catch {
      setForgotBusy(false);
      setForgotError("Network error. Please try again.");
    }
  }

  async function handleResetPasswordWithOtp(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setForgotBusy(true);
    setForgotError("");
    const data = Object.fromEntries(new FormData(event.currentTarget).entries());
    try {
      const response = await fetch("/api/auth/forgot-password/reset", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...data, resetToken: forgotToken }),
      });
      const result = await response.json();
      setForgotBusy(false);
      if (response.ok) {
        setForgotSuccess(result.message || "Password reset successfully!");
        setForgotStep(3);
      } else {
        setForgotError(result.message || "Failed to reset password.");
      }
    } catch {
      setForgotBusy(false);
      setForgotError("Network error. Please try again.");
    }
  }

  async function submitApplication(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setStatus({ type: "sending" });
    const form = new FormData(event.currentTarget);
    const payload = Object.fromEntries(form.entries());
    try {
      const response = await fetch("/api/requests", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const result = await response.json();
      if (!response.ok) throw new Error(result.message);
      setStatus({ type: "success", message: `Thanks—we’ve received your request. Reference ${result.reference}. A banker will contact you shortly.` });
    } catch (error) {
      setStatus({ type: "error", message: error instanceof Error ? error.message : "Please try again." });
    }
  }

  const faqs = [
    ["How do I become a TRUST WORLD BANK customer?", "Choose any checking or savings account and select Open an account. The application takes only a few minutes. You’ll need a government-issued ID, Social Security number and a funding source."],
    ["Are my deposits insured?", "TRUST WORLD BANK is presented as an FDIC-insured institution for this demonstration. In a live launch, insurance and charter disclosures must reflect the bank’s actual regulatory status."],
    ["Can I manage everything from my phone?", "Yes. Digital banking includes mobile deposit, card controls, alerts, bill pay, transfers, statements and secure messages—all from one simple dashboard."],
    ["What support is available?", "Our digital support is available 24/7. Bankers are available by phone, secure message and at local financial centers during posted business hours."],
  ];

  return (
    <main id="top">
      <div className="utility-bar">
        <div className="container utility-inner">
          <p><ShieldCheck size={14} /> Your security is our priority</p>
          <div>
            <a href="#locations"><MapPin size={14} /> {t.navLocations}</a>
            <a href="#support"><Headphones size={14} /> {t.navHelp}</a>
            <div className="lang-switcher-wrap" onClick={(e) => e.stopPropagation()}>
              <button type="button" className="lang-btn" onClick={() => setLangOpen(!langOpen)}>
                <Globe2 size={13} /> <span>{LANGUAGES.find(l => l.code === lang)?.name || "English"}</span> <ChevronDown size={12} />
              </button>
              {langOpen && (
                <div className="lang-dropdown">
                  {LANGUAGES.map((l) => (
                    <button key={l.code} className={lang === l.code ? "active" : ""} onClick={() => switchLanguage(l.code)}>
                      <span>{l.flag}</span> <b>{l.name}</b>
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      <header className="site-header">
        <div className="container header-inner">
          <Brand />
          <nav className="desktop-nav" aria-label="Main navigation">
            {navItems.map((item) => <a key={item} href={`#${item.toLowerCase().replaceAll(" ", "-")}`}>{item}<ChevronDown size={15} /></a>)}
          </nav>
          <div className="header-actions">
            <button className="icon-button search-button" aria-label="Search"><Search size={20} /></button>
            <button className="login-button" onClick={() => { updateAtmosphere(); setLoginOpen(true); }}><LockKeyhole size={18} /> {t.navLogin}</button>
            <button className="menu-button" onClick={() => setMobileOpen(!mobileOpen)} aria-label="Open menu">{mobileOpen ? <X /> : <Menu />}</button>
          </div>
        </div>
        {mobileOpen && (
          <nav className="mobile-nav container" aria-label="Mobile navigation">
            {navItems.map((item) => <a key={item} href={`#${item.toLowerCase().replaceAll(" ", "-")}`} onClick={() => setMobileOpen(false)}>{item}<ChevronRight size={18} /></a>)}
            <a href="#rates" onClick={() => setMobileOpen(false)}>Rates <ChevronRight size={18} /></a>
            <a href="#locations" onClick={() => setMobileOpen(false)}>{t.navLocations} <ChevronRight size={18} /></a>
          </nav>
        )}
      </header>

      <section className="hero">
        <div className="hero-image" aria-hidden="true" />
        <div className="container hero-content">
          <div className="hero-copy">
            <span className="eyebrow light-eyebrow">{t.heroEyebrow}</span>
            <h1>{t.heroH1_1}<br /><em>{t.heroH1_2}</em></h1>
            <p>{t.heroSubtitle}</p>
            <div className="hero-buttons">
              <button className="button coral" onClick={() => openDepositApplication()}>{t.navOpenAccount} <ArrowRight size={18} /></button>
              <a href="#borrow" className="button white">{t.heroExploreLoans}</a>
            </div>
            <p className="hero-note"><Check size={16} /> {t.heroOpen5Mins}</p>
          </div>
        </div>
        <div className="hero-trust-card">
          <ShieldCheck />
          <div><b>Bank with confidence</b><span>Secure. Local. Here for you.</span></div>
        </div>
      </section>

      <section className="quick-bar" aria-label="Quick links">
        <div className="container quick-grid">
          {quickLinks.map(([Icon, label]) => (
            <a href={label === "Financial calculators" ? "#calculator" : label === "Find a location" ? "#locations" : "#support"} key={label as string}>
              <Icon size={21} /><span>{label as string}</span>
            </a>
          ))}
        </div>
      </section>

      <section className="section products-section" id="bank">
        <div className="container">
          <div className="section-heading centered">
            <span className="eyebrow">BANKING FOR REAL LIFE</span>
            <h2>Everything you need. All in one place.</h2>
            <p>Whatever you’re working toward, we have the tools, guidance and products to help you move forward.</p>
          </div>
          <div className="product-grid">
            {products.map(({ icon: Icon, title, text, link }) => (
              <article className="product-card" key={title}>
                <div className="product-icon"><Icon size={28} /></div>
                <h3>{title}</h3>
                <p>{text}</p>
                <button onClick={() => title === "Checking" || title === "Savings" || title === "Offshore Account" ? openDepositApplication(title as DepositAccount) : openApplication(title)}>{link} <ArrowRight size={17} /></button>
              </article>
            ))}
          </div>
        </div>
      </section>

      <section className="feature-split" id="why-trust-world">
        <div className="feature-photo family-photo"><span className="photo-label"><HeartHandshake size={20} /> People first, always.</span></div>
        <div className="feature-copy navy-panel">
          <span className="eyebrow light-eyebrow">WHY TRUST WORLD</span>
          <h2>Not just your bank.<br />Your financial ally.</h2>
          <p>You deserve more than transactions. You deserve a team that listens, understands and stands beside you through every chapter.</p>
          <ul>
            <li><span><Check /></span><div><b>Advice that feels personal</b><small>Real guidance from people who know your community.</small></div></li>
            <li><span><Check /></span><div><b>Better value, built in</b><small>Competitive rates and fewer fees help your money go further.</small></div></li>
            <li><span><Check /></span><div><b>Technology that keeps up</b><small>Secure tools make managing your money feel effortless.</small></div></li>
          </ul>
          <a className="text-link light-link" href="#about">Discover the Trust World difference <ArrowRight size={18} /></a>
        </div>
      </section>

      <section className="section rate-section" id="rates">
        <div className="container">
          <div className="section-heading split-heading">
            <div><span className="eyebrow">FEATURED RATES</span><h2>Great rates. Greater possibilities.</h2></div>
            <p>Put your plans in motion with rates designed to help you borrow smarter and save faster.</p>
          </div>
          <div className="rate-grid">
            {rates.map((rate, index) => (
              <article className={`rate-card ${index === 1 ? "featured" : ""}`} key={rate.name}>
                {index === 1 && <span className="popular">POPULAR</span>}
                <h3>{rate.name}</h3>
                <p>{rate.detail}</p>
                <strong>{rate.rate}</strong>
                <small>{rate.name.includes("certificate") ? "Minimum $1,000 deposit" : rate.name.includes("card") ? "Based on creditworthiness" : "Terms and conditions apply"}</small>
                <button onClick={() => rate.name.includes("certificate") ? openDepositApplication("Savings") : openApplication(rate.name)}>{rate.action} <ArrowRight size={17} /></button>
              </article>
            ))}
          </div>
          <p className="rate-disclaimer">Rates shown are for illustrative purposes and may change without notice. APR = Annual Percentage Rate. APY = Annual Percentage Yield. <a href="#disclosures">View rate disclosures</a></p>
        </div>
      </section>

      <section className="section digital-section">
        <div className="container digital-grid">
          <div className="phone-visual" aria-label="Mobile banking app preview">
            <div className="phone">
              <div className="phone-top" />
              <div className="phone-screen">
                <div className="phone-brand"><span>TW</span> Good morning, Maya</div>
                <div className="balance-card"><small>TOTAL BALANCE</small><strong>$24,680.12</strong><span>Across 3 accounts</span></div>
                <div className="phone-actions"><span>↑<small>Send</small></span><span>↓<small>Deposit</small></span><span>→<small>Pay</small></span></div>
                <div className="account-row"><span><i>••</i> Essential Checking</span><b>$4,821.09</b></div>
                <div className="account-row"><span><i>••</i> Goal Savings</span><b>$19,859.03</b></div>
              </div>
            </div>
            <div className="secure-badge"><ShieldCheck /><b>Protected 24/7</b><span>Advanced security</span></div>
          </div>
          <div className="digital-copy">
            <span className="eyebrow">BANKING IN YOUR POCKET</span>
            <h2>Your money, always within reach.</h2>
            <p>Deposit a check from the couch. Lock a card in seconds. Send money before your coffee gets cold. Our digital banking works wherever life takes you.</p>
            <div className="check-grid">
              {["Mobile check deposit", "Instant card controls", "Real-time account alerts", "Easy bill pay", "Fast, secure transfers", "24/7 account access"].map((item) => <span key={item}><Check /> {item}</span>)}
            </div>
            <button className="button navy" onClick={() => setLoginOpen(true)}>Enroll in digital banking <ArrowRight size={18} /></button>
            <div className="app-links"><a href="#"> <span>Download on the<br /><b>App Store</b></span></a><a href="#"><span className="play">▶</span><span>GET IT ON<br /><b>Google Play</b></span></a></div>
          </div>
        </div>
      </section>

      <section className="calculator-section" id="calculator">
        <div className="container calculator-grid">
          <div className="calculator-copy">
            <span className="eyebrow light-eyebrow">PLAN WITH CONFIDENCE</span>
            <h2>See what fits your budget.</h2>
            <p>Adjust the numbers to estimate a monthly auto loan payment, then get pre-approved when you’re ready.</p>
            <p className="calc-note"><ShieldCheck /> Checking your rate won’t affect your credit score.</p>
          </div>
          <div className="calculator-card">
            <label><span>Loan amount</span><b>${loanAmount.toLocaleString()}</b></label>
            <input aria-label="Loan amount" type="range" min="5000" max="80000" step="1000" value={loanAmount} onChange={(e) => setLoanAmount(Number(e.target.value))} />
            <div className="range-labels"><span>$5,000</span><span>$80,000</span></div>
            <label className="term-label"><span>Loan term</span><b>{term} months</b></label>
            <div className="term-buttons">{[36, 48, 60, 72].map((month) => <button key={month} className={term === month ? "active" : ""} onClick={() => setTerm(month)}>{month} mo.</button>)}</div>
            <div className="payment-result"><span>Estimated monthly payment<small>Based on 5.24% APR</small></span><strong>${payment.toFixed(2)}<small>/mo</small></strong></div>
            <button className="button coral full" onClick={() => openApplication("Auto Loan")}>Get pre-approved <ArrowRight size={18} /></button>
          </div>
        </div>
      </section>

      <section className="feature-split business-feature" id="business">
        <div className="feature-copy cream-panel">
          <span className="eyebrow">BUSINESS BANKING</span>
          <h2>Your business is personal.<br />So is our support.</h2>
          <p>From your first sale to your next location, our local business bankers bring practical expertise and financial solutions that scale with you.</p>
          <div className="business-stats"><div><strong>$250M+</strong><span>invested in local businesses</span></div><div><strong>20+ yrs</strong><span>average banker experience</span></div></div>
          <button className="button navy" onClick={() => openApplication("Business Banking")}>Meet our business team <ArrowRight size={18} /></button>
        </div>
        <div className="feature-photo business-photo"><div className="quote-card"><MessageCircle /><p>“They understood the dream before they ever saw the numbers.”</p><b>— Camille, café owner</b></div></div>
      </section>

      <section className="section resource-section" id="plan">
        <div className="container">
          <div className="section-heading centered"><span className="eyebrow">MONEY, MADE CLEARER</span><h2>Helpful resources for what’s next.</h2><p>Practical guidance to help you make informed decisions with confidence.</p></div>
          <div className="resource-grid">
            <article className="resource-card featured-resource"><div className="resource-img house-img" /><div><span>HOMEOWNERSHIP · 6 MIN READ</span><h3>How much home can you comfortably afford?</h3><p>Look beyond the listing price and learn what really shapes a healthy home-buying budget.</p><a href="#">Read the article <ArrowRight /></a></div></article>
            <article className="resource-card"><div className="resource-icon"><TrendingUp /></div><span>SAVING · 4 MIN READ</span><h3>5 small money habits that add up</h3><p>Simple changes you can make today to build momentum for tomorrow.</p><a href="#">Read more <ArrowRight /></a></article>
            <article className="resource-card"><div className="resource-icon"><BadgeDollarSign /></div><span>CREDIT · 5 MIN READ</span><h3>Understanding your credit score</h3><p>Know the factors that matter and the steps that can help strengthen your score.</p><a href="#">Read more <ArrowRight /></a></article>
          </div>
        </div>
      </section>

      <section className="location-section" id="locations">
        <div className="container location-card">
          <div>
            <span className="eyebrow light-eyebrow">WE’RE CLOSE BY</span>
            <h2>Find your nearest financial center.</h2>
            <p>Friendly faces, expert advice and convenient service—right in your neighborhood.</p>
            <div className="location-search"><MapPin /><input aria-label="City, state, or ZIP" placeholder="Enter city, state or ZIP" /><button onClick={() => alert("Branch search is ready for your location.")}>Search</button></div>
          </div>
          <div className="map-visual" aria-label="Stylized location map">
            <div className="map-road road-a" /><div className="map-road road-b" /><div className="map-road road-c" />
            <span className="pin pin-a"><MapPin /></span><span className="pin pin-b"><MapPin /></span><span className="pin pin-c"><MapPin /></span>
            <div className="map-info"><b><Landmark /> Downtown Center</b><span>Open today until 5:00 PM</span></div>
          </div>
        </div>
      </section>

      <section className="section faq-section" id="support">
        <div className="container faq-grid">
          <div><span className="eyebrow">COMMON QUESTIONS</span><h2>Answers when you need them.</h2><p>Can’t find what you’re looking for?</p><a href="mailto:hello@trustworld.example">Visit our Help Center <ArrowRight size={17} /></a></div>
          <div className="faq-list">{faqs.map(([question, answer], index) => <article key={question} className={activeFaq === index ? "open" : ""}><button onClick={() => setActiveFaq(activeFaq === index ? null : index)}><span>{question}</span><ChevronDown /></button>{activeFaq === index && <p>{answer}</p>}</article>)}</div>
        </div>
      </section>

      <section className="cta-section"><div className="container cta-inner"><div><span className="eyebrow light-eyebrow">LET’S MOVE FORWARD</span><h2>Ready to bank with confidence?</h2><p>Open an account online in minutes. We’ll be here for everything after.</p></div><div><button className="button coral" onClick={() => openDepositApplication()}>Open an account <ArrowRight size={18} /></button><a className="button outline-light" href="#support">Talk to a banker</a></div></div></section>

      <footer id="about">
        <div className="container footer-top">
          <div className="footer-brand"><Brand light /><p>Banking built on trust, strengthened by community and designed for your world.</p><div className="socials"><a href="#" aria-label="Community"><Globe2 /></a><a href="#" aria-label="Photo updates"><Camera /></a><a href="#" aria-label="Videos"><Play /></a></div></div>
          <div className="footer-column"><h3>Bank</h3><a href="#bank">Checking</a><a href="#bank">Savings</a><a href="#bank">Credit cards</a><a href="#rates">Rates</a><a href="#">Digital banking</a></div>
          <div className="footer-column"><h3>Borrow</h3><a href="#borrow">Auto loans</a><a href="#borrow">Mortgages</a><a href="#borrow">Home equity</a><a href="#borrow">Personal loans</a><a href="#calculator">Calculators</a></div>
          <div className="footer-column"><h3>Support</h3><a href="#support">Help center</a><a href="#locations">Locations & ATMs</a><a href="#support">Contact us</a><a href="#">Routing number</a><a href="#">Report fraud</a></div>
          <div className="footer-contact"><h3>Need help?</h3><a href="tel:18008789675"><Headphones /> 1-800-TRUST-WL</a><p>Mon–Fri, 8am–8pm<br />Sat, 9am–2pm</p><button onClick={() => openApplication("Request a callback")}><MessageCircle /> Send us a message</button></div>
        </div>
        <div className="container footer-bottom" id="disclosures"><div><span className="equal-house"><Home /> Equal Housing Lender</span><span><ShieldCheck /> Member FDIC</span></div><p>© 2026 TRUST WORLD BANK. All rights reserved.</p><nav><a href="#">Privacy</a><a href="#">Security</a><a href="#">Terms</a><a href="#">Accessibility</a></nav><small>TRUST WORLD BANK is a fictional demonstration brand. Products, rates and regulatory marks shown are illustrative and not an offer of financial services.</small></div>
      </footer>

      <button className="chat-button" aria-label="Chat with us" onClick={() => openApplication("Chat support")}><MessageCircle /><span>Chat with us</span></button>

      {depositOpen && <ModalShell label="Open a deposit account" onClose={() => setDepositOpen(false)}><AccountOpeningForm initialAccount={depositAccount} initialCurrency={depositCurrency} onClose={() => setDepositOpen(false)} /></ModalShell>}

      {forgotPasswordOpen && (
        <ModalShell label="Password Recovery" onClose={() => setForgotPasswordOpen(false)}>
          <div className="modal-header">
            <div className="mini-mark">
              <KeyRound size={22} />
            </div>
            <span className="eyebrow">ACCOUNT RECOVERY • 2-STEP VERIFICATION</span>
            <h2>Reset Password</h2>
            <p>
              {forgotStep === 1 && "Verify your account number and security PIN to request a one-time code."}
              {forgotStep === 2 && `Enter the 6-digit OTP code sent to your email on file (${forgotMaskedEmail}).`}
              {forgotStep === 3 && "Your password has been reset successfully."}
            </p>
          </div>

          {forgotStep === 1 && (
            <form className="login-form" onSubmit={handleRequestRecoveryOtp}>
              <label>
                Account Number
                <input
                  name="accountNumber"
                  type="text"
                  required
                  placeholder="e.g. 740123456789"
                  autoComplete="off"
                />
              </label>
              <label>
                6-digit Security PIN
                <div className="password-input">
                  <input
                    name="pin"
                    type="password"
                    inputMode="numeric"
                    pattern="[0-9]{6}"
                    maxLength={6}
                    required
                    placeholder="••••••"
                    autoComplete="off"
                  />
                  <LockKeyhole />
                </div>
              </label>

              {forgotError && <p className="form-error">{forgotError}</p>}

              <button className="button navy full" type="submit" disabled={forgotBusy}>
                {forgotBusy ? "Verifying..." : "Verify & Send Email OTP"} <ArrowRight size={18} />
              </button>

              <div className="form-between" style={{ justifyContent: "center", marginTop: 8 }}>
                <a href="#" onClick={(e) => { e.preventDefault(); setForgotPasswordOpen(false); setLoginOpen(true); }}>
                  Back to Sign In
                </a>
              </div>
            </form>
          )}

          {forgotStep === 2 && (
            <form className="login-form" onSubmit={handleResetPasswordWithOtp}>
              <label>
                6-digit Email OTP Code
                <input
                  name="otpCode"
                  type="text"
                  inputMode="numeric"
                  pattern="[0-9]{6}"
                  maxLength={6}
                  required
                  placeholder="Enter 6-digit code..."
                  autoFocus
                />
              </label>

              <label>
                New Password
                <div className="password-input">
                  <input
                    name="newPassword"
                    type="password"
                    minLength={6}
                    maxLength={12}
                    required
                    placeholder="6–12 chars (letters & numbers)"
                    autoComplete="new-password"
                  />
                  <LockKeyhole />
                </div>
              </label>

              <label>
                Confirm New Password
                <div className="password-input">
                  <input
                    name="confirmPassword"
                    type="password"
                    minLength={6}
                    maxLength={12}
                    required
                    placeholder="Repeat new password"
                    autoComplete="new-password"
                  />
                  <LockKeyhole />
                </div>
              </label>

              {forgotError && <p className="form-error">{forgotError}</p>}

              <button className="button coral full" type="submit" disabled={forgotBusy}>
                {forgotBusy ? "Resetting Password..." : "Submit New Password"} <ArrowRight size={18} />
              </button>

              <div className="form-between" style={{ justifyContent: "space-between", marginTop: 8 }}>
                <a href="#" onClick={(e) => { e.preventDefault(); setForgotStep(1); setForgotError(""); }}>
                  ← Back to Step 1
                </a>
                <a href="#" onClick={(e) => { e.preventDefault(); setForgotPasswordOpen(false); setLoginOpen(true); }}>
                  Back to Sign In
                </a>
              </div>
            </form>
          )}

          {forgotStep === 3 && (
            <div className="success-message">
              <div>
                <Check size={28} />
              </div>
              <h3>Password Reset!</h3>
              <p>{forgotSuccess}</p>
              <button
                className="button navy full"
                onClick={() => {
                  setForgotPasswordOpen(false);
                  setLoginOpen(true);
                }}
              >
                Log In With New Password
              </button>
            </div>
          )}
        </ModalShell>
      )}

      {loginOpen && <ModalShell label="Online banking login" onClose={() => setLoginOpen(false)}><div className={`login-atmosphere ${loginAtmosphere.time} ${loginAtmosphere.season}`}><div className="atmosphere-orb"/><i className="particle p1"/><i className="particle p2"/><i className="particle p3"/><span>{loginAtmosphere.time === "night" ? "✦" : loginAtmosphere.season === "winter" ? "❄" : loginAtmosphere.season === "autumn" ? "◆" : "●"}</span></div><div className="modal-header login-modal-header"><div className="mini-mark">TW</div><span className="eyebrow">SECURE ONLINE BANKING · {loginAtmosphere.season.toUpperCase()}</span><h2>{signedInAccount ? `Welcome, ${signedInAccount.name}.` : `${loginAtmosphere.greeting}.`}</h2><p>{signedInAccount ? "Your account summary is shown below." : t.loginSubtitle}</p></div>{signedInAccount ? <div className="signed-in-summary"><div><small>ACCOUNT</small><b>{signedInAccount.accountType}</b></div><div><small>ACCOUNT NUMBER</small><b>{signedInAccount.accountNumber}</b></div><div><small>AVAILABLE BALANCE</small><b>{new Intl.NumberFormat("en-US", { style: "currency", currency: signedInAccount.currency }).format(Number(signedInAccount.balance))}</b></div><div><small>STATUS</small><b>{signedInAccount.status.replaceAll("_", " ")}</b></div><p className={signedInAccount.accessLevel === "full" ? "access-active" : ""}><ShieldCheck /> {signedInAccount.accessLevel === "full" ? "Full online banking is active. Your secure account is available anytime." : signedInAccount.locked ? "This account is locked. Contact support for assistance." : signedInAccount.restricted ? "This account has restricted access. Contact support for assistance." : "Secure status access is active. Transactions remain unavailable until identity verification is approved."}</p><div className="login-countdown"><span>{loginCountdown}</span><p>Entering secure online banking automatically…</p></div><button className="button navy full" onClick={() => { window.location.href = "/online-banking"; }}>Continue to full access</button></div> : <form className="login-form" onSubmit={submitLogin}><label>{t.loginUserId}<input name="userId" required autoComplete="username" placeholder={t.loginUserId} /></label><label>{t.loginPassword}<div className="password-input"><input name="password" required type="password" autoComplete="current-password" placeholder={t.loginPassword} /><LockKeyhole /></div></label><div className="form-between"><label className="remember"><input type="checkbox" /> {t.loginRemember}</label><a href="#" onClick={(e) => { e.preventDefault(); setLoginOpen(false); setForgotPasswordOpen(true); setForgotStep(1); setForgotError(""); setForgotSuccess(""); }}>{t.loginForgot}</a></div>{loginStatus && <p className="form-error">{loginStatus}</p>}<button className="button navy full" type="submit">{t.loginBtn} <ArrowRight size={18} /></button><p className="login-enroll">{t.loginNewToDigital} <a href="#" onClick={() => { setLoginOpen(false); openDepositApplication(); }}>{t.loginOpenAccountLink}</a></p><div className="secure-line"><ShieldCheck /> {t.loginSecureNotice}</div></form>}</ModalShell>}

      {applyOpen && <ModalShell label="Product application" onClose={() => setApplyOpen(false)}><div className="modal-header"><div className="mini-mark"><UserRound /></div><span className="eyebrow">LET’S GET STARTED</span><h2>Connect with a banker.</h2><p>Tell us a little about yourself. We’ll help you take the next step.</p></div>{status.type === "success" ? <div className="success-message"><div><Check /></div><h3>Request received!</h3><p>{status.message}</p><button className="button navy" onClick={() => setApplyOpen(false)}>Done</button></div> : <form className="application-form" onSubmit={submitApplication}><input type="hidden" name="requestType" value="application" /><div className="form-row"><label>First name<input name="firstName" required /></label><label>Last name<input name="lastName" required /></label></div><label>Email address<input name="email" type="email" required /></label><label>Phone number<input name="phone" type="tel" /></label><label>I’m interested in<select name="product" value={selectedProduct} onChange={(e) => setSelectedProduct(e.target.value)}>{["Personal Checking", "Savings", "Credit Cards", "Auto Loan", "Home Loan", "Home Equity", "Business Banking", "Digital Banking Enrollment", "Request a callback", "Chat support"].map((item) => <option key={item}>{item}</option>)}</select></label><label>How can we help? <span>(optional)</span><textarea name="message" rows={3} /></label>{status.type === "error" && <p className="form-error">{status.message}</p>}<button className="button coral full" type="submit" disabled={status.type === "sending"}>{status.type === "sending" ? "Submitting…" : "Submit request"} <ArrowRight size={18} /></button><small className="form-privacy"><LockKeyhole /> Your information is protected and will never be sold.</small></form>}</ModalShell>}
    </main>
  );
}
