const { useContext, useEffect, useRef, useState } = React;
const seo = window.AZN_SEO || {};
const SignupContext = React.createContext({ openSignup: () => {} });

const media = {
  logo: "/assets/brand-assets/trimmed_logo_white.png",
  heroDesktop: "/assets/install-assets/kaufman-hero-desktop.mp4",
  heroMobile: "/assets/install-assets/kaufman-hero-mobile.mp4",
  heroPoster: "/assets/install-assets/kaufman-hero-poster.jpg",
  gilbert: "/assets/stock-assets/iStock-1395786272.jpg",
  aboutHero: "/assets/stock-assets/iStock-2164218773.jpg",
  supportAgent: "https://static.wixstatic.com/media/nsplsh_a7817f00a1f9454f963bea548c56175d~mv2.jpg/v1/fill/w_509,h_318,fp_0.50_0.69,q_80,usm_0.66_1.00_0.01,enc_avif,quality_auto/Image%20by%20Good%20Faces.jpg",
  gradient: "https://static.wixstatic.com/media/11062b_773720c471c8454d84f5e2ae1c354440~mv2.jpg/v1/fill/w_100,h_56,al_c,q_80,usm_0.66_1.00_0.01,blur_3,enc_avif,quality_auto/11062b_773720c471c8454d84f5e2ae1c354440~mv2.jpg",
  reviewsBg: "https://static.wixstatic.com/media/11062b_bfdb3dc7eb314c8faca8eaf7241345bd~mv2.jpg/v1/fill/w_1220,h_391,fp_0.08_0.49,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/11062b_bfdb3dc7eb314c8faca8eaf7241345bd~mv2.jpg",
  helpBg: "https://static.wixstatic.com/media/nsplsh_e93fe904018f45288d37c19fdaf247e0~mv2.jpg/v1/fill/w_1220,h_391,fp_0.00_0.50,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/nsplsh_e93fe904018f45288d37c19fdaf247e0~mv2.jpg",
  partnerBg: "https://static.wixstatic.com/media/11062b_29bcd52189e5456c9140bc3c3c583d61~mv2.jpeg/v1/fill/w_1017,h_391,fp_0.50_1.00,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/11062b_29bcd52189e5456c9140bc3c3c583d61~mv2.jpeg",
  careersDesk: "https://static.wixstatic.com/media/95a8d23fd351498dacce637ff0136bb8.jpg/v1/fill/w_240,h_160,al_c,q_80,usm_0.66_1.00_0.01,enc_auto/Work%20Desk.jpg",
  homelabHero: "https://static.wixstatic.com/media/11062b_db8f5ddb085b41fda169efb854f9b69e~mv2.jpg/v1/fill/w_1017,h_288,al_c,q_80,usm_0.66_1.00_0.01,enc_avif,quality_auto/11062b_db8f5ddb085b41fda169efb854f9b69e~mv2.jpg",
  homelabBg: "https://static.wixstatic.com/media/11062b_b9e4eaeea1e14361a9922299ada08703~mv2.jpg/v1/fill/w_1017,h_1286,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/11062b_b9e4eaeea1e14361a9922299ada08703~mv2.jpg",
  homelabStatic: "https://static.wixstatic.com/media/a3afae_60c4a0bbbf0a420b95d73af70de3296f~mv2.png/v1/fill/w_509,h_322,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/Website%20Image%20(4).png",
  homelabSpeed: "https://static.wixstatic.com/media/a3afae_155acd9c38ed498ea49845f05684fb38~mv2.png/v1/fill/w_509,h_322,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/Website%20Image%20(3).png",
  homelabRouter: "https://static.wixstatic.com/media/a3afae_bb2b6a5cee764a61bf3774f34ef50e2c~mv2.png/v1/fill/w_509,h_322,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/Bring%20Your%20Own%20Router.png",
  homelabLatency: "/assets/install-assets/speed_test_gilbert.png",
  referralBg: "https://static.wixstatic.com/media/8bc1fb7a6fc34518926834b99b9c22dd.jpg/v1/fill/w_1017,h_240,al_c,q_80,usm_0.66_1.00_0.01,enc_avif,quality_auto/8bc1fb7a6fc34518926834b99b9c22dd.jpg",
  referralProgress: "https://static.wixstatic.com/media/a3afae_51a86c079a3a4f849bf95bca4389b587~mv2.png/v1/crop/x_6,y_7,w_760,h_233/fill/w_638,h_196,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/Screenshot%202026-04-24%20at%209_26_56%E2%80%AFAM.png",
  referralSignup: "https://static.wixstatic.com/media/a3afae_27b3fd3cf21f4fe2a5044a8021ca51c6~mv2.png/v1/crop/x_0,y_158,w_1600,h_621/fill/w_804,h_312,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/Signup.png",
  referralCredit: "https://static.wixstatic.com/media/a3afae_df0632c46ba84f9c905eec6ba60a7e43~mv2.png/v1/fill/w_722,h_406,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/%24100%20Discount.png",
  referralFree: "https://static.wixstatic.com/media/a3afae_1d0903dab84243f1afdde2a14737073d~mv2.png/v1/crop/x_0,y_1,w_1600,h_899/fill/w_775,h_435,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/Website%20Image%20(5).png",
  installSample: "/assets/install-assets/DSC_0307.jpg",
  techGradient: "https://static.wixstatic.com/media/11062b_f45c8724ba06470ab65ea35c97405911~mv2.jpg/v1/fill/w_1017,h_439,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/11062b_f45c8724ba06470ab65ea35c97405911~mv2.jpg",
  plansBg: "https://static.wixstatic.com/media/11062b_0be77b5f185c4f31a6ed42b9eefec045~mv2.jpg/v1/fill/w_976,h_283,al_c,q_80,usm_0.66_1.00_0.01,enc_avif,quality_auto/11062b_0be77b5f185c4f31a6ed42b9eefec045~mv2.jpg",
  router: "https://static.wixstatic.com/media/c77807_2c2ed575762942f2a59779428cb641ce~mv2.png/v1/fill/w_58,h_74,al_c,q_85,usm_0.66_1.00_0.01,blur_2,enc_avif,quality_auto/c77807_2c2ed575762942f2a59779428cb641ce~mv2.png",
  standardRouter: "/assets/stock-assets/2204_hi_res.png",
  proRouter: "/assets/stock-assets/2414_hi_res.png",
  dish: "https://static.wixstatic.com/media/a3afae_0e81715cc14e4a0baa4ba7e2dad77f0f~mv2.avif/v1/fill/w_147,h_147,al_c,q_80,usm_0.66_1.00_0.01,blur_2,enc_avif,quality_auto/images_svc_ui.avif",
  freeInternet: "/assets/stock-assets/Free%20Internet.png",
  cambium4625: "https://static.wixstatic.com/media/a3afae_7faf4a979791484c9c2a6ae56eb5a7b5~mv2.webp/v1/fill/w_139,h_142,al_c,q_80,usm_0.66_1.00_0.01,enc_avif,quality_auto/epmp_4525_hero.webp",
  ubiquitiLtuAp: "https://static.wixstatic.com/media/a3afae_45dce8ea817c45a093b6c7576a4f6184~mv2.avif/v1/fill/w_233,h_156,al_c,q_80,usm_0.66_1.00_0.01,enc_avif,quality_auto/images_svc_ui.avif",
  cambium4600: "https://static.wixstatic.com/media/a3afae_172698b0d2dc4df894551dc3b2ce19e7~mv2.png/v1/fill/w_206,h_137,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/images_edited.png",
  ubiquitiLtuLr: "https://static.wixstatic.com/media/a3afae_f1f175f2b4f141ce97acd4c90567456a~mv2.avif/v1/fill/w_196,h_131,al_c,q_80,usm_0.66_1.00_0.01,enc_avif,quality_auto/images_svc_ui.avif",
  ubiquitiWaveAp: "https://static.wixstatic.com/media/a3afae_672deb7c0a70421a94053f30aa131fc6~mv2.avif/v1/fill/w_206,h_137,al_c,q_80,usm_0.66_1.00_0.01,enc_avif,quality_auto/images_svc_ui.avif",
};

const plans = [
  {
    name: "Standard",
    value: "10",
    kicker: "Included Router",
    price: 54,
    router: media.standardRouter,
    bullets: ["Included with Residential Internet", "Best for smaller homes or fewer devices", "4 Ethernet ports"],
  },
  {
    name: "Pro",
    value: "8",
    kicker: "Router Upgrade",
    price: 64,
    router: media.proRouter,
    bullets: ["Adds stronger WiFi hardware", "Best for larger homes or many devices", "Expanded WiFi coverage"],
  },
];

const supportEmail = "sales@arizonanetwork.com";
const supportPhone = "480-582-1736";
const serviceAreas = seo.serviceAreas || ["Gilbert, AZ", "Florence, AZ", "San Tan Valley, AZ", "Anthem at Merrill Ranch", "Magic Ranch", "Johnson Ranch", "Copper Basin"];
const resourceArticles = seo.resourceArticles || [];
const trialReferralCode = "AZN30DAYTRIAL_2025";
const trialReferralLink = "https://www.arizonanetwork.com/gilbertfreetrial?referralCode=AZN30DAYTRIAL_2025";
const googleReviewsUrl = "https://www.google.com/search?q=arizona+network#lrd=0x872bab6607cbe2f5:0x71fee1738861361e,1,,,,";
const routerOptions = [
  { value: "1", label: "No extender", price: 0, detail: "Use the router you selected without an added extender." },
  { value: "104", label: "Add Whole Home WiFi Extender", price: 10, detail: "Add extra WiFi coverage for larger homes, thick walls, or rooms farther from the router." },
];
const cardBrandLogos = [
  { name: "Visa", src: "/assets/payment-icons/visa.svg" },
  { name: "Mastercard", src: "/assets/payment-icons/mastercard.svg" },
  { name: "American Express", src: "/assets/payment-icons/amex.svg" },
  { name: "Discover", src: "/assets/payment-icons/discover.svg" },
];

const legalPages = {
  "/residential-internet-agreement": {
    eyebrow: "Residential Terms",
    title: "Residential Internet Agreement",
    intro: "These terms describe the month-to-month residential internet service relationship between Arizona Network and the customer at the service address.",
    sections: [
      {
        title: "Service term",
        paragraphs: [
          "Residential internet service is provided on a month-to-month basis. Service begins after Arizona Network completes installation and activates the customer's service.",
          "Arizona Network may update service terms, pricing, policies, or service features when needed. Continued use of the service after notice of an update means the customer accepts the updated terms.",
        ],
      },
      {
        title: "Installation and service availability",
        paragraphs: [
          "Service is subject to address-level availability, signal quality, network capacity, installation conditions, and other technical factors. Some addresses may require address review before installation can be confirmed.",
          "Installation includes professional placement and configuration of Arizona Network equipment needed to provide service. The customer must provide safe access to the service location for installation, maintenance, and equipment recovery.",
        ],
      },
      {
        title: "Billing and autopay",
        paragraphs: [
          "A valid debit or credit card is required for autopay. No charges are made until service is installed and active unless the customer separately agrees to an upfront charge.",
          "After service is active, Arizona Network may charge the payment method on file for monthly service, regulatory or recovery fees, installation charges, equipment charges, and other amounts allowed by the agreement.",
        ],
      },
      {
        title: "Equipment",
        paragraphs: [
          "Arizona Network-provided radios, routers, power supplies, mounts, cabling, and related equipment remain Arizona Network property unless Arizona Network states otherwise in writing.",
          "The customer is responsible for reasonable care of installed equipment and must return or allow recovery of Arizona Network-owned equipment after cancellation.",
        ],
      },
      {
        title: "Service performance",
        paragraphs: [
          "Fixed wireless performance can vary based on signal path, network conditions, internet destinations, WiFi environment, customer devices, weather, power availability, and other factors outside Arizona Network's control.",
          "Arizona Network may use reasonable network management practices to keep the network secure, reliable, and fair for customers.",
        ],
      },
      {
        title: "Customer responsibilities",
        paragraphs: [
          "Customers must use the service lawfully and follow the Acceptable Use Policy, network management disclosures, and related service policies.",
          "Customers are responsible for keeping account contact information current so Arizona Network can send service, billing, appointment, and legal notices.",
        ],
      },
    ],
  },
  "/cancellation-terms": {
    eyebrow: "Residential Terms",
    title: "Cancellation Terms",
    intro: "Arizona Network residential service is month-to-month, with cancellation handled through the support team so billing and equipment recovery can be closed out cleanly.",
    sections: [
      {
        title: "How to cancel",
        paragraphs: [
          `Customers may request cancellation by contacting Arizona Network at ${supportEmail} or ${supportPhone}.`,
          "The customer remains responsible for charges already incurred before cancellation is completed, including any active service period, unpaid balance, equipment charges, or other charges allowed by the agreement.",
        ],
      },
      {
        title: "Effective date",
        paragraphs: [
          "Cancellation generally becomes effective after Arizona Network receives the request, confirms the account, and schedules any equipment return or recovery needed.",
          "Arizona Network may keep the account active long enough to complete equipment recovery, prevent accidental service interruption, or resolve billing issues.",
        ],
      },
      {
        title: "No long-term contract",
        paragraphs: [
          "Residential service is month-to-month. Arizona Network does not require a long-term residential contract for standard home internet service unless a separate written promotion or agreement says otherwise.",
        ],
      },
    ],
  },
  "/equipment-return-terms": {
    eyebrow: "Residential Terms",
    title: "Equipment Return Terms",
    intro: "Arizona Network-owned equipment must be returned or made available for recovery when service ends.",
    sections: [
      {
        title: "Arizona Network-owned equipment",
        paragraphs: [
          "Outdoor radios, routers, power supplies, mounts, cabling, and related hardware provided by Arizona Network remain Arizona Network property unless otherwise stated in writing.",
          "Customers may not sell, transfer, discard, damage, or keep Arizona Network-owned equipment after service ends.",
        ],
      },
      {
        title: "Return or recovery",
        paragraphs: [
          "After cancellation, the customer must return Arizona Network-owned equipment or allow Arizona Network reasonable access to recover it.",
          "Customers should not remove roof-mounted or exterior equipment unless Arizona Network instructs them to do so. Arizona Network can coordinate safe recovery of installed equipment.",
        ],
      },
      {
        title: "Unreturned or damaged equipment",
        paragraphs: [
          "If equipment is not returned, cannot be recovered, or is returned damaged beyond ordinary wear, Arizona Network may charge the account for replacement or recovery costs allowed by the agreement.",
        ],
      },
    ],
  },
  "/acceptable-use-policy": {
    eyebrow: "Policy",
    title: "Acceptable Use Policy",
    intro: "This policy explains basic rules for using Arizona Network internet service safely, legally, and without harming other customers or the network.",
    sections: [
      {
        title: "Lawful use",
        paragraphs: [
          "Customers may not use Arizona Network service for unlawful, fraudulent, abusive, threatening, harassing, defamatory, or harmful activity.",
          "Customers are responsible for activity that occurs through their connection, including activity by guests, household members, devices, servers, and customer-owned routers.",
        ],
      },
      {
        title: "Network security",
        paragraphs: [
          "Customers may not attack, scan, disrupt, overload, probe, or attempt unauthorized access to any network, system, service, customer device, or Arizona Network infrastructure.",
          "Arizona Network may take reasonable action to protect the network, customers, and third parties from spam, malware, denial-of-service activity, botnets, identity theft, or other security threats.",
        ],
      },
      {
        title: "Fair use and network integrity",
        paragraphs: [
          "Customers may not use the service in a way that unreasonably interferes with other customers or degrades network performance.",
          "Arizona Network may manage traffic, suspend service, block harmful activity, or require corrective action when needed to protect network reliability and security.",
        ],
      },
      {
        title: "Resale and shared access",
        paragraphs: [
          "Residential service is intended for use at the service address. Customers may not resell service or provide service to other locations without written approval from Arizona Network.",
        ],
      },
    ],
  },
  "/privacy-policy": {
    eyebrow: "Policy",
    title: "Privacy Policy",
    intro: "Arizona Network collects and uses customer information to provide internet service, manage accounts, schedule installations, process support requests, and communicate about service.",
    sections: [
      {
        title: "Information we collect",
        paragraphs: [
          "Arizona Network may collect contact information, service address details, installation notes, account identifiers, billing status, communication records, support history, device and network diagnostics, and website sign-up information.",
          "Payment card details entered during sign-up are used to set up autopay with the billing system and are not intentionally stored in the website database.",
        ],
      },
      {
        title: "How we use information",
        paragraphs: [
          "Information is used to check service availability, create and manage accounts, schedule and complete installations, provide support, send account notices, process billing, improve service, and protect the network.",
          "Arizona Network may send transactional email or text messages related to installation, service, billing, outages, account notices, and support.",
        ],
      },
      {
        title: "Sharing",
        paragraphs: [
          "Arizona Network may share information with vendors and service providers that help operate the website, billing system, messaging, scheduling, support, network monitoring, or payment-related workflows.",
          "Arizona Network may also disclose information when required by law, to protect customers or the network, to investigate abuse, or to enforce service terms.",
        ],
      },
      {
        title: "Customer choices",
        paragraphs: [
          `Customers can request account help, contact updates, or privacy questions by emailing ${supportEmail}.`,
          "Marketing preferences are handled separately from service, billing, installation, outage, and legal notices.",
        ],
      },
    ],
  },
};

function generateUUID() {
  if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
    const random = Math.random() * 16 | 0;
    const value = char === "x" ? random : (random & 0x3) | 0x8;
    return value.toString(16);
  });
}

async function apiPost(path, body) {
  const response = await fetch(path, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  const data = await response.json();
  if (!response.ok) {
    throw new Error(data.message || "Request failed");
  }
  return data;
}

function normalizeSignupCode(value) {
  return String(value || "").trim().replace(/\s+/g, "").toUpperCase();
}

function luhnValid(value) {
  const digits = String(value || "").replace(/\D/g, "");
  if (digits.length < 12 || digits.length > 19) return false;
  let sum = 0;
  let doubleDigit = false;
  for (let index = digits.length - 1; index >= 0; index -= 1) {
    let digit = Number(digits[index]);
    if (doubleDigit) {
      digit *= 2;
      if (digit > 9) digit -= 9;
    }
    sum += digit;
    doubleDigit = !doubleDigit;
  }
  return sum % 10 === 0;
}

function isPastAppointmentTime(value) {
  const appointmentDate = new Date(value);
  return !Number.isFinite(appointmentDate.getTime()) || appointmentDate.getTime() <= Date.now();
}

function formatAppointmentDay(value) {
  const appointmentDate = new Date(value);
  if (!Number.isFinite(appointmentDate.getTime())) return "Install date";
  return appointmentDate.toLocaleDateString("en-US", {
    weekday: "short",
    month: "short",
    day: "numeric",
    timeZone: "America/Phoenix",
  });
}

function formatAppointmentTime(value) {
  const appointmentDate = new Date(value);
  if (!Number.isFinite(appointmentDate.getTime())) return "Install time";
  return appointmentDate.toLocaleTimeString("en-US", {
    hour: "numeric",
    minute: "2-digit",
    timeZone: "America/Phoenix",
  });
}

function formatDateInputValue(date = new Date()) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function formatDateForAppointmentApi(value) {
  const match = String(value || "").match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (!match) return new Date().toLocaleDateString("en-US");
  return `${Number(match[2])}/${Number(match[3])}/${match[1]}`;
}

function formatDateInputDisplay(value) {
  const match = String(value || "").match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (!match) return "soonest available";
  const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]), 12, 0, 0, 0);
  return date.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

function routerPlanKey(name) {
  return /pro|premium/i.test(String(name || "")) ? "Pro" : "Standard";
}

function routerDisplayName(name) {
  return `${routerPlanKey(name)} Router`;
}

function routerUpgradeAmount(plan, basePrice) {
  return Math.max(0, Number(plan?.price || 0) - Number(basePrice || 0));
}

function defaultPlanOptions() {
  return plans.map((plan) => ({
    value: plan.value,
    label: routerDisplayName(plan.name),
    name: plan.name,
    routerName: routerDisplayName(plan.name),
    price: plan.price,
  }));
}

function readStoredPlanOptions() {
  try {
    const stored = JSON.parse(localStorage.getItem("aznPlanOptions") || "null");
    if (Array.isArray(stored) && stored.length > 0) return stored;
  } catch (error) {
    // Fall back to the standard plan list when saved checkout data is stale.
  }
  return defaultPlanOptions();
}

async function loadGooglePlaces() {
  if (window.google?.maps?.places) return true;
  const config = await fetch("/api/config").then((res) => res.json());
  if (!config.googleMapsApiKey) return false;

  await new Promise((resolve, reject) => {
    const existing = document.querySelector("script[data-google-places]");
    if (existing) {
      existing.addEventListener("load", resolve, { once: true });
      existing.addEventListener("error", reject, { once: true });
      return;
    }

    const script = document.createElement("script");
    script.src = `https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(config.googleMapsApiKey)}&libraries=places`;
    script.async = true;
    script.defer = true;
    script.dataset.googlePlaces = "true";
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });

  return Boolean(window.google?.maps?.places);
}

async function loadGoogleMaps() {
  if (window.google?.maps?.Map) return true;
  const config = await fetch("/api/config").then((res) => res.json());
  if (!config.googleMapsApiKey) return false;

  await new Promise((resolve, reject) => {
    const existing = document.querySelector("script[data-google-maps]");
    if (existing) {
      existing.addEventListener("load", resolve, { once: true });
      existing.addEventListener("error", reject, { once: true });
      return;
    }

    const script = document.createElement("script");
    script.src = `https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(config.googleMapsApiKey)}`;
    script.async = true;
    script.defer = true;
    script.dataset.googleMaps = "true";
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });

  return Boolean(window.google?.maps?.Map);
}

function upsertMeta(name, content) {
  if (!content) return;
  let element = document.head.querySelector(`meta[name="${name}"]`);
  if (!element) {
    element = document.createElement("meta");
    element.setAttribute("name", name);
    document.head.appendChild(element);
  }
  element.setAttribute("content", content);
}

function upsertProperty(property, content) {
  if (!content) return;
  let element = document.head.querySelector(`meta[property="${property}"]`);
  if (!element) {
    element = document.createElement("meta");
    element.setAttribute("property", property);
    document.head.appendChild(element);
  }
  element.setAttribute("content", content);
}

function upsertLink(rel, href, attributes = {}) {
  if (!href) return;
  let element = document.head.querySelector(`link[rel="${rel}"]${attributes.hreflang ? `[hreflang="${attributes.hreflang}"]` : ""}`);
  if (!element) {
    element = document.createElement("link");
    element.setAttribute("rel", rel);
    Object.entries(attributes).forEach(([key, value]) => element.setAttribute(key, value));
    document.head.appendChild(element);
  }
  element.setAttribute("href", href);
}

function syncSeo(pathname, options = {}) {
  if (!seo.getRoute || !seo.absoluteUrl || !seo.buildStructuredData) return;
  const route = options.notFound
    ? {
        path: pathname || "/",
        title: "Page Not Found | Arizona Network",
        description: "The Arizona Network page you were looking for could not be found. Use the main navigation to get back to internet plans, support, or account tools.",
        keywords: "Arizona Network page not found, Arizona Network 404",
      }
    : seo.getRoute(pathname);
  const url = seo.absoluteUrl(route.path);
  const article = seo.getArticle ? seo.getArticle(route.path) : null;
  const image = seo.absoluteUrl(seo.socialImagePath);
  const robots = options.notFound ? "noindex, follow" : "index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1";

  document.documentElement.lang = "en-US";
  document.title = route.title;
  upsertMeta("description", route.description);
  upsertMeta("keywords", route.keywords);
  upsertMeta("robots", robots);
  upsertMeta("googlebot", robots);
  upsertMeta("bingbot", robots);
  upsertMeta("author", "Arizona Network");
  upsertMeta("geo.region", "US-AZ");
  upsertMeta("geo.placename", "Arizona");
  upsertLink("canonical", url);
  upsertLink("alternate", url, { hreflang: "en-US" });
  upsertProperty("og:type", article ? "article" : "website");
  upsertProperty("og:site_name", "Arizona Network");
  upsertProperty("og:title", route.title);
  upsertProperty("og:description", route.description);
  upsertProperty("og:url", url);
  upsertProperty("og:image", image);
  upsertProperty("og:locale", "en_US");
  if (article) {
    upsertProperty("article:published_time", article.published);
    upsertProperty("article:modified_time", article.modified);
    upsertProperty("article:section", article.category);
    upsertProperty("article:author", "Arizona Network");
  }
  upsertMeta("twitter:card", "summary_large_image");
  upsertMeta("twitter:title", route.title);
  upsertMeta("twitter:description", route.description);
  upsertMeta("twitter:image", image);

  let jsonLd = document.getElementById("azn-structured-data");
  if (!jsonLd) {
    jsonLd = document.createElement("script");
    jsonLd.id = "azn-structured-data";
    jsonLd.type = "application/ld+json";
    document.head.appendChild(jsonLd);
  }
  jsonLd.textContent = JSON.stringify(options.notFound ? {
    "@context": "https://schema.org",
    "@type": "WebPage",
    name: route.title,
    url,
    description: route.description,
    isPartOf: { "@id": `${seo.siteUrl}/#website` },
    about: { "@id": `${seo.siteUrl}/#organization` },
  } : seo.buildStructuredData(route.path));
}

function App() {
  const path = window.location.pathname.replace(/\/$/, "");
  const [signupPlan, setSignupPlan] = useState(() => localStorage.getItem("aznPreferredPlan") || "Standard");
  const [signupModalOpen, setSignupModalOpen] = useState(() => window.location.hash === "#signup");
  const isPlansPage = path === "/our-plans";
  const isSignupPage = path === "/signup";
  const isOrderPage = path === "/order";
  const isAboutPage = path === "/about-us";
  const isReviewsPage = path === "/reviews";
  const isFeedbackPage = path === "/feedback";
  const isHelpPage = path === "/help";
  const isNmdPage = path === "/nmd";
  const isPartnerPage = path === "/partner";
  const isCareersPage = path === "/careers";
  const isHomelabPage = path === "/homelab";
  const isGilbertTrialPage = path === "/gilbertfreetrial";
  const isReferralPage = path === "/referral-program";
  const isSpeedTestPage = path === "/speed-test";
  const isStatusPage = path === "/status";
  const isResourcesPage = path === "/resources";
  const activeLegalPage = legalPages[path];
  const activeArticle = resourceArticles.find((article) => article.path === path);
  const isLegalPage = Boolean(activeLegalPage);
  const isResourceArticlePage = Boolean(activeArticle);
  const isHomePage = path === "";
  const isKnownPage = isHomePage || isPlansPage || isSignupPage || isOrderPage || isAboutPage || isReviewsPage || isFeedbackPage || isHelpPage || isNmdPage || isPartnerPage || isCareersPage || isHomelabPage || isGilbertTrialPage || isReferralPage || isSpeedTestPage || isStatusPage || isResourcesPage || isResourceArticlePage || isLegalPage;

  useEffect(() => {
    syncSeo(path || "/", { notFound: !isKnownPage });
  }, [path, isKnownPage]);

  function openSignup(planName) {
    const nextPlan = planName || signupPlan;
    if (nextPlan) {
      setSignupPlan(nextPlan);
      localStorage.setItem("aznPreferredPlan", nextPlan);
    }
    setSignupModalOpen(true);
  }

  function closeSignupModal() {
    setSignupModalOpen(false);
    if (window.location.hash === "#signup") {
      window.history.replaceState(null, "", `${window.location.pathname}${window.location.search}`);
    }
  }

  useEffect(() => {
    function openFromHash() {
      if (window.location.hash === "#signup") openSignup();
    }

    openFromHash();
    window.addEventListener("hashchange", openFromHash);
    return () => window.removeEventListener("hashchange", openFromHash);
  }, []);

  useEffect(() => {
    document.body.classList.toggle("signup-modal-open", signupModalOpen);
    return () => document.body.classList.remove("signup-modal-open");
  }, [signupModalOpen]);

  return (
    <SignupContext.Provider value={{ openSignup }}>
      <Header
        active={path === "" ? "home" : isPlansPage ? "plans" : (isSignupPage || isOrderPage) ? "signup" : isAboutPage ? "about" : isReviewsPage ? "reviews" : isHelpPage ? "help" : (isResourcesPage || isResourceArticlePage) ? "resources" : isSpeedTestPage ? "speed" : isStatusPage ? "status" : ""}
        simple={isOrderPage}
      />
      <main>
        {isPlansPage ? <PlansPage /> :
          isSignupPage ? <SignupPage selectedPlan={signupPlan} setSelectedPlan={setSignupPlan} /> :
          isOrderPage ? <OrderPage selectedPlan={signupPlan} setSelectedPlan={setSignupPlan} /> :
          isAboutPage ? <AboutPage /> :
          isReviewsPage ? <ReviewsPage /> :
          isFeedbackPage ? <FeedbackPage /> :
          isHelpPage ? <HelpPage /> :
          isNmdPage ? <NmdPage /> :
          isPartnerPage ? <PartnerPage /> :
          isCareersPage ? <CareersPage /> :
          isHomelabPage ? <HomelabPage /> :
          isGilbertTrialPage ? <GilbertTrialPage /> :
          isReferralPage ? <ReferralPage /> :
          isSpeedTestPage ? <SpeedTestPage /> :
          isStatusPage ? <StatusPage /> :
          isResourcesPage ? <ResourcesPage /> :
          isResourceArticlePage ? <ResourceArticlePage article={activeArticle} /> :
          isLegalPage ? <LegalPage doc={activeLegalPage} /> :
          isHomePage ? <HomePage /> :
          <NotFoundPage />}
      </main>
      <Footer simple={isOrderPage} />
      {signupModalOpen && (
        <SignupAddressModal
          selectedPlan={signupPlan}
          setSelectedPlan={setSignupPlan}
          onClose={closeSignupModal}
        />
      )}
    </SignupContext.Provider>
  );
}

function NotFoundPage() {
  return (
    <div className="not-found-page">
      <section className="not-found-hero" aria-labelledby="notFoundTitle">
        <div className="not-found-copy">
          <p className="eyebrow">404 - signal not found</p>
          <h1 id="notFoundTitle">This page is not on our map.</h1>
          <p>
            The link may have moved, the URL may have a typo, or the page may no longer be available.
          </p>
          <div className="not-found-actions">
            <a className="button" href="/">Go Home</a>
            <a className="button secondary-button" href="/our-plans">View Internet Options</a>
            <a className="button secondary-button" href="/help">Get Help</a>
          </div>
        </div>
        <div className="not-found-card" aria-hidden="true">
          <span>404</span>
          <strong>Page not found</strong>
          <p>Try another Arizona Network page.</p>
        </div>
      </section>
    </div>
  );
}

function SpeedTestPage() {
  const [markup, setMarkup] = useState("");
  const scriptLoadedRef = useRef(false);

  useEffect(() => {
    let cancelled = false;

    async function loadSpeedTest() {
      const response = await fetch("/src/speed-test.html", { cache: "no-cache" });
      const html = await response.text();
      if (!cancelled) setMarkup(html);
    }

    loadSpeedTest().catch(() => {
      if (!cancelled) {
        setMarkup(`
          <section class="speed-page-intro" aria-labelledby="speedPageTitle">
            <div>
              <p class="eyebrow">Internet speed test</p>
              <h1 id="speedPageTitle">Arizona Network Speed Test</h1>
              <p>The speed test could not load. Please refresh the page and try again.</p>
            </div>
          </section>
        `);
      }
    });

    return () => {
      cancelled = true;
      document.body.classList.remove("modal-open");
    };
  }, []);

  useEffect(() => {
    if (!markup || scriptLoadedRef.current || !markup.includes('id="ring"')) return;
    scriptLoadedRef.current = true;
    window.AZN_SPEED_API_BASE = "/api/speed";

    const script = document.createElement("script");
    script.type = "module";
    script.src = "/src/speed-test-app.js";
    script.dataset.aznSpeedTest = "true";
    document.body.appendChild(script);
  }, [markup]);

  return (
    <div
      className="speed-test-page"
      dangerouslySetInnerHTML={{ __html: markup || '<section class="speed-page-intro"><p class="eyebrow">Internet speed test</p><h1>Loading speed test...</h1></section>' }}
    />
  );
}

function statusLabel(status) {
  if (status === "operational") return "Operational";
  if (status === "degraded") return "Degraded";
  if (status === "down") return "Offline";
  if (status === "maintenance") return "Maintenance";
  return "Pending";
}

function formatStatusTime(value) {
  if (!value) return "Waiting for first check";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Waiting for first check";
  return date.toLocaleString([], {
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
}

function formatShortStatusTime(value) {
  if (!value) return "Pending";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Pending";
  return date.toLocaleTimeString([], {
    hour: "numeric",
    minute: "2-digit",
  });
}

function latencyChartCoordinates(points, width, height, padding) {
  if (points.length === 0) return "";
  const times = points.map((point) => new Date(point.checkedAt).getTime());
  const latencies = points.map((point) => Number(point.latencyMs)).filter((value) => Number.isFinite(value));
  if (!latencies.length) return [];
  const minTime = Math.min(...times);
  const maxTime = Math.max(...times);
  const minSample = Math.min(...latencies);
  const maxSample = Math.max(...latencies);
  const spread = Math.max(2, maxSample - minSample);
  const minLatency = Math.max(0, minSample - spread * 0.8);
  const maxLatency = maxSample + spread * 0.8;
  const plotWidth = width - padding * 2;
  const plotHeight = height - padding * 2;

  return points.map((point) => {
    const time = new Date(point.checkedAt).getTime();
    const latency = Number(point.latencyMs);
    if (!Number.isFinite(latency)) return null;
    const x = padding + (maxTime === minTime ? plotWidth : ((time - minTime) / (maxTime - minTime)) * plotWidth);
    const y = padding + plotHeight - ((latency - minLatency) / (maxLatency - minLatency)) * plotHeight;
    return { ...point, x, y };
  }).filter(Boolean);
}

function latencyChartPath(points, width, height, padding) {
  return latencyChartCoordinates(points, width, height, padding)
    .map((point, index) => `${index === 0 ? "M" : "L"} ${point.x.toFixed(2)} ${point.y.toFixed(2)}`)
    .join(" ");
}

function StatusLatencyChart({ checks = [] }) {
  const points = checks.filter((check) => Number.isFinite(Number(check.latencyMs)));
  const width = 720;
  const height = 260;
  const padding = 38;
  const path = latencyChartPath(points, width, height, padding);
  const coordinates = latencyChartCoordinates(points, width, height, padding);
  const latencies = points.map((point) => Number(point.latencyMs));
  const average = latencies.length ? Math.round(latencies.reduce((total, value) => total + value, 0) / latencies.length) : null;
  const max = latencies.length ? Math.round(Math.max(...latencies)) : null;
  const min = latencies.length ? Math.round(Math.min(...latencies)) : null;
  const first = points[0]?.checkedAt;
  const last = points[points.length - 1]?.checkedAt;
  const lowPoint = coordinates.reduce((lowest, point) => Number(point.latencyMs) < Number(lowest.latencyMs) ? point : lowest, coordinates[0]);
  const highPoint = coordinates.reduce((highest, point) => Number(point.latencyMs) > Number(highest.latencyMs) ? point : highest, coordinates[0]);
  const highlightedPoints = [coordinates[0], lowPoint, highPoint, coordinates[coordinates.length - 1]]
    .filter(Boolean)
    .filter((point, index, array) => array.findIndex((item) => item.checkedAt === point.checkedAt && item.latencyMs === point.latencyMs) === index);
  const yLabels = latencies.length ? [max, average, min] : [];

  if (!points.length) {
    return (
      <div className="status-chart-empty">
        <p>No latency samples were recorded in the last 24 hours.</p>
      </div>
    );
  }

  return (
    <div className="status-chart">
      <div className="status-chart-stats" aria-label="Latency summary">
        <span>Avg {average} ms</span>
        <span>Low {min} ms</span>
        <span>High {max} ms</span>
      </div>
      <p className="status-chart-note">
        Response times have stayed low and steady during this period.
      </p>
      <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label="Latency over the last 24 hours" preserveAspectRatio="none">
        {[0, 0.5, 1].map((ratio, index) => {
          const y = padding + ratio * (height - padding * 2);
          return <line className="status-chart-grid" key={ratio} x1={padding} y1={y} x2={width - padding} y2={y} />;
        })}
        <line className="status-chart-axis-line" x1={padding} y1={height - padding} x2={width - padding} y2={height - padding} />
        <line className="status-chart-axis-line" x1={padding} y1={padding} x2={padding} y2={height - padding} />
        {yLabels.map((label, index) => {
          const y = padding + index * ((height - padding * 2) / 2);
          return <text key={`${label}-${index}`} x={padding - 10} y={y + 4} textAnchor="end">{label}ms</text>;
        })}
        <path className="status-chart-area" d={`${path} L ${width - padding} ${height - padding} L ${padding} ${height - padding} Z`} />
        <path className="status-chart-line" d={path} />
        {highlightedPoints.map((point) => <circle key={`${point.checkedAt}-${point.latencyMs}`} cx={point.x} cy={point.y} r="4" />)}
      </svg>
      <div className="status-chart-axis">
        <span>{formatShortStatusTime(first)}</span>
        <span>{formatShortStatusTime(last)}</span>
      </div>
    </div>
  );
}

function StatusHistoryPanel({ monitor, historyState }) {
  const checks = historyState?.data?.checks || [];
  const outages = checks.filter((check) => check.status === "down").length;
  const degraded = checks.filter((check) => check.status === "degraded").length;

  return (
    <div className="status-history-panel">
      <div className="status-history-heading">
        <div>
          <p className="eyebrow">Last 24 hours</p>
          <h3>{monitor.name} latency</h3>
        </div>
        <div className="status-history-stats">
          <span>{checks.length} checks</span>
          <span>{degraded} degraded</span>
          <span>{outages} offline</span>
        </div>
      </div>
      {historyState?.loading ? (
        <p className="notice">Loading 24-hour history...</p>
      ) : historyState?.error ? (
        <p className="notice">{historyState.error}</p>
      ) : (
        <StatusLatencyChart checks={checks} />
      )}
    </div>
  );
}

function monitorInitials(name = "") {
  const words = name.split(/\s+/).filter(Boolean);
  if (!words.length) return "AZ";
  return words.slice(0, 2).map((word) => word[0]).join("").toUpperCase();
}

function uptimePercent(checks = [], fallbackStatus = "unknown") {
  if (!checks.length) return fallbackStatus === "down" ? 0 : fallbackStatus === "unknown" ? null : 100;
  const upChecks = checks.filter((check) => check.status !== "down").length;
  return (upChecks / checks.length) * 100;
}

function latestLatency(checks = [], monitor) {
  const latest = [...checks].reverse().find((check) => Number.isFinite(Number(check.latencyMs)));
  const value = Number(latest?.latencyMs ?? monitor.latencyMs);
  return Number.isFinite(value) ? `${Math.round(value)}ms` : "Pending";
}

function statusBlockClass(status) {
  if (status === "down") return "down";
  if (status === "degraded") return "degraded";
  if (status === "maintenance") return "maintenance";
  if (status === "operational") return "up";
  return "unknown";
}

function statusColor(status) {
  if (status === "down") return "#ff3f57";
  if (status === "degraded") return "#ffd166";
  if (status === "maintenance") return "#56cfe1";
  return "#6bb69e";
}

function buildStatusBlocks(checks = [], count = 96) {
  if (!checks.length) return Array.from({ length: count }, () => ({ status: "unknown" }));
  const sorted = [...checks].sort((a, b) => new Date(a.checkedAt) - new Date(b.checkedAt));
  if (sorted.length >= count) return sorted.slice(-count);
  const pad = Array.from({ length: count - sorted.length }, () => ({ status: "unknown" }));
  return [...pad, ...sorted];
}

function StatusUptimeStrip({ checks = [], status = "unknown" }) {
  const blocks = buildStatusBlocks(checks, 72);
  if (!checks.length) {
    return <div className={`status-uptime-strip status-${statusBlockClass(status)}`} aria-label="Current status timeline" />;
  }

  return (
    <div className="status-uptime-strip segmented" aria-label="Last 24 hours status timeline">
      {blocks.map((check, index) => <span key={`${check.checkedAt || "empty"}-${index}`} className={statusBlockClass(check.status)} />)}
    </div>
  );
}

function StatusMinuteGrid({ checks = [] }) {
  const blocks = buildStatusBlocks(checks, 144);
  const rows = [
    ["00:00 - 05:59", blocks.slice(0, 36)],
    ["06:00 - 11:59", blocks.slice(36, 72)],
    ["12:00 - 17:59", blocks.slice(72, 108)],
    ["18:00 - 23:59", blocks.slice(108, 144)],
  ];

  return (
    <div className="status-minute-grid">
      {rows.map(([label, rowBlocks]) => (
        <div className="status-minute-row" key={label}>
          <p>{label}</p>
          <div>
            {rowBlocks.map((check, index) => <span key={`${label}-${check.checkedAt || "empty"}-${index}`} className={statusBlockClass(check.status)} />)}
          </div>
        </div>
      ))}
    </div>
  );
}

function StatusMonitorCard({ monitor, historyState, onOpen }) {
  const checks = historyState?.data?.checks || [];
  const percent = uptimePercent(checks, monitor.status);
  const percentText = percent === null ? "Pending" : `${percent.toFixed(3)}%`;

  return (
    <button className="status-monitor-card" type="button" onClick={onOpen}>
      <div className="status-monitor-top">
        <span className="status-monitor-avatar">{monitorInitials(monitor.name)}</span>
        <div>
          <h3>{monitor.name}</h3>
          <p>{monitor.message || "Arizona Network site"}</p>
        </div>
        <div className="status-monitor-score">
          <span className={`status-check-icon status-${monitor.status || "unknown"}`} aria-hidden="true" />
          <strong>{percentText}</strong>
          <small>{latestLatency(checks, monitor)}</small>
        </div>
      </div>
      <StatusUptimeStrip checks={checks} status={monitor.status} />
      <div className="status-monitor-dates">
        <span>24 hours ago</span>
        <span>{formatStatusTime(monitor.lastCheckedAt)}</span>
      </div>
    </button>
  );
}

function StatusOutageMap({ monitors = [], onOpen }) {
  const mapRef = useRef(null);
  const [mapsReady, setMapsReady] = useState(false);
  const [mapUnavailable, setMapUnavailable] = useState(false);
  const mappedMonitors = monitors.filter((monitor) => Number.isFinite(Number(monitor.latitude)) && Number.isFinite(Number(monitor.longitude)));
  const mapVersion = mappedMonitors.map((monitor) => `${monitor.id}:${monitor.status}:${monitor.latitude}:${monitor.longitude}`).join("|");

  useEffect(() => {
    let cancelled = false;
    loadGoogleMaps()
      .then((ready) => {
        if (!cancelled) {
          setMapsReady(ready);
          setMapUnavailable(!ready);
        }
      })
      .catch(() => {
        if (!cancelled) setMapUnavailable(true);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    if (!mapsReady || !mapRef.current || !mappedMonitors.length) return;
    const center = mappedMonitors.reduce((acc, monitor) => ({
      lat: acc.lat + Number(monitor.latitude) / mappedMonitors.length,
      lng: acc.lng + Number(monitor.longitude) / mappedMonitors.length,
    }), { lat: 0, lng: 0 });
    const map = new google.maps.Map(mapRef.current, {
      center,
      zoom: mappedMonitors.length > 1 ? 10 : 12,
      disableDefaultUI: true,
      zoomControl: true,
      backgroundColor: "#070709",
      styles: [
        { elementType: "geometry", stylers: [{ color: "#111217" }] },
        { elementType: "labels.text.fill", stylers: [{ color: "#b8bed8" }] },
        { elementType: "labels.text.stroke", stylers: [{ color: "#070709" }] },
        { featureType: "road", elementType: "geometry", stylers: [{ color: "#242733" }] },
        { featureType: "water", elementType: "geometry", stylers: [{ color: "#0c1828" }] },
        { featureType: "poi", stylers: [{ visibility: "off" }] },
      ],
    });
    const bounds = new google.maps.LatLngBounds();
    mappedMonitors.forEach((monitor) => {
      const position = { lat: Number(monitor.latitude), lng: Number(monitor.longitude) };
      bounds.extend(position);
      const marker = new google.maps.Marker({
        position,
        map,
        title: monitor.name,
        label: {
          text: monitorInitials(monitor.name),
          color: "#080812",
          fontWeight: "900",
        },
        icon: {
          path: google.maps.SymbolPath.CIRCLE,
          fillColor: statusColor(monitor.status),
          fillOpacity: 1,
          strokeColor: "#f7f8ff",
          strokeWeight: 2,
          scale: 14,
        },
      });
      marker.addListener("click", () => onOpen(monitor));
    });
    if (mappedMonitors.length > 1) map.fitBounds(bounds, 72);
  }, [mapsReady, mapVersion]);

  const hasOutages = monitors.some((monitor) => ["down", "degraded", "maintenance"].includes(monitor.status));
  const hasMonitorData = monitors.length > 0;
  const mapTitle = !hasMonitorData
    ? "Status map is waiting for monitor data."
    : hasOutages
      ? "Sites needing attention are highlighted."
      : "No outages detected on monitored sites.";
  const mapCopy = !hasMonitorData
    ? "Once monitor data is available, tower locations and outage markers will appear here."
    : hasOutages
      ? "Yellow, blue, and red markers show degraded, maintenance, or offline sites."
      : "All mapped towers are currently reporting normally. If your connection feels off, check your local equipment or contact support.";

  return (
    <section className="status-map-card" aria-labelledby="statusMapTitle">
      <div className="status-map-copy">
        <p className="eyebrow">Outage map</p>
        <h2 id="statusMapTitle">{mapTitle}</h2>
        <p>{mapCopy}</p>
      </div>
      <div className="status-map-shell">
        {mapsReady && mappedMonitors.length ? (
          <div className="status-google-map" ref={mapRef} aria-label="Arizona Network outage map" />
        ) : (
          <div className="status-map-fallback" ref={mapRef}>
            {mappedMonitors.length ? mappedMonitors.map((monitor, index) => (
              <button
                key={monitor.id || monitor.name}
                type="button"
                className={`status-map-pin status-${monitor.status || "unknown"}`}
                style={{
                  left: `${28 + (index % 4) * 18}%`,
                  top: `${30 + Math.floor(index / 4) * 18}%`,
                }}
                onClick={() => onOpen(monitor)}
              >
                {monitorInitials(monitor.name)}
              </button>
            )) : <p>No mapped monitors are available yet.</p>}
            {mapUnavailable && <span className="status-map-note">Map view is temporarily unavailable.</span>}
          </div>
        )}
      </div>
    </section>
  );
}

function StatusSiteMiniMap({ monitor }) {
  const mapRef = useRef(null);
  const [mapsReady, setMapsReady] = useState(false);
  const [mapUnavailable, setMapUnavailable] = useState(false);
  const latitude = Number(monitor?.latitude);
  const longitude = Number(monitor?.longitude);
  const hasLocation = Number.isFinite(latitude) && Number.isFinite(longitude);

  useEffect(() => {
    let cancelled = false;
    if (!hasLocation) return undefined;
    loadGoogleMaps()
      .then((ready) => {
        if (!cancelled) {
          setMapsReady(ready);
          setMapUnavailable(!ready);
        }
      })
      .catch(() => {
        if (!cancelled) setMapUnavailable(true);
      });
    return () => {
      cancelled = true;
    };
  }, [hasLocation]);

  useEffect(() => {
    if (!mapsReady || !mapRef.current || !hasLocation) return;
    const position = { lat: latitude, lng: longitude };
    const map = new google.maps.Map(mapRef.current, {
      center: position,
      zoom: 13,
      disableDefaultUI: true,
      zoomControl: true,
      backgroundColor: "#070709",
      styles: [
        { elementType: "geometry", stylers: [{ color: "#111217" }] },
        { elementType: "labels.text.fill", stylers: [{ color: "#b8bed8" }] },
        { elementType: "labels.text.stroke", stylers: [{ color: "#070709" }] },
        { featureType: "road", elementType: "geometry", stylers: [{ color: "#242733" }] },
        { featureType: "water", elementType: "geometry", stylers: [{ color: "#0c1828" }] },
        { featureType: "poi", stylers: [{ visibility: "off" }] },
      ],
    });
    new google.maps.Marker({
      position,
      map,
      title: monitor.name,
      label: {
        text: monitorInitials(monitor.name),
        color: "#080812",
        fontWeight: "900",
      },
      icon: {
        path: google.maps.SymbolPath.CIRCLE,
        fillColor: statusColor(monitor.status),
        fillOpacity: 1,
        strokeColor: "#f7f8ff",
        strokeWeight: 2,
        scale: 14,
      },
    });
  }, [mapsReady, hasLocation, latitude, longitude, monitor.status]);

  return (
    <div className="status-site-map-card">
      <div>
        <p className="eyebrow">Site location</p>
        <h3>{monitor.name}</h3>
      </div>
      {hasLocation ? (
        <div className="status-site-map-shell">
          {mapsReady ? (
            <div className="status-site-google-map" ref={mapRef} aria-label={`${monitor.name} map`} />
          ) : (
            <div className="status-site-map-fallback" ref={mapRef}>
              <span className={`status-map-pin status-${monitor.status || "unknown"}`}>{monitorInitials(monitor.name)}</span>
              {mapUnavailable && <small>Map view is temporarily unavailable.</small>}
            </div>
          )}
        </div>
      ) : (
        <p className="status-map-missing">No location is configured for this site yet.</p>
      )}
    </div>
  );
}

function StatusEventList({ events = [], fallback, maintenance = false }) {
  if (!events.length) return <p>{fallback}</p>;

  return (
    <div className="status-event-list">
      {events.map((event) => (
        <article key={event.id || event.title}>
          <span>{maintenance ? event.status || "scheduled" : event.impact || event.status || "incident"}</span>
          <h3>{event.title}</h3>
          {event.description && <p>{event.description}</p>}
          <small>
            {maintenance
              ? `${formatStatusTime(event.startsAt)} - ${formatStatusTime(event.endsAt)}`
              : `Started ${formatStatusTime(event.startedAt)}`}
          </small>
        </article>
      ))}
    </div>
  );
}

function StatusEventsPanel({ incidents = [], maintenances = [] }) {
  if (!incidents.length && !maintenances.length) return null;

  return (
    <section className="status-events" aria-label="Network status events">
      {incidents.length > 0 && (
        <div>
          <p className="eyebrow">Active incidents</p>
          <StatusEventList events={incidents} fallback="" />
        </div>
      )}
      {maintenances.length > 0 && (
        <div>
          <p className="eyebrow">Scheduled maintenance</p>
          <StatusEventList events={maintenances} fallback="" maintenance />
        </div>
      )}
    </section>
  );
}

function StatusDayModal({ monitor, historyState, onClose }) {
  const [activeTab, setActiveTab] = useState("status");
  const checks = historyState?.data?.checks || [];
  const monitorIncidents = historyState?.data?.incidents || [];
  const monitorMaintenances = historyState?.data?.maintenances || [];
  const percent = uptimePercent(checks, monitor.status);
  const percentText = percent === null ? "Pending" : `${percent.toFixed(2)}%`;
  const incidents = checks.filter((check) => check.status === "down").length;

  useEffect(() => {
    function closeOnEscape(event) {
      if (event.key === "Escape") onClose();
    }
    window.addEventListener("keydown", closeOnEscape);
    return () => window.removeEventListener("keydown", closeOnEscape);
  }, [onClose]);

  return (
    <div className="status-modal-backdrop" onMouseDown={(event) => {
      if (event.target === event.currentTarget) onClose();
    }}>
      <div className="status-modal" role="dialog" aria-modal="true" aria-labelledby="statusModalTitle">
        <button className="status-modal-close" type="button" onClick={onClose} aria-label="Close status details">x</button>
        <div className="status-modal-heading">
          <div>
            <h2 id="statusModalTitle">{monitor.name}</h2>
            <p>Minute-by-minute status data for the last 24 hours</p>
          </div>
          <strong>{percentText}</strong>
        </div>
        <div className="status-modal-tabs" role="tablist" aria-label="Status detail views">
          {["status", "latency", "incidents", "maintenances"].map((tab) => (
            <button key={tab} type="button" className={activeTab === tab ? "active" : ""} onClick={() => setActiveTab(tab)}>
              {tab[0].toUpperCase() + tab.slice(1)}
            </button>
          ))}
        </div>
        <div className="status-modal-panel">
          <StatusSiteMiniMap monitor={monitor} />
          {historyState?.loading ? (
            <p className="notice">Loading 24-hour history...</p>
          ) : historyState?.error ? (
            <p className="notice">{historyState.error}</p>
          ) : activeTab === "latency" ? (
            <StatusLatencyChart checks={checks} />
          ) : activeTab === "incidents" ? (
            <StatusEventList
              events={monitorIncidents}
              fallback={incidents ? `${incidents} offline checks were recorded in this window.` : "No offline incidents were recorded in this window."}
            />
          ) : activeTab === "maintenances" ? (
            <StatusEventList
              events={monitorMaintenances}
              fallback="No scheduled maintenance events are attached to this monitor yet."
              maintenance
            />
          ) : (
            <>
              <div className="status-modal-subhead">
                <h3>Per-Minute Status</h3>
                <span>{percentText}</span>
              </div>
              <StatusMinuteGrid checks={checks} />
              <div className="status-modal-legend">
                <span><i className="up" /> Operational</span>
                <span><i className="degraded" /> Degraded</span>
                <span><i className="maintenance" /> Maintenance</span>
                <span><i className="down" /> Offline</span>
                <span><i className="unknown" /> No data</span>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function StatusPage() {
  const [summary, setSummary] = useState(null);
  const [error, setError] = useState("");
  const [activeMonitor, setActiveMonitor] = useState(null);
  const [historyByMonitor, setHistoryByMonitor] = useState({});
  const monitors = summary?.monitors || [];
  const incidents = summary?.incidents || [];
  const maintenances = summary?.maintenances || [];
  const overall = summary?.overall || "unknown";
  const statusPlainLanguage = overall === "operational"
    ? "No outages detected. Arizona Network service is operating normally."
    : overall === "degraded"
      ? "One or more sites are responding inconsistently. We are watching it closely."
      : overall === "down"
        ? "An outage is detected at one or more sites."
        : overall === "maintenance"
          ? "Scheduled maintenance is in progress on one or more sites."
          : "Status data is still warming up.";

  useEffect(() => {
    let cancelled = false;

    async function loadStatus() {
      try {
        const response = await fetch("/api/status/summary", { cache: "no-store" });
        const data = await response.json();
        if (cancelled) return;
        setSummary(data);
        setError(response.ok ? "" : "Status data is still warming up.");
      } catch {
        if (!cancelled) {
          setError("Status data is temporarily unavailable.");
        }
      }
    }

    loadStatus();
    const interval = setInterval(loadStatus, 60000);
    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, []);

  async function loadMonitorHistory(monitor) {
    if (historyByMonitor[monitor.id]?.data || historyByMonitor[monitor.id]?.loading) return;
    setHistoryByMonitor((current) => ({
      ...current,
      [monitor.id]: { loading: true, data: null, error: "" },
    }));
    try {
      const response = await fetch(`/api/status/history?monitorId=${encodeURIComponent(monitor.id)}`, { cache: "no-store" });
      const data = await response.json();
      setHistoryByMonitor((current) => ({
        ...current,
        [monitor.id]: {
          loading: false,
          data,
          error: response.ok ? "" : "Status history is temporarily unavailable.",
        },
      }));
    } catch {
      setHistoryByMonitor((current) => ({
        ...current,
        [monitor.id]: { loading: false, data: null, error: "Status history is temporarily unavailable." },
      }));
    }
  }

  function openMonitor(monitor) {
    setActiveMonitor(monitor);
    loadMonitorHistory(monitor);
  }

  useEffect(() => {
    monitors.slice(0, 12).forEach((monitor) => {
      loadMonitorHistory(monitor);
    });
  }, [summary?.updatedAt]);

  return (
    <div className="status-page">
      <section className="status-hero compact" aria-labelledby="networkStatusTitle">
        <div className="status-page-kicker">
          <span>Is Arizona Network Down?</span>
        </div>
        <div>
          <h1 id="networkStatusTitle">Is Arizona Network Down?</h1>
          <p>Real-time Arizona Network service status.</p>
        </div>
      </section>

      <section className={`status-overview status-${overall}`} aria-label="Network status summary">
        <span className="status-glow" />
        <h2>{overall === "operational" ? "All sites operational" : summary?.label || "Loading network status"}</h2>
        <p>{statusPlainLanguage} We are checking {monitors.length} live network {monitors.length === 1 ? "site" : "sites"}. Last updated {formatStatusTime(summary?.updatedAt)}.</p>
      </section>

      <StatusEventsPanel incidents={incidents} maintenances={maintenances} />

      <StatusOutageMap monitors={monitors} onOpen={openMonitor} />

      <section className="status-board modern" aria-labelledby="statusBoardTitle">
        <div className="status-board-heading">
          <div>
            <p className="eyebrow">Tower monitors</p>
            <h2 id="statusBoardTitle">Site uptime</h2>
          </div>
          {error && <p className="notice">{error}</p>}
        </div>
        <div className="status-monitor-list">
          {monitors.length ? monitors.map((monitor) => (
            <StatusMonitorCard
              key={monitor.id || monitor.name}
              monitor={monitor}
              historyState={historyByMonitor[monitor.id]}
              onOpen={() => openMonitor(monitor)}
            />
          )) : (
            <p>No monitors are reporting yet.</p>
          )}
        </div>
      </section>
      {activeMonitor && (
        <StatusDayModal
          monitor={activeMonitor}
          historyState={historyByMonitor[activeMonitor.id]}
          onClose={() => setActiveMonitor(null)}
        />
      )}
    </div>
  );
}

function HomePage() {
  const { openSignup } = useSignup();

  return (
    <>
      <section className="hero" id="home">
        <video
          className="hero-video"
          autoPlay
          muted
          loop
          playsInline
          preload="metadata"
          poster={media.heroPoster}
        >
          <source src={media.heroMobile} media="(max-width: 720px)" type="video/mp4" />
          <source src={media.heroDesktop} type="video/mp4" />
        </video>
        <div className="hero-card">
          <div>
            <h1>Fast Home Internet for Arizona Neighborhoods</h1>
            <p>Professionally installed fixed wireless internet for Gilbert, Florence, San Tan Valley, and nearby communities.</p>
            <p>No contracts. No throttling. No surprise bills. Just local service that works.</p>
          </div>
          <button className="button shadow" type="button" onClick={() => openSignup()}>Check Availability</button>
        </div>
      </section>

      <section className="community" id="about">
        <div className="community-inner">
          <div className="copy-block">
            <h2>Local Internet, Local Accountability</h2>
            <p>Arizona Network is an Arizona-owned internet provider built for neighborhoods that want reliable speed without contracts, bundles, or call-center runaround.</p>
            <p>We live here, we work here, and we treat your home connection like it matters because it does.</p>
            <a href="/about-us">Read more about Arizona Network</a>
          </div>
          <img src={media.gilbert} alt="New Service Available In Gilbert, AZ" />
        </div>
      </section>

      <section className="promise-band" id="plans">
        <div className="promise-band-inner">
          <h2>No contracts.</h2>
          <h2>No bundles.</h2>
          <h2>No surprises.</h2>
        </div>
      </section>

      <ServiceAreaSection />
      <ResourcePreview />
      <SignupCta />
      <Testimonial />

      <section className="feature-grid">
        <div className="feature-grid-inner">
          <Feature title="24/7 Customer Support" text="Any problem, any time. Get the help you need, not a sales pitch." accent="480-582-1736" />
          <Feature title="Router Included" text="Residential Internet includes the equipment required to get connected. Choose the included standard router, upgrade the router, or add an extender for more coverage." images={[media.standardRouter, media.proRouter]} />
          <Feature
            title="Free Internet For Life"
            text="Give someone $100 toward their first bill, earn $100 when they install, and after five successful referrals your internet is free for life."
            highlights={[["Give", "$100"], ["Get", "$100"], ["Refer", "5"]]}
            ctaHref="/referral-program"
            ctaLabel="See Referral Program"
            className="feature-referral"
            showBackground={false}
          />
        </div>
      </section>
    </>
  );
}

function ServiceAreaSection() {
  return (
    <section className="service-area-section" aria-labelledby="service-area-heading">
      <p className="eyebrow">Arizona internet service areas</p>
      <h2 id="service-area-heading">Local internet for Gilbert, Florence, San Tan Valley, and nearby communities.</h2>
      <p>Arizona Network provides fixed wireless home internet for Arizona neighborhoods that want reliable speed, local support, transparent pricing, and no contracts.</p>
      <ul aria-label="Current Arizona Network service areas">
        {serviceAreas.map((area) => <li key={area}>{area}</li>)}
      </ul>
    </section>
  );
}

function ResourcePreview() {
  return (
    <section className="resource-preview" aria-labelledby="resource-preview-heading">
      <div className="resource-preview-heading">
        <p className="eyebrow">Internet guides</p>
        <h2 id="resource-preview-heading">Make a smarter internet decision.</h2>
        <a className="advanced-link" href="/resources">View all resources</a>
      </div>
      <div className="resource-grid compact">
        {resourceArticles.slice(0, 3).map((article) => <ResourceCard key={article.slug} article={article} />)}
      </div>
    </section>
  );
}

function PlansPage() {
  const { openSignup } = useSignup();
  const [selectedPlan, setSelectedPlan] = useState("Standard");
  const base = Math.min(...plans.map((plan) => plan.price));
  const selectedRouterPlan = plans.find((plan) => plan.name === selectedPlan) || plans[0];
  const regulatory = Number((selectedRouterPlan.price * 0.03).toFixed(2));
  const monthly = selectedRouterPlan.price + regulatory;
  const installFee = 74;

  return (
    <div className="plans-page">
      <section className="plans-hero" style={{ backgroundImage: `url(${media.plansBg})` }}>
        <div className="plans-hero-copy">
          <h1>Up to 1 Gbps Home Internet with Clear Pricing</h1>
        </div>
      </section>

      <section className="plan-card-section" id="plans">
        <ResidentialInternetCard onChoose={() => openSignup(selectedPlan)} />
        <div className="router-choice-heading">
          <p className="eyebrow">Choose Your Router</p>
          <h2>The internet service is the same. Pick the WiFi hardware that fits your home.</h2>
        </div>
        <div className="plan-cards router-plan-cards">
          {plans.map((plan) => (
            <PlanCard
              key={plan.name}
              plan={plan}
              basePrice={base}
              selected={selectedPlan === plan.name}
              onChoose={() => {
                setSelectedPlan(plan.name);
                openSignup(plan.name);
              }}
            />
          ))}
        </div>
      </section>

      <section className="transition-plan">
        <p className="eyebrow">Home Internet Transition Plan</p>
        <h2>A simple, stress-free switch from your old provider to your new one.</h2>
        <div className="transition-grid">
          <MiniStep title="Keep Your Existing WiFi Name" text="We can pre-configure your new router with your existing network name and password, so phones, TVs, tablets, cameras, and smart home devices reconnect automatically." />
          <MiniStep title="Zero Downtime" text="We install your new service before you cancel your old one. Once everything is running smoothly, then you confirm cancellation with your old provider." />
          <MiniStep title="A Risk-Free First Month" text="If the service does not work for you in the first 30 days, you can cancel without penalty and we will help you transition back if needed." />
        </div>
      </section>

      <SignupCta selectedPlan={`${selectedPlan} Router`} monthly={monthly} installFee={installFee} onOpen={() => openSignup(selectedPlan)} />

      <PerformanceSection />
      <RouterSpecs />
      <InstallProcess />
      <Testimonial />
    </div>
  );
}

function SignupPage({ selectedPlan, setSelectedPlan }) {
  return (
    <div className="signup-page">
      <SignupPanel selectedPlan={selectedPlan} setSelectedPlan={setSelectedPlan} titleId="signupPageTitle" initialStep={0} />
    </div>
  );
}

function OrderPage({ selectedPlan, setSelectedPlan }) {
  return (
    <div className="signup-page order-page">
      <SignupPanel selectedPlan={selectedPlan} setSelectedPlan={setSelectedPlan} titleId="orderPageTitle" initialStep={1} />
    </div>
  );
}

function SignupAddressModal({ selectedPlan, setSelectedPlan, onClose }) {
  useEffect(() => {
    function handleKeyDown(event) {
      if (event.key === "Escape") onClose();
    }
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [onClose]);

  function closeOnBackdrop(event) {
    if (event.target === event.currentTarget) onClose();
  }

  return (
    <div className="signup-modal-backdrop" onMouseDown={closeOnBackdrop}>
      <section className="signup-modal" role="dialog" aria-modal="true" aria-labelledby="signupModalTitle">
        <button className="signup-modal-close" type="button" onClick={onClose} aria-label="Close signup">&times;</button>
        <SignupPanel
          selectedPlan={selectedPlan}
          setSelectedPlan={setSelectedPlan}
          titleId="signupModalTitle"
          initialStep={0}
          modal
          onServiceable={() => {
            onClose();
            window.location.href = "/order";
          }}
        />
      </section>
    </div>
  );
}

function AboutPage() {
  const valueCards = [
    {
      title: "You get our best price.",
      lead: "Life can be full of surprises, but your internet price shouldn't be one of them.",
      text: "We don't have contracts or surprise price hikes. In fact, our price per Mbps has decreased since we launched in 2017.",
      icon: "$",
    },
    {
      title: "You get help from people who stay with it.",
      lead: "Getting the help you need should never be stressful or difficult.",
      text: "Our support team is local, personal, and focused on solving the issue instead of passing you around.",
      icon: "i",
    },
    {
      title: "You get internet without the clutter.",
      lead: "We offer quality internet. That's what we do best and what we'll stick to.",
      text: "No confusing bundles with products that you don't need. One simple plan, just choose the right router for your home.",
      icon: "...",
    },
  ];

  const tech = [
    ["Cambium 4625", media.cambium4625],
    ["Ubiquiti LTU AP", media.ubiquitiLtuAp],
    ["Cambium 4600 AP", media.cambium4600],
    ["Ubiquiti LTU LR", media.ubiquitiLtuLr],
    ["Ubiquiti Wave LR", media.dish],
    ["Ubiquiti Wave AP", media.ubiquitiWaveAp],
  ];

  return (
    <div className="about-page">
      <section className="about-hero" style={{ backgroundImage: `url(${media.aboutHero})` }}>
        <div className="about-hero-card">
          <h1>Local internet service with real people behind it.</h1>
          <div className="risk-free">
            <h2>Try it risk-free</h2>
            <p>If your service does not meet your expectations within the first 30 days, we will refund your installation fee and your first month with no hassle and no fine print.</p>
          </div>
        </div>
      </section>

      <section className="about-values">
        {valueCards.map((card) => (
          <article key={card.title}>
            <span className="value-icon">{card.icon}</span>
            <h2>{card.title}</h2>
            <h3>{card.lead}</h3>
            <p>{card.text}</p>
          </article>
        ))}
      </section>

      <section className="support-split">
        <div>
          <h2>Real support from real people</h2>
          <p>We pride ourselves on delivering exceptional service through our expert technicians and customer care team.</p>
          <p><strong>When the internet acts up, our priority is solving the problem, not giving you a sales pitch.</strong></p>
          <p>Arizona Network uses fast, secure routers and professional installation because a good connection has to work inside the home too. When something is not working the way it should, we stay with it until there is a clear next step.</p>
        </div>
        <img src={media.supportAgent} alt="Friendly customer service agent quickly helps solve issues." />
      </section>

      <section className="tech-section" style={{ backgroundImage: `url(${media.techGradient})` }}>
        <div className="tech-section-inner">
          <div className="tech-copy">
            <h2>Smarter tech, better results</h2>
            <p>We believe your internet should just work - fast, reliable, and hassle-free. That is why we use the best tools available, whether it is cutting-edge 60 GHz Ubiquiti Wave for ultra-high-speed connections or Cambium AX 6 GHz for rock-solid coverage in challenging environments.</p>
            <p>By combining these advanced technologies, we make sure you get the performance you need, wherever you are. Unlike the one-size-fits-all providers, we design our network with flexibility in mind, adapting to each community and location we serve.</p>
          </div>
          <div className="tech-grid">
            {tech.map(([name, src]) => (
              <figure key={name}>
                <img src={src} alt={name} />
                <figcaption>{name}</figcaption>
              </figure>
            ))}
          </div>
        </div>
      </section>

      <section className="about-cta">
        <p>Ready to see your options?</p>
        <a className="button" href="/our-plans">View Internet Options</a>
      </section>
    </div>
  );
}

function ReviewsPage() {
  const reviews = [
    {
      quote: "Aaron stayed with me to make sure all my electronics were set up and running, then fine tuned the service till it was working great.",
      name: "Lisa D.",
      since: "Google review",
      theme: "Hands-on setup",
    },
    {
      quote: "Nick did an outstanding job. Arrived on time and completed the required work the first time, with no re-dos.",
      name: "Steve W.",
      since: "Google review",
      theme: "On-time install",
    },
    {
      quote: "So glad to switch from Cox. This is better quality, faster speed, unlimited downloading and cheaper.",
      name: "Dawn W.",
      since: "Google review",
      theme: "Better value",
    },
    {
      quote: "We are very pleased with the speed and consistency of the service. The service men were very professional and did a wonderful job.",
      name: "Cathy L.",
      since: "Google review",
      theme: "Consistent speed",
    },
    {
      quote: "The installer was excellent, explained everything about the install and how the unit works, and was very polite and professional.",
      name: "Ruth C.",
      since: "Google review",
      theme: "Clear communication",
    },
    {
      quote: "Technicians were on time, efficient, courteous, friendly and extremely helpful.",
      name: "Mary Ann W.",
      since: "Google review",
      theme: "Helpful technicians",
    },
  ];
  const proofPoints = [
    ["24/7", "Support when the connection matters"],
    ["No contracts", "Stay because it works, not because you are locked in"],
    ["Local team", "People who know the neighborhoods we serve"],
  ];
  const reviewThemes = [
    ["Technicians Who Stay With It", "Customers call out installers who make sure devices are connected, wiring is current, and the service is tuned before they leave."],
    ["A Real Alternative to Big Providers", "Several reviews mention switching from larger providers for better value, unlimited downloading, and a more personal support experience."],
    ["Professional Communication", "Reviews repeatedly mention on-time visits, clear explanations, polite technicians, and helpful office communication when schedules change."],
  ];

  return (
    <div className="reviews-page">
      <section className="reviews-hero" style={{ backgroundImage: `url(${media.reviewsBg})` }}>
        <div className="reviews-hero-copy">
          <p className="eyebrow">Customer reviews</p>
          <h1>Don't just take our word for it! <span>Hear what our customers have to say.</span></h1>
        </div>
      </section>

      <section className="review-proof" aria-label="Arizona Network review highlights">
        {proofPoints.map(([value, label]) => (
          <article key={value}>
            <strong>{value}</strong>
            <span>{label}</span>
          </article>
        ))}
      </section>

      <section className="reviews-grid" aria-label="Customer reviews">
        <div className="reviews-section-heading">
          <p className="eyebrow">In their words</p>
          <h2>What customers notice after switching.</h2>
        </div>
        <div className="reviews-grid-inner">
          {reviews.map((review) => <ReviewCard key={review.name} review={review} />)}
        </div>
      </section>

      <section className="review-feature">
        <div>
          <p className="eyebrow">A different kind of ISP</p>
          <h2>Built around service, not call-center runaround.</h2>
          <p>Arizona Network is small enough to be personal and technical enough to solve real internet problems. The goal is simple: clear communication, reliable installs, and support that treats your home connection like it matters.</p>
        </div>
        <blockquote>
          "I saved $110 a month and the quality is so much better."
          <cite>Lisa D., Google review</cite>
        </blockquote>
      </section>

      <section className="review-themes" aria-labelledby="reviewThemesTitle">
        <div className="reviews-section-heading">
          <p className="eyebrow">Common themes</p>
          <h2 id="reviewThemesTitle">The patterns behind the feedback.</h2>
        </div>
        <div className="review-theme-grid">
          {reviewThemes.map(([title, text]) => (
            <article key={title}>
              <h3>{title}</h3>
              <p>{text}</p>
            </article>
          ))}
        </div>
      </section>

      <section className="more-reviews">
        <h2>Need more?</h2>
        <div className="more-actions">
          <a className="button" href={googleReviewsUrl} target="_blank" rel="noopener noreferrer">Google Reviews</a>
          <a className="button secondary-button" href="/about-us">Read About Us</a>
        </div>
        <p>Still undecided? Learn more about how Arizona Network works and what makes the service different.</p>
      </section>

      <SignupCta eyebrow="Ready to get connected?" title="Check your address without leaving this page." />
    </div>
  );
}

function FeedbackPage() {
  const params = new URLSearchParams(window.location.search);
  const satisfactionOptions = ["Very satisfied", "Satisfied", "Neutral", "Unsatisfied", "Very unsatisfied"];
  const reliabilityOptions = ["Excellent", "Good", "Okay", "Poor", "Not sure"];
  const [form, setForm] = useState({
    mbrId: params.get("mbr_id") || params.get("customer_id") || "",
    firstName: params.get("first_name") || params.get("firstName") || params.get("name") || "",
    lastName: params.get("last_name") || params.get("lastName") || "",
    email: params.get("email") || "",
    refCode: params.get("ref_code") || params.get("refCode") || "",
    npsScore: params.get("nps") || "",
    overallSatisfaction: "",
    internetReliability: "",
    speedSatisfaction: "",
    supportSatisfaction: "",
    billingSatisfaction: "",
    likedMost: "",
    improvementFeedback: "",
    contactPermission: false,
  });
  const [status, setStatus] = useState("");
  const [busy, setBusy] = useState(false);

  function updateField(field, value) {
    setForm((current) => ({ ...current, [field]: value }));
  }

  function updateCheckbox(field, checked) {
    setForm((current) => ({ ...current, [field]: checked }));
  }

  async function submitFeedback(event) {
    event.preventDefault();
    if (form.npsScore === "") {
      setStatus("Choose a 0-10 recommendation score before submitting.");
      return;
    }
    if (!form.overallSatisfaction) {
      setStatus("Choose an overall satisfaction rating before submitting.");
      return;
    }

    setBusy(true);
    setStatus("Submitting your survey...");
    try {
      const result = await apiPost("/api/feedback", {
        ...form,
        source: params.get("source") || "biannual_survey",
      });
      if (result.status === "failure") {
        setStatus("We could not submit that just now. Please call or email us and we will help.");
        return;
      }
      setForm((current) => ({
        ...current,
        npsScore: "",
        overallSatisfaction: "",
        internetReliability: "",
        speedSatisfaction: "",
        supportSatisfaction: "",
        billingSatisfaction: "",
        likedMost: "",
        improvementFeedback: "",
        contactPermission: false,
      }));
      setStatus("Thank you. Your survey was submitted to the Arizona Network team.");
    } catch (error) {
      setStatus(error.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="feedback-page">
      <section className="simple-hero feedback-hero">
        <p className="eyebrow">Customer survey</p>
        <h1>How are we doing?</h1>
        <p>This short survey helps us measure customer satisfaction and spot what needs attention across reliability, speed, support, and billing.</p>
      </section>

      <section className="feedback-section">
        <form className="feedback-form" onSubmit={submitFeedback}>
          <div>
            <p className="eyebrow">Your experience</p>
            <h2>Customer satisfaction survey</h2>
          </div>
          <div className="survey-grid">
            <label htmlFor="feedbackFirstName">
              First name
              <input id="feedbackFirstName" value={form.firstName} onChange={(event) => updateField("firstName", event.target.value)} autoComplete="given-name" />
            </label>
            <label htmlFor="feedbackLastName">
              Last name
              <input id="feedbackLastName" value={form.lastName} onChange={(event) => updateField("lastName", event.target.value)} autoComplete="family-name" />
            </label>
          </div>
          <label htmlFor="feedbackEmail">
            Email
            <input id="feedbackEmail" type="email" value={form.email} onChange={(event) => updateField("email", event.target.value)} autoComplete="email" />
          </label>

          <fieldset className="survey-fieldset">
            <legend>How likely are you to recommend Arizona Network to a friend or neighbor?</legend>
            <div className="nps-scale">
              {Array.from({ length: 11 }, (_, score) => (
                <label key={score} className={form.npsScore === String(score) ? "selected" : ""}>
                  <input
                    type="radio"
                    name="npsScore"
                    value={score}
                    checked={form.npsScore === String(score)}
                    onChange={(event) => updateField("npsScore", event.target.value)}
                  />
                  <span>{score}</span>
                </label>
              ))}
            </div>
            <div className="nps-labels">
              <span>Not likely</span>
              <span>Extremely likely</span>
            </div>
          </fieldset>

          <label htmlFor="overallSatisfaction">
            Overall satisfaction
            <select id="overallSatisfaction" value={form.overallSatisfaction} onChange={(event) => updateField("overallSatisfaction", event.target.value)}>
              <option value="">Choose one</option>
              {satisfactionOptions.map((option) => <option key={option} value={option}>{option}</option>)}
            </select>
          </label>

          <div className="survey-grid">
            <label htmlFor="internetReliability">
              Internet reliability
              <select id="internetReliability" value={form.internetReliability} onChange={(event) => updateField("internetReliability", event.target.value)}>
                <option value="">Choose one</option>
                {reliabilityOptions.map((option) => <option key={option} value={option}>{option}</option>)}
              </select>
            </label>
            <label htmlFor="speedSatisfaction">
              Speed performance
              <select id="speedSatisfaction" value={form.speedSatisfaction} onChange={(event) => updateField("speedSatisfaction", event.target.value)}>
                <option value="">Choose one</option>
                {satisfactionOptions.map((option) => <option key={option} value={option}>{option}</option>)}
              </select>
            </label>
            <label htmlFor="supportSatisfaction">
              Support experience
              <select id="supportSatisfaction" value={form.supportSatisfaction} onChange={(event) => updateField("supportSatisfaction", event.target.value)}>
                <option value="">Choose one</option>
                {satisfactionOptions.map((option) => <option key={option} value={option}>{option}</option>)}
              </select>
            </label>
            <label htmlFor="billingSatisfaction">
              Billing clarity
              <select id="billingSatisfaction" value={form.billingSatisfaction} onChange={(event) => updateField("billingSatisfaction", event.target.value)}>
                <option value="">Choose one</option>
                {satisfactionOptions.map((option) => <option key={option} value={option}>{option}</option>)}
              </select>
            </label>
          </div>

          <label htmlFor="likedMost">
            What is working well?
            <textarea
              id="likedMost"
              value={form.likedMost}
              onChange={(event) => updateField("likedMost", event.target.value)}
              rows="4"
              placeholder="Reliability, support, installation, billing, speed, communication..."
            />
          </label>
          <label htmlFor="improvementFeedback">
            What should we improve?
            <textarea
              id="improvementFeedback"
              value={form.improvementFeedback}
              onChange={(event) => updateField("improvementFeedback", event.target.value)}
              rows="5"
              placeholder="Tell us what would make the service, support, or customer experience better."
            />
          </label>
          <label className="choice-row" htmlFor="contactPermission">
            <input
              id="contactPermission"
              type="checkbox"
              checked={form.contactPermission}
              onChange={(event) => updateCheckbox("contactPermission", event.target.checked)}
            />
            You may contact me about this response.
          </label>
          <button className="button" type="submit" disabled={busy}>Submit Survey</button>
          {status && <p className="notice">{status}</p>}
        </form>

        <aside className="feedback-aside">
          <h2>Need help right away?</h2>
          <p>This survey is reviewed by the team, but urgent service issues should still come through support so we can respond quickly.</p>
          <a className="button secondary-button" href="tel:14805821736">Call 480-582-1736</a>
          <a className="text-button" href={`mailto:${supportEmail}`}>{supportEmail}</a>
        </aside>
      </section>
    </div>
  );
}

const faqData = {
  General: [
    {
      question: "Where do you offer service?",
      answer: [
        "Our current active service neighborhoods include:",
        "Anthem at Merrill Ranch (Florence, AZ)",
        "Magic Ranch (Florence, AZ)",
        "Johnson Ranch (San Tan Valley, AZ)",
        "Copper Basin (San Tan Valley)",
        "Gilbert Road and Warner Road (Gilbert, AZ)",
      ],
    },
    {
      question: "What if you do not offer service in my neighborhood?",
      answer: [
        "Submit a request and we will use it to understand where demand is growing.",
        "Neighbor requests help us prioritize future expansion, so it also helps when nearby homes fill out the request form.",
      ],
    },
    {
      question: "What kinds of routers do you use?",
      answer: ["Residential Internet includes a MikroTik standard router. Customers can upgrade to a Pro Router for stronger WiFi hardware, and can add a whole-home extender when extra coverage is needed."],
    },
    {
      question: "Can I use my own router with Arizona Network?",
      answer: ["Yes. While we provide routers as a courtesy, most routers are compatible with our network. Our technician will confirm compatibility during installation."],
    },
    {
      question: "Can I use a VPN with Arizona Network internet?",
      answer: ["Yes. You can use personal and work-from-home VPNs with Arizona Network internet. The service is compatible with a wide range of VPN providers."],
    },
  ],
  Installation: [
    {
      question: "How long will it take to get service installed?",
      answer: ["Usually, we can get a technician out to your home within a week. The installation itself typically takes a few hours, depending on roof type, cabling, and signal conditions."],
    },
    {
      question: "What does the installation process involve?",
      answer: ["Our installation process is designed to be seamless and efficient. We use specialized roof mounts, place the antenna discreetly whenever possible, and route cabling carefully for reliable performance."],
    },
    {
      question: "Can I complete the installation myself?",
      answer: ["Leave installation to the professionals. Because our equipment and cabling are specialized, customer self-installation is not available."],
    },
  ],
  Billing: [
    {
      question: "What payment methods do you support?",
      answer: ["We currently accept debit and credit cards."],
    },
    {
      question: "Should I expect my monthly price to increase?",
      answer: [
        "We pride ourselves on transparent and fair pricing.",
        "As technology evolves, we may introduce faster service options that cost more, but we will never force you onto a new plan. You can always remain on your legacy service plan.",
      ],
    },
    {
      question: "What are the options for seasonal residents or snowbirds?",
      answer: [
        "We offer free service suspension, so you only pay for the months you use the service.",
        "We also offer a minimal service option for smart devices and security systems for $15/month while you are away.",
      ],
    },
  ],
  Technical: [
    {
      question: "Do your routers support wired connections?",
      answer: [
        "Yes. The standard router and Pro Router include Ethernet ports for wired devices.",
        "If you need more wired ports, the setup can be expanded by connecting an Ethernet switch.",
      ],
    },
  ],
};

function HelpPage() {
  const tabs = Object.keys(faqData);
  const [activeTab, setActiveTab] = useState("General");
  const [openQuestion, setOpenQuestion] = useState(faqData.General[0].question);

  function selectTab(tabName) {
    setActiveTab(tabName);
    setOpenQuestion(faqData[tabName][0].question);
  }

  return (
    <div className="help-page">
      <section className="help-hero" style={{ backgroundImage: `url(${media.helpBg})` }}>
        <h1>Still have questions? <span>Luckily, we have answers!</span></h1>
      </section>

      <section className="status-callout">
        <div className="status-callout-inner">
          <h2>Stay In the Know with Real-Time Network Status</h2>
          <p>Never wonder if there's an outage or maintenance in your neighborhood again. Our status page keeps you up to speed, 24/7.</p>
        <a className="button secondary-button" href="/status">View Network Status</a>
        </div>
      </section>

      <section className="faq-section">
        <h2>Frequently asked questions</h2>
        <div className="faq-tabs" role="tablist" aria-label="Categories">
          {tabs.map((tabName) => (
            <button
              key={tabName}
              className={activeTab === tabName ? "active" : ""}
              role="tab"
              aria-selected={activeTab === tabName}
              onClick={() => selectTab(tabName)}
            >
              {tabName}
            </button>
          ))}
        </div>
        <div className="faq-list" role="tabpanel" aria-label={activeTab}>
          {faqData[activeTab].map((item) => (
            <article key={item.question} className={openQuestion === item.question ? "open" : ""}>
              <button onClick={() => setOpenQuestion(openQuestion === item.question ? "" : item.question)}>
                <span>{item.question}</span>
                <span>{openQuestion === item.question ? "-" : "+"}</span>
              </button>
              {openQuestion === item.question && (
                <div className="faq-answer">
                  {item.answer.map((line) => <p key={line}>{line}</p>)}
                </div>
              )}
            </article>
          ))}
        </div>
      </section>
    </div>
  );
}

function NmdPage() {
  const sections = [
    {
      title: "Network Practices",
      items: [
        "Arizona Network does not manage an individual end user's capacity under normal use, but may manage the network when activity unreasonably impacts other customers.",
        "Reasonable network management may be used to protect against security threats, denial-of-service attacks, malicious code, spam, identity theft, or unlawful content.",
        "Arizona Network does not block lawful content, applications, services, or non-harmful devices, subject to reasonable network management.",
        "Customers are required to use a router. Customers may use an Arizona Network-provided router or an approved customer-owned router.",
      ],
    },
    {
      title: "Performance Characteristics",
      items: [
        "Residential and business service tiers may vary by speed, features, pricing, and availability.",
        "Advertised speeds are targets and may vary based on customer equipment, WiFi conditions, network usage, internet destinations, and factors outside Arizona Network's control.",
        "Latency is typically low enough for everyday use, but real-time applications such as gaming can be affected by network and internet conditions.",
      ],
    },
    {
      title: "Commercial Terms",
      items: [
        "Pricing and plan details are available on the plans page or by calling 480-582-1736.",
        "Customer personal information is governed by Arizona Network's privacy practices and may change from time to time.",
        "Questions, concerns, and written complaints can be directed to Arizona Network customer service.",
      ],
    },
  ];

  return (
    <DocumentPage eyebrow="Network Management Disclosure" title="Open Internet and Network Management Disclosure">
      <p>The Federal Communications Commission requires internet service providers to disclose information about network management practices, service performance, and commercial terms. This page explains how Arizona Network manages residential internet service in plain language.</p>
      {sections.map((section) => (
        <section key={section.title} className="document-section">
          <h2>{section.title}</h2>
          <ul>
            {section.items.map((item) => <li key={item}>{item}</li>)}
          </ul>
        </section>
      ))}
      <section className="document-section">
        <h2>Contact and Redress</h2>
        <p>For questions about service or this disclosure, contact Arizona Network at <a href={`mailto:${supportEmail}`}>{supportEmail}</a> or <a href="tel:14805821736">{supportPhone}</a>.</p>
      </section>
    </DocumentPage>
  );
}

function PartnerPage() {
  async function submitPartnerInterest(values) {
    const result = await apiPost("/api/partner-interest", {
      companyName: values["Company Name"],
      contactName: values["Company Contact Name"],
      contactEmail: values["Company Contact Email"],
      businessAddress: values["Business Address"],
      referrerName: values["Name of Referrer"],
      sourcePage: "/partner",
    });
    if (result.status === "failure") {
      throw new Error(result.message || "We could not submit that just now.");
    }
  }

  return (
    <LandingPage className="partner-page" heroImage={media.partnerBg} eyebrow="Business Partnership Program" title="Join our Business Partnership Program" subtitle="Apply today, or refer a local business that would be a good fit for Arizona Network.">
      <section className="split-section">
        <ContactForm
          title="Apply for the program"
          fields={["Company Name", "Company Contact Name", "Company Contact Email", "Business Address", "Name of Referrer"]}
          requiredFields={["Company Name", "Company Contact Email"]}
          buttonText="Submit Partnership Interest"
          successText="Thanks. We received your partnership interest, and the Arizona Network team can follow up from here."
          onSubmit={submitPartnerInterest}
        />
        <div className="copy-panel">
          <h2>Benefits the program offers your business</h2>
          <ul className="check-list">
            <li>Free 1 Gbps internet service and a high-performance router.</li>
            <li>Network planning help for employees and customers.</li>
            <li>Personable support from a team committed to resolving issues quickly.</li>
          </ul>
        </div>
      </section>
      <section className="three-up">
        <MiniStep title="Operate a high-traffic business" text="Restaurants, medical offices, salons, and similar local businesses are a natural fit." />
        <MiniStep title="Switch your internet provider" text="Approved partners receive complimentary service and installation." />
        <MiniStep title="Help spread the word" text="Allow small Arizona Network materials on premises, such as cards or signage." />
      </section>
      <section className="quote-band">
        <p>"Arizona Network is efficient, consistent, and reliable. That alone is 95% of what any business would want from a service provider."</p>
        <strong>Blaine, co-founder of Experience PT</strong>
      </section>
    </LandingPage>
  );
}

function CareersPage() {
  const bullets = [
    "Answer inbound calls, emails, and customer inquiries.",
    "Help customers choose the right internet plan and equipment.",
    "Support new customer sign-ups and installation scheduling.",
    "Troubleshoot basic service, account, and billing issues.",
    "Coordinate with technicians and installation teams.",
  ];

  return (
    <div className="careers-page">
      <section className="simple-hero">
        <p className="eyebrow">Careers</p>
        <h1>Join a local ISP team that cares about clear communication and good service.</h1>
      </section>
      <section className="job-card">
        <img src={media.careersDesk} alt="Working from home desk" />
        <div>
          <h2>Customer Support Specialist</h2>
          <p className="job-tags"><span>Phoenix, AZ</span><span>Full-time / Part-time</span><span>Hybrid</span></p>
          <p>Arizona Network is hiring a Customer Support and Sales Representative to help prospective and existing customers with plans, equipment, sign-ups, scheduling, and common service questions.</p>
          <h3>What you will do</h3>
          <ul>{bullets.map((bullet) => <li key={bullet}>{bullet}</li>)}</ul>
          <h3>What we are looking for</h3>
          <p>Customer service or inside sales experience, strong communication skills, attention to detail, and comfort with basic internet and WiFi concepts.</p>
          <p><strong>Compensation:</strong> $20-$28/hour depending on experience.</p>
          <a className="button" href={`mailto:${supportEmail}?subject=Customer%20Support%20Specialist%20Application`}>Apply by Email</a>
        </div>
      </section>
    </div>
  );
}

function HomelabPage() {
  const { openSignup } = useSignup();
  const features = [
    ["Public Static IPv4/IPv6 Address", "Run game servers, host websites, or access your home lab from anywhere without carrier-grade NAT workarounds.", media.homelabStatic],
    ["Symmetrical Speeds. Built for Real Services.", "Stream with Plex or Jellyfin, sync backups, and serve files without download-first limitations.", media.homelabSpeed],
    ["Bring Your Own Router", "Use the hardware you trust, from Ubiquiti UniFi to enterprise Cisco gear or your own custom setup.", media.homelabRouter],
    ["Low Latency, Even Under Load", "60 GHz last-mile links and controlled subscriber density help keep latency and jitter stable.", media.homelabLatency],
  ];

  return (
    <LandingPage className="homelab-page" heroImage={media.homelabHero} eyebrow="Advanced Features" title="Your Homelab Starts Here" subtitle="Run servers. Self-host everything. No blocked ports. No nonsense.">
      <section className="dark-feature-stack" style={{ backgroundImage: `url(${media.homelabBg})` }}>
        {features.map(([title, text, image]) => <ImageFeature key={title} title={title} text={text} image={image} />)}
      </section>
      <section className="signup-heading">
        <h2>Ready to upgrade your homelab?</h2>
        <button className="button" type="button" onClick={() => openSignup("Pro")}>Check Availability</button>
      </section>
      <PlanPreview />
    </LandingPage>
  );
}

function GilbertTrialPage() {
  const { openSignup } = useSignup();
  const trialPlan = "Standard";
  const [offerEmail, setOfferEmail] = useState("");
  const [offerMessage, setOfferMessage] = useState("");
  const [offerBusy, setOfferBusy] = useState(false);
  const trialBenefits = [
    ["Risk-Free for 30 Days", "Try Arizona Network with zero commitment. The first month is completely free."],
    ["No Upfront Costs", "Installation is included at no charge, and you will not pay anything until day 31."],
    ["Full-Speed Performance", "Use the service for work, streaming, and WiFi testing during your trial."],
    ["Cancel Anytime", "Stop before the 30-day mark and owe nothing."],
    ["Local Support", "Talk to friendly Arizona-based technicians who actually pick up the phone."],
  ];

  async function sendTrialOffer(event) {
    event.preventDefault();
    const email = offerEmail.trim();
    if (!email) {
      setOfferMessage("Enter your email and we will send the trial offer.");
      return;
    }

    let sessionValue = sessionStorage.getItem("sessionID");
    if (!sessionValue) {
      sessionValue = generateUUID();
      sessionStorage.setItem("sessionID", sessionValue);
    }

    setOfferBusy(true);
    setOfferMessage("Saving your trial offer...");
    try {
      const result = await apiPost("/api/website/send-offer", {
        sessionID: sessionValue,
        email,
        referralPage: trialReferralLink,
        referralCode: trialReferralCode,
      });
      await apiPost("/api/email/subscribe", { email, name: "" }).catch(() => {});
      setOfferEmail("");
      setOfferMessage(result.emailStatus === "sent" ? "Your discount code has been sent." : `Use code ${trialReferralCode} when you sign up.`);
    } catch (error) {
      setOfferMessage(error.message);
    } finally {
      setOfferBusy(false);
    }
  }

  return (
    <div className="trial-page">
      <section className="trial-hero">
        <h1>Try Arizona Network free for 30 days</h1>
        <p>No install fee. No charge for the first month. Pay only if you love the speed and reliability.</p>
        <strong>Limited number of free-trial spots available.</strong>
        <button className="button shadow" type="button" onClick={() => openSignup(trialPlan)}>Start Free Trial Sign-Up</button>
      </section>
      <section className="email-capture">
        <form className="contact-form" onSubmit={sendTrialOffer}>
          <h2>Not Quite Ready?</h2>
          <p>We can email you the 30-day free-trial offer so you can come back any time.</p>
          <label htmlFor="offerEmail">
            Email
            <input
              id="offerEmail"
              type="email"
              value={offerEmail}
              onChange={(event) => setOfferEmail(event.target.value)}
              placeholder="example@domain.com"
              autoComplete="email"
            />
          </label>
          <button className="button" type="submit" disabled={offerBusy}>Send Offer</button>
          {offerMessage && <p className="notice">{offerMessage}</p>}
        </form>
      </section>
      <PlanPreview />
      <section className="benefit-list">
        <h2>Why Try It?</h2>
        <div className="three-up">
          {trialBenefits.map(([title, text]) => <MiniStep key={title} title={title} text={text} />)}
        </div>
      </section>
      <section className="gallery-strip">
        <h2>Real Installations on Arizona Homes</h2>
        <img src={media.installSample} alt="Arizona Network installation sample" />
      </section>
      <section className="fine-print">
        <p className="eyebrow">Fine Print</p>
        <h2>Trial Terms</h2>
        <p>30-day free trial available for new residential customers only. A valid credit card is required before installation. Your card will not be charged during the trial period. If you cancel before day 30, you will owe nothing. If you continue service, billing begins automatically at the normal monthly rate on day 31.</p>
      </section>
      <InstallProcess />
    </div>
  );
}

function ReferralPage() {
  const benefits = [
    ["They get $100", "Your friend or family member gets a $100 account credit after their Arizona Network service is installed and active for 30 days."],
    ["You get $100", "You receive a $100 credit for each successful referral. The credit is applied directly to your Arizona Network account."],
    ["Five referrals can make internet free", "After 5 successful referrals, your monthly internet bill drops to $0. No gimmicks, no expiration, and no points system to decode."],
  ];
  const steps = [
    ["Step 1: Find your referral code", "Log in to your customer portal to copy your unique referral link or code. You can share it by text, email, group chat, or social media.", media.referralProgress],
    ["Step 2: They sign up with your link", "When someone uses your referral link, the sign-up is automatically connected to your account. Phone sign-ups can mention your name or referral code.", media.referralSignup],
    ["Step 3: Service gets installed", "We check availability, schedule installation, and get them connected. Once their service is active for 30 days, the referral qualifies.", media.referralCredit],
    ["Step 4: Credits are applied", "They get $100, you get $100, and every successful referral moves you closer to free internet for life.", media.referralFree],
  ];
  const rules = [
    "The referred customer must be new to Arizona Network and must sign up using your referral link, referral code, or your name.",
    "Referral credits apply after the referred service has been installed and active for 30 days.",
    "Credits are applied to Arizona Network accounts and are not paid out as cash.",
    "After 5 successful referrals, your monthly internet bill is reduced to $0 for life while your account remains active and in good standing.",
  ];

  return (
    <LandingPage className="referral-page" heroImage={media.referralBg} eyebrow="Referral Program" title="Refer 5, Free Internet For Life" subtitle="Give someone $100 toward Arizona Network service, earn $100 for yourself, and after 5 successful referrals your monthly internet bill drops to $0.">
      <section className="referral-program-intro">
        <div>
          <p className="eyebrow">Give $100. Get $100.</p>
          <h2>A referral program built for neighbors, friends, and family.</h2>
          <p>Arizona Network grows best when customers tell people they trust. The referral program keeps that simple: share your code, help someone get connected, and earn account credits when their service becomes active.</p>
        </div>
        <div className="referral-scorecard" aria-label="Referral reward summary">
          <strong>$100</strong>
          <span>credit for them</span>
          <strong>$100</strong>
          <span>credit for you</span>
          <strong>5</strong>
          <span>successful referrals for free internet for life</span>
        </div>
      </section>

      <section className="three-up referral-benefits" aria-label="Referral program benefits">
        {benefits.map(([title, text]) => <MiniStep key={title} title={title} text={text} />)}
      </section>

      <section className="step-images">
        {steps.map(([title, text, image]) => <ImageFeature key={title} title={title} text={text} image={image} />)}
      </section>

      <section className="referral-details">
        <div className="copy-panel">
          <p className="eyebrow">How to share</p>
          <h2>Use your customer portal, or just share your code.</h2>
          <p>Your referral link is the cleanest option because it attaches the referral automatically. If someone calls or signs up another way, they can still mention your name or referral code so the team can connect the account.</p>
          <a className="button" href="https://portal.arizonanetwork.com/" target="_blank" rel="noopener noreferrer">Open Customer Portal</a>
        </div>
        <div className="copy-panel">
          <p className="eyebrow">Program basics</p>
          <h2>Plain-language terms</h2>
          <ul className="check-list">
            {rules.map((rule) => <li key={rule}>{rule}</li>)}
          </ul>
        </div>
      </section>

      <section className="about-cta">
        <p>Ready to share or help someone get connected?</p>
        <div className="more-actions">
          <a className="button" href="https://portal.arizonanetwork.com/" target="_blank" rel="noopener noreferrer">Get My Referral Code</a>
          <a className="button secondary-button" href="/our-plans">View Internet Options</a>
        </div>
      </section>
    </LandingPage>
  );
}

function ResourcesPage() {
  const { openSignup } = useSignup();
  const featured = resourceArticles[0];
  const remaining = resourceArticles.slice(1);

  return (
    <div className="resources-page">
      <section className="resources-hero">
        <div>
          <p className="eyebrow">Internet Resource Center</p>
          <h1>Practical internet guides for Arizona homes.</h1>
          <p>Clear answers about fixed wireless internet, WiFi, installation, seasonal homes, speed, and advanced home networks.</p>
        </div>
      </section>

      {featured && (
        <section className="featured-resource" aria-label="Featured internet guide">
          <article>
            <p className="eyebrow">{featured.category}</p>
            <h2>{featured.h1}</h2>
            <p>{featured.summary}</p>
            <div className="resource-meta">
              <span>{featured.readTime}</span>
              <span>Updated {formatDisplayDate(featured.modified)}</span>
            </div>
            <a className="button" href={featured.path}>Read Guide</a>
          </article>
        </section>
      )}

      <section className="resource-grid" aria-label="Internet guides">
        {remaining.map((article) => <ResourceCard key={article.slug} article={article} />)}
      </section>

      <section className="resource-cta">
        <p className="eyebrow">Ready to compare service?</p>
        <h2>See whether Arizona Network is available at your address.</h2>
        <div className="more-actions">
          <button className="button" type="button" onClick={() => openSignup()}>Check Availability</button>
          <a className="button secondary-button" href="/help">Read FAQ</a>
        </div>
      </section>
    </div>
  );
}

function ResourceCard({ article }) {
  return (
    <article className="resource-card">
      <div>
        <p className="eyebrow">{article.category}</p>
        <h2>{article.h1}</h2>
        <p>{article.description}</p>
      </div>
      <div className="resource-card-footer">
        <span>{article.readTime}</span>
        <a href={article.path}>Read more</a>
      </div>
    </article>
  );
}

function ResourceArticlePage({ article }) {
  const { openSignup } = useSignup();
  const relatedArticles = resourceArticles
    .filter((item) => item.slug !== article.slug)
    .slice(0, 3);

  return (
    <div className="resource-article-page">
      <article className="resource-article">
        <header className="article-hero">
          <div className="article-hero-grid">
            <div className="article-hero-inner">
              <a className="article-back" href="/resources">Resources</a>
              <p className="eyebrow">{article.category}</p>
              <h1>{article.h1}</h1>
              <p>{article.summary}</p>
              <div className="article-meta">
                <span>{article.readTime}</span>
                <span>Published {formatDisplayDate(article.published)}</span>
                <span>Updated {formatDisplayDate(article.modified)}</span>
              </div>
            </div>
          </div>
        </header>

        <section className="article-layout">
          <aside className="article-sidebar" aria-label="Article summary">
            <h2>Quick Takeaways</h2>
            <ul>
              {article.takeaways.map((takeaway) => <li key={takeaway}>{takeaway}</li>)}
            </ul>
            <div className="sidebar-card">
              <h3>Need service?</h3>
              <p>Check availability and compare Arizona Network internet and router options for your address.</p>
              <button className="button" type="button" onClick={() => openSignup()}>Check Availability</button>
            </div>
          </aside>

          <div className="article-body">
            {article.sections.map((section) => (
              <section key={section.heading}>
                <h2>{section.heading}</h2>
                {section.paragraphs?.map((paragraph) => <p key={paragraph}>{paragraph}</p>)}
                {section.bullets && (
                  <ul>
                    {section.bullets.map((bullet) => <li key={bullet}>{bullet}</li>)}
                  </ul>
                )}
              </section>
            ))}

            <section className="article-faq">
              <h2>Frequently Asked Questions</h2>
              {article.faqs.map((faq) => (
                <article key={faq.question}>
                  <h3>{faq.question}</h3>
                  <p>{faq.answer}</p>
                </article>
              ))}
            </section>

            <section className="article-links">
              <h2>Next Steps</h2>
              <div className="more-actions">
                {article.relatedLinks.map((link) => (
                  <a
                    key={link.href}
                    className="button secondary-button"
                    href={link.href}
                    target={link.href.startsWith("http") ? "_blank" : undefined}
                    rel={link.href.startsWith("http") ? "noopener noreferrer" : undefined}
                  >
                    {link.label}
                  </a>
                ))}
              </div>
            </section>
          </div>
        </section>
      </article>

      <section className="related-resources">
        <p className="eyebrow">More internet guides</p>
        <h2>Keep learning</h2>
        <div className="resource-grid compact">
          {relatedArticles.map((item) => <ResourceCard key={item.slug} article={item} />)}
        </div>
      </section>
    </div>
  );
}

function formatDisplayDate(value) {
  return new Date(`${value}T00:00:00`).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

function LegalPage({ doc }) {
  return (
    <DocumentPage eyebrow={doc.eyebrow} title={doc.title}>
      <p>{doc.intro}</p>
      <p className="document-updated">Last updated May 18, 2026</p>
      {doc.sections.map((section) => (
        <section key={section.title} className="document-section">
          <h2>{section.title}</h2>
          {section.paragraphs.map((paragraph) => <p key={paragraph}>{paragraph}</p>)}
        </section>
      ))}
      <section className="document-section">
        <h2>Questions</h2>
        <p>For questions about these terms, contact Arizona Network at <a href={`mailto:${supportEmail}`}>{supportEmail}</a> or <a href="tel:14805821736">{supportPhone}</a>.</p>
      </section>
    </DocumentPage>
  );
}

function DocumentPage({ eyebrow, title, children }) {
  return (
    <div className="document-page">
      <section className="document-hero">
        <p className="eyebrow">{eyebrow}</p>
        <h1>{title}</h1>
      </section>
      <article className="document-body">{children}</article>
    </div>
  );
}

function LandingPage({ className, heroImage, eyebrow, title, subtitle, children }) {
  return (
    <div className={`landing-page ${className || ""}`}>
      <section className="landing-hero" style={{ backgroundImage: `url(${heroImage})` }}>
        <div>
          <p className="eyebrow">{eyebrow}</p>
          <h1>{title}</h1>
          <p>{subtitle}</p>
        </div>
      </section>
      {children}
    </div>
  );
}

function ContactForm({ title, intro, fields, requiredFields = [], buttonText, successText, onSubmit }) {
  const [message, setMessage] = useState("");
  const [busy, setBusy] = useState(false);
  const [values, setValues] = useState(() => Object.fromEntries(fields.map((field) => [field, ""])));
  const fieldId = (field) => field.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");

  function updateField(field, value) {
    setValues((current) => ({ ...current, [field]: value }));
  }

  async function handleSubmit(event) {
    event.preventDefault();
    if (!onSubmit) {
      setMessage(successText);
      return;
    }

    setBusy(true);
    setMessage("");
    try {
      await onSubmit(values);
      setValues(Object.fromEntries(fields.map((field) => [field, ""])));
      setMessage(successText);
    } catch (error) {
      setMessage(error.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <form className="contact-form" onSubmit={handleSubmit}>
      <h2>{title}</h2>
      {intro && <p>{intro}</p>}
      {fields.map((field) => (
        <label key={field} htmlFor={fieldId(field)}>
          {field}
          <input
            id={fieldId(field)}
            name={fieldId(field)}
            type={field.toLowerCase().includes("email") ? "email" : "text"}
            autoComplete={field.toLowerCase().includes("email") ? "email" : "on"}
            placeholder={field === "Email" ? "example@domain.com" : ""}
            required={requiredFields.includes(field)}
            value={values[field] || ""}
            onChange={(event) => updateField(field, event.target.value)}
          />
        </label>
      ))}
      <button className="button" type="submit" disabled={busy}>{busy ? "Submitting..." : buttonText}</button>
      {message && <p className="notice">{message}</p>}
    </form>
  );
}

function ImageFeature({ title, text, image }) {
  return (
    <article className="image-feature">
      <div>
        <h2>{title}</h2>
        <p>{text}</p>
      </div>
      <img src={image} alt={title} />
    </article>
  );
}

function PlanPreview() {
  return (
    <section className="plan-card-section preview-plans">
      <ResidentialInternetCard buttonHref="/our-plans" buttonLabel="View Internet Options" />
      <div className="router-choice-heading compact-heading">
        <p className="eyebrow">Router Options</p>
        <h2>Choose standard WiFi or upgrade the router for larger homes.</h2>
      </div>
      <div className="plan-cards router-plan-cards">
        {plans.map((plan) => <PlanCard key={plan.name} plan={plan} basePrice={plans[0].price} selected={false} buttonHref="/our-plans" buttonLabel="View Router Options" />)}
      </div>
    </section>
  );
}

function ReviewCard({ review }) {
  return (
    <article className="review-tile">
      <p className="review-theme">{review.theme}</p>
      <p className="review-quote">"{review.quote}"</p>
      <div className="review-meta">
        <div>
          <strong>-- {review.name}</strong>
          <span>{review.since}</span>
        </div>
      </div>
    </article>
  );
}

function ResidentialInternetCard({ onChoose, buttonHref, buttonLabel }) {
  const { openSignup } = useSignup();
  const action = onChoose || ((event) => {
    event.preventDefault();
    openSignup("Standard");
  });

  return (
    <article className="residential-plan-card">
      <div>
        <p className="plan-kicker">Residential Internet</p>
        <h2>Up to 1 Gbps home internet service</h2>
        <p>Unlimited data, no long-term contract, local support, and professional fixed-wireless installation.</p>
      </div>
      <div className="residential-price">
        <span>Starts at</span>
        <strong>${plans[0].price.toFixed(2)}</strong>
        <small>/month before fees</small>
      </div>
      {buttonHref ? (
        <a className="plan-action" href={buttonHref}>{buttonLabel || "View Internet Options"}</a>
      ) : (
        <button type="button" onClick={action}>Check Availability</button>
      )}
    </article>
  );
}

function PlanCard({ plan, basePrice, selected, onChoose, buttonHref, buttonLabel }) {
  const { openSignup } = useSignup();
  const upgrade = routerUpgradeAmount(plan, basePrice);
  const routerName = routerDisplayName(plan.name);

  function openPlanSignup(event) {
    event.preventDefault();
    openSignup(plan.name);
  }

  return (
    <article className={`plan-card ${selected ? "selected" : ""}`}>
      <p className="plan-kicker">{plan.kicker}</p>
      <h2>{routerName}</h2>
      <a className="plan-price" href="/signup" onClick={openPlanSignup}>{upgrade > 0 ? `+$${upgrade.toFixed(2)}` : "Included"}</a>
      <p className="up-to">{upgrade > 0 ? "per month router upgrade" : "with Residential Internet"}</p>
      <strong>{plan.name === "Pro" ? "Expanded WiFi" : "Everyday WiFi"}</strong>
      <img src={plan.router} alt={routerName} />
      <ul>
        {plan.bullets.map((bullet) => <li key={bullet}>{bullet}</li>)}
      </ul>
      {buttonHref ? (
        <a className="plan-action" href={buttonHref}>{buttonLabel || "View Internet Options"}</a>
      ) : (
        <button onClick={onChoose}>{selected ? "Selected" : "Choose Router"}</button>
      )}
    </article>
  );
}

function useSignup() {
  return useContext(SignupContext);
}

function SignupCta({ eyebrow = "Ready to sign up?", title = "Check availability and schedule installation in one guided flow.", selectedPlan, monthly, installFee, onOpen }) {
  const { openSignup } = useSignup();
  const action = onOpen || (() => openSignup(selectedPlan));

  return (
    <section className="signup-cta" id="signup">
      <div>
        <p className="eyebrow">{eyebrow}</p>
        <h2>{title}</h2>
        {monthly && (
          <p>
            Residential Internet with {selectedPlan || "your selected router"} is estimated at ${monthly.toFixed(2)}/month. Installation is ${installFee.toFixed(2)}.
          </p>
        )}
      </div>
      <button className="button shadow" type="button" onClick={action}>Start Sign-Up</button>
    </section>
  );
}

function SignupPanel({ selectedPlan = "Standard", setSelectedPlan, titleId, initialStep, modal = false, onServiceable }) {
  const { openSignup } = useSignup();
  const preferredPlan = localStorage.getItem("aznPreferredPlan") || selectedPlan;
  const defaultPlan = plans.find((plan) => plan.name === preferredPlan) || plans[0];
  const savedStep = typeof initialStep === "number" ? initialStep : Number(localStorage.getItem("aznCurrentStep") || 0);
  const [step, setStep] = useState([0, 1, 2, 3, 4].includes(savedStep) ? savedStep : 0);
  const [notice, setNotice] = useState("");
  const [busy, setBusy] = useState(false);
  const [completionType, setCompletionType] = useState(() => localStorage.getItem("aznCompletionType") || "");
  const [appointmentOptions, setAppointmentOptions] = useState([]);
  const [appointmentStatus, setAppointmentStatus] = useState("");
  const [appointmentsLoaded, setAppointmentsLoaded] = useState(false);
  const [appointmentDate, setAppointmentDate] = useState(() => localStorage.getItem("appointmentDate") || formatDateInputValue());
  const [broadbandLabelOpen, setBroadbandLabelOpen] = useState(false);
  const [referralStatus, setReferralStatus] = useState("");
  const [referralBusy, setReferralBusy] = useState(false);
  const [referralDiscount, setReferralDiscount] = useState(null);
  const [placesReady, setPlacesReady] = useState(false);
  const [browserID, setBrowserID] = useState("");
  const [sessionID, setSessionID] = useState("");
  const [planOptions, setPlanOptions] = useState(readStoredPlanOptions);
  const [form, setForm] = useState(() => ({
    addressText: localStorage.getItem("addressFormatted") || "",
    address: JSON.parse(localStorage.getItem("aznAddress") || "null"),
    speedPlan: localStorage.getItem("speedPlan") || defaultPlan.value,
    firstName: localStorage.getItem("firstName") || "",
    lastName: localStorage.getItem("lastName") || "",
    email: localStorage.getItem("email") || "",
    phone: localStorage.getItem("phone") || "",
    referralCode: localStorage.getItem("referralCode") || "",
    routerOption: localStorage.getItem("routerOption") || routerOptions[0].value,
    cardName: "",
    cardNumber: "",
    cardExpiry: "",
    cardCvc: "",
    appointmentTime: localStorage.getItem("appointmentTime") || "",
    appointmentInstaller: localStorage.getItem("appointmentInstaller") || "",
    manualName: "",
    manualPhone: "",
    manualEmail: "",
  }));
  const addressInputRef = useRef(null);
  const referralValidationRef = useRef("");

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const referralCode = params.get("referralCode");
    if (referralCode) {
      localStorage.setItem("referralCode", referralCode);
      setForm((current) => ({ ...current, referralCode }));
    }

    let browser = localStorage.getItem("userID");
    if (!browser) {
      browser = generateUUID();
      localStorage.setItem("userID", browser);
      apiPost("/api/website/create-user", { browserID: browser, userAgent: navigator.userAgent }).catch(() => {});
    }

    let sessionValue = sessionStorage.getItem("sessionID");
    if (!sessionValue) {
      sessionValue = generateUUID();
      sessionStorage.setItem("sessionID", sessionValue);
      apiPost("/api/website/create-session", { browserID: browser, sessionID: sessionValue }).catch(() => {});
    }

    setBrowserID(browser);
    setSessionID(sessionValue);
  }, []);

  useEffect(() => {
    let listener;
    loadGooglePlaces()
      .then((ready) => {
        setPlacesReady(ready);
        if (!ready || !addressInputRef.current) return;
        const autocomplete = new google.maps.places.Autocomplete(addressInputRef.current, {
          componentRestrictions: { country: "us" },
          fields: ["address_components", "formatted_address", "geometry", "name"],
          types: ["address"],
        });
        listener = autocomplete.addListener("place_changed", () => {
          const place = autocomplete.getPlace();
          const address = normalizePlace(place);
          if (!address) {
            setNotice("Choose a full address from the suggestions so we can check serviceability.");
            return;
          }
          saveAddress(address);
          setNotice("");
        });
      })
      .catch(() => setPlacesReady(false));

    return () => {
      if (listener?.remove) listener.remove();
    };
  }, []);

  useEffect(() => {
    if (!modal) {
      localStorage.setItem("aznCurrentStep", String(step));
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
    if (step > 0 && sessionID) {
      apiPost("/api/website/log-info", { sessionID, info: collectInfo() }).catch(() => {});
    }
  }, [step, sessionID, modal]);

  useEffect(() => {
    if (step === 4 && !appointmentsLoaded) {
      loadAppointmentOptions(appointmentDate);
    }
  }, [step, appointmentsLoaded, appointmentDate]);

  useEffect(() => {
    const code = normalizeSignupCode(form.referralCode);
    if (!code) {
      referralValidationRef.current = "";
      setReferralDiscount(null);
      setReferralStatus("");
      return undefined;
    }
    const validationKey = `${code}:${form.speedPlan}`;
    if (step !== 4 || referralValidationRef.current === validationKey) return undefined;
    const timer = window.setTimeout(() => {
      validateReferralCode({ quiet: true });
    }, 350);
    return () => window.clearTimeout(timer);
  }, [step, form.referralCode, form.speedPlan]);

  useEffect(() => {
    if (!broadbandLabelOpen) return undefined;
    function closeOnEscape(event) {
      if (event.key === "Escape") setBroadbandLabelOpen(false);
    }

    document.body.classList.add("signup-modal-open");
    document.addEventListener("keydown", closeOnEscape);
    return () => {
      document.body.classList.remove("signup-modal-open");
      document.removeEventListener("keydown", closeOnEscape);
    };
  }, [broadbandLabelOpen]);

  function normalizePlace(place) {
    const location = place?.geometry?.location;
    if (!place?.formatted_address || !location) return null;
    const getPart = (type, useShort = false) => {
      const part = place.address_components?.find((component) => component.types.includes(type));
      return part ? (useShort ? part.short_name : part.long_name) : "";
    };
    return {
      formatted: place.formatted_address,
      streetNumber: getPart("street_number"),
      streetName: getPart("route"),
      city: getPart("locality") || getPart("sublocality") || getPart("administrative_area_level_2"),
      state: getPart("administrative_area_level_1", true),
      postalCode: getPart("postal_code"),
      location: {
        latitude: location.lat(),
        longitude: location.lng(),
      },
    };
  }

  function saveAddress(address) {
    localStorage.setItem("addressFormatted", address.formatted);
    localStorage.setItem("aznAddress", JSON.stringify(address));
    localStorage.setItem("lat", address.location.latitude);
    localStorage.setItem("lng", address.location.longitude);
    setForm((current) => ({ ...current, address, addressText: address.formatted }));
  }

  function updateForm(field, value) {
    setForm((current) => ({ ...current, [field]: value }));
    if (["speedPlan", "firstName", "lastName", "email", "phone", "referralCode", "routerOption"].includes(field)) {
      localStorage.setItem(field, value);
    }
    if (field === "referralCode" || field === "speedPlan") {
      referralValidationRef.current = "";
      setReferralDiscount(null);
      setReferralStatus("");
    }
  }

  async function validateReferralCode({ quiet = false } = {}) {
    const referralCode = normalizeSignupCode(form.referralCode);
    if (!referralCode) {
      referralValidationRef.current = "";
      setReferralDiscount(null);
      setReferralStatus("");
      return null;
    }

    const validationKey = `${referralCode}:${form.speedPlan}`;
    setReferralBusy(true);
    if (!quiet) setReferralStatus("Checking code...");
    try {
      const result = await apiPost("/api/signup/referral-code", {
        referralCode,
        speedPlan: form.speedPlan,
      });
      referralValidationRef.current = validationKey;
      if (!result.valid || !result.discount) {
        setReferralDiscount(null);
        setReferralStatus(result.message || "That code was not found.");
        return null;
      }
      setReferralDiscount(result.discount);
      setReferralStatus(`${result.discount.label || "Discount"} applied.`);
      return result.discount;
    } catch (error) {
      referralValidationRef.current = "";
      setReferralDiscount(null);
      setReferralStatus(error.message || "Code could not be checked.");
      return null;
    } finally {
      setReferralBusy(false);
    }
  }

  function choosePlan(plan) {
    updateForm("speedPlan", plan.value);
    setSelectedPlan?.(plan.name);
    localStorage.setItem("aznPreferredPlan", plan.name);
  }

  function selectedAppointmentSnapshot() {
    return form.appointmentTime && !isPastAppointmentTime(form.appointmentTime) ? {
      time: form.appointmentTime,
      installer: form.appointmentInstaller,
    } : null;
  }

  function collectInfo() {
    const selectedPlanOption = planOptions.find((item) => item.value === form.speedPlan) || planOptions[0];
    const address = form.address || {};
    const selectedAppointment = selectedAppointmentSnapshot();
    return {
      firstName: form.firstName,
      lastName: form.lastName,
      phoneNumber: form.phone,
      emailAddress: form.email,
      addressOne: [address.streetNumber, address.streetName].filter(Boolean).join(" ") || form.addressText,
      addressTwo: "",
      city: address.city || "",
      state: address.state || "",
      zip: address.postalCode || "",
      mapMarker: {
        lat: address.location?.latitude || "",
        lng: address.location?.longitude || "",
      },
      speedPlan: selectedPlanOption?.value || form.speedPlan,
      router: form.routerOption || routerOptions[0].value,
      installAppointment: {
        installer: "",
        time: "",
      },
      customerStatus: 3,
      oneTimeDiscount: "",
      specialNotes: "Customer completed checkout flow. Arizona Network can confirm or adjust the installation appointment as needed.",
      referralCode: form.referralCode || "",
    };
  }

  async function findSoonestAppointment(dateValue = appointmentDate) {
    const result = await apiPost("/api/signup/appts", { soonestDate: formatDateForAppointmentApi(dateValue) });
    const appointment = Array.isArray(result.data)
      ? result.data.find((item) => !isPastAppointmentTime(item.time))
      : null;
    if (!appointment) return null;
    const snapshot = {
      time: appointment.time,
      installer: appointment.installer_group || "",
    };
    chooseAppointment(snapshot);
    return snapshot;
  }

  function chooseAppointment(appointment) {
    const snapshot = {
      time: appointment.time,
      installer: appointment.installer || appointment.installer_group || "",
    };
    localStorage.setItem("appointmentTime", snapshot.time);
    localStorage.setItem("appointmentInstaller", snapshot.installer);
    setForm((current) => ({
      ...current,
      appointmentTime: snapshot.time,
      appointmentInstaller: snapshot.installer,
    }));
  }

  function updateAppointmentDate(value) {
    const nextDate = value || formatDateInputValue();
    localStorage.setItem("appointmentDate", nextDate);
    localStorage.removeItem("appointmentTime");
    localStorage.removeItem("appointmentInstaller");
    setAppointmentDate(nextDate);
    setAppointmentOptions([]);
    setAppointmentsLoaded(false);
    setAppointmentStatus("Loading available install times...");
    setForm((current) => ({
      ...current,
      appointmentTime: "",
      appointmentInstaller: "",
    }));
  }

  function openDatePicker(event) {
    if (typeof event.currentTarget.showPicker === "function") {
      try {
        event.currentTarget.showPicker();
      } catch (error) {
        // Some browsers open the native picker automatically on click.
      }
    }
  }

  async function loadAppointmentOptions(dateValue = appointmentDate) {
    setAppointmentStatus("Loading available install times...");
    try {
      const result = await apiPost("/api/signup/appts", { soonestDate: formatDateForAppointmentApi(dateValue) });
      const available = Array.isArray(result.data)
        ? result.data.filter((item) => !isPastAppointmentTime(item.time))
        : [];
      setAppointmentOptions(available);
      setAppointmentsLoaded(true);
      if (!available.length) {
        setAppointmentStatus("No online install times are available right now. We can confirm timing after checkout.");
        return;
      }
      setAppointmentStatus("");
      if (!selectedAppointmentSnapshot()) chooseAppointment(available[0]);
    } catch (error) {
      setAppointmentsLoaded(true);
      setAppointmentStatus("Install times could not be loaded right now. We can confirm scheduling after checkout.");
    }
  }

  async function checkService(event) {
    event.preventDefault();
    if (!form.address?.location) {
      setNotice(placesReady ? "Select your address from the suggestions before checking availability." : "Address lookup is taking longer than expected. Send it for review and we will check it manually.");
      return;
    }

    setBusy(true);
    setNotice("Checking service availability...");
    try {
      const result = await apiPost("/api/signup/address-check", { address: form.address, sessionID });
      if (result.status === "success") {
        const remotePlans = Array.isArray(result.plans) ? result.plans.map(([id, name, price]) => ({
          value: String(id),
          label: routerDisplayName(name),
          name: routerPlanKey(name),
          routerName: routerDisplayName(name),
          price: Number(price),
        })).sort((left, right) => left.price - right.price) : planOptions;
        const currentPlan = planOptions.find((plan) => plan.value === form.speedPlan)?.name;
        const matchingRemotePlan = remotePlans.find((plan) => plan.name === currentPlan) || remotePlans[0];
        setPlanOptions(remotePlans);
        updateForm("speedPlan", matchingRemotePlan?.value || form.speedPlan);
        setSelectedPlan?.(matchingRemotePlan?.name || currentPlan || defaultPlan.name);
        localStorage.setItem("aznPlanOptions", JSON.stringify(remotePlans));
        localStorage.setItem("serviceable", "true");
        localStorage.setItem("aznCurrentStep", "1");
        setNotice("");
        if (onServiceable) {
          onServiceable();
        } else {
          setStep(1);
        }
      } else {
        localStorage.setItem("serviceable", "false");
        setNotice("That address needs a review before sign-up.");
        setStep(3);
      }
    } catch (error) {
      setNotice(error.message);
    } finally {
      setBusy(false);
    }
  }

  function parseExpiry(value) {
    const digits = String(value || "").replace(/\D/g, "");
    if (digits.length !== 4 && digits.length !== 6) return "";
    const month = digits.slice(0, 2);
    const year = digits.length === 4 ? `20${digits.slice(2)}` : digits.slice(2);
    return `${month}/01/${year}`;
  }

  function collectPayment() {
    return {
      cardHolder: form.cardName || `${form.firstName} ${form.lastName}`.trim(),
      cardNumber: form.cardNumber.replace(/\D/g, ""),
      expirationDate: parseExpiry(form.cardExpiry),
    };
  }

  function collectAgreements() {
    return {
      serviceTerms: true,
      broadbandLabel: true,
      autopay: true,
      electronicNotices: true,
      transactionalMessages: true,
      marketingMessages: false,
    };
  }

  async function submitSignup(event) {
    event.preventDefault();
    if (!form.email || !form.firstName || !form.lastName || !form.phone) {
      setNotice("Enter your contact information to place the order.");
      return;
    }
    if (!luhnValid(form.cardNumber)) {
      setNotice("Enter a valid credit or debit card number.");
      return;
    }
    if (!parseExpiry(form.cardExpiry)) {
      setNotice("Enter the card expiration as MM/YY.");
      return;
    }
    if (!form.cardCvc) {
      setNotice("Enter the card security code.");
      return;
    }

    setBusy(true);
    setNotice("Placing your order...");
    try {
      let appointment = selectedAppointmentSnapshot();
      if (!appointment) appointment = await findSoonestAppointment();
      if (!appointment) {
        setNotice("We could not find an installation appointment to hold. Please call us and we will finish the order.");
        return;
      }
      const result = await apiPost("/api/signup/submit", {
        info: collectInfo(),
        payment: collectPayment(),
        agreements: collectAgreements(),
        userID: browserID,
        sessionID,
      });
      if (result.status === "failure") {
        setNotice(result.message || "Sign-up could not be completed.");
        return;
      }
      const keepBrowserID = browserID;
      localStorage.clear();
      localStorage.setItem("userID", keepBrowserID);
      localStorage.setItem("aznCurrentStep", "2");
      localStorage.setItem("aznCompletionType", "order");
      setCompletionType("order");
      setStep(2);
      setNotice("Success. Your order has been placed.");
    } catch (error) {
      setNotice(error.message);
    } finally {
      setBusy(false);
    }
  }

  async function submitManualReview(event) {
    event.preventDefault();
    const name = form.manualName || `${form.firstName} ${form.lastName}`.trim();
    const phone = form.manualPhone || form.phone;
    const email = form.manualEmail || form.email;
    const address = form.addressText || form.address?.formatted;
    if (!name || !phone || !email || !address) {
      setNotice("Complete name, phone, email, and address so we can review service availability.");
      return;
    }

    setBusy(true);
    try {
      const result = await apiPost("/api/signup/manual-review", {
        info: {
          name,
          phone,
          email,
          address,
          org: 1,
          coverageStatus: "Needs manual review",
          sourcePage: window.location.pathname || "/",
          sessionID,
          browserID,
          referralCode: form.referralCode || "",
        },
      });
      setNotice(result.status === "failure" ? "We received your address review request, but could not confirm the final status. We will follow up if we need anything else." : "Thanks. Your address was submitted for review.");
      localStorage.setItem("aznCurrentStep", "2");
      localStorage.setItem("aznCompletionType", "review");
      setCompletionType("review");
      setStep(2);
    } catch (error) {
      setNotice(error.message);
    } finally {
      setBusy(false);
    }
  }

  function resetSignup() {
    const keepBrowserID = localStorage.getItem("userID");
    localStorage.clear();
    if (keepBrowserID) localStorage.setItem("userID", keepBrowserID);
    setForm((current) => ({
      ...current,
      addressText: "",
      address: null,
      speedPlan: defaultPlan.value,
      firstName: "",
      lastName: "",
      email: "",
      phone: "",
      referralCode: "",
      routerOption: routerOptions[0].value,
      cardName: "",
      cardNumber: "",
      cardExpiry: "",
      cardCvc: "",
      appointmentTime: "",
      appointmentInstaller: "",
      manualName: "",
      manualPhone: "",
      manualEmail: "",
    }));
    setPlanOptions(defaultPlanOptions());
    setAppointmentOptions([]);
    setAppointmentStatus("");
    setAppointmentsLoaded(false);
    setAppointmentDate(formatDateInputValue());
    referralValidationRef.current = "";
    setReferralStatus("");
    setReferralDiscount(null);
    setCompletionType("");
    setNotice("");
    setStep(0);
  }

  const selectedPlanOption = planOptions.find((item) => item.value === form.speedPlan) || planOptions[0];
  const availablePlanPrices = planOptions.map((plan) => Number(plan.price || 0)).filter((price) => Number.isFinite(price) && price > 0);
  const internetBase = availablePlanPrices.length ? Math.min(...availablePlanPrices) : plans[0].price;
  const routerUpgrade = routerUpgradeAmount(selectedPlanOption, internetBase);
  const selectedRouterName = selectedPlanOption?.routerName || routerDisplayName(selectedPlanOption?.name);
  const monthlyBase = selectedPlanOption?.price || defaultPlan.price;
  const selectedExtenderOption = routerOptions.find((option) => option.value === form.routerOption) || routerOptions[0];
  const extenderMonthly = Number(selectedExtenderOption.price || 0);
  const regulatory = Number((monthlyBase * 0.03).toFixed(2));
  const monthly = monthlyBase + extenderMonthly + regulatory;
  const installFee = 74;
  const appliedReferralDiscount = referralDiscount && normalizeSignupCode(referralDiscount.code) === normalizeSignupCode(form.referralCode)
    ? referralDiscount
    : null;
  const installDiscount = Number(appliedReferralDiscount?.oneTime || 0);
  const totalDueUponInstall = Math.max(0, monthly + installFee - installDiscount);
  const hasServiceAddress = Boolean(form.addressText && form.address?.location);
  const isServiceable = localStorage.getItem("serviceable") === "true";
  const appointmentDateChanged = appointmentDate !== formatDateInputValue();
  const selectedLocalRouterPlan = plans.find((plan) => plan.name === selectedPlanOption?.name) || plans[0];
  const broadbandPlanIdentifier = `AZN-RES-1G-${routerPlanKey(selectedLocalRouterPlan.name).toUpperCase()}${extenderMonthly > 0 ? "-EXT" : ""}`;
  const selectedRouterDescription = selectedLocalRouterPlan.name === "Pro"
    ? "Pro Router is built for larger homes, heavier streaming or gaming, more connected devices, or rooms that need stronger WiFi coverage."
    : "Standard Router fits smaller homes, apartments, and everyday internet use with fewer devices and shorter distances between rooms.";
  const selectedRouterBullets = selectedLocalRouterPlan.name === "Pro"
    ? ["Best for larger layouts", "Stronger WiFi hardware", "Good fit for busier households"]
    : ["Included with Residential Internet", "Best for smaller homes", "Good fit for everyday browsing and streaming"];

  return (
    <section className={`signup-flow step-${step}`}>
      {step === 0 && (
        <div className="service-selection">
          <div className="signup-flow-heading">
            <p className="eyebrow">Service check</p>
            <h1 id={titleId}>Check availability at your address.</h1>
            <p>Enter your install address. Covered homes continue to plan options and checkout.</p>
          </div>
          <form className="service-selection-form" onSubmit={checkService}>
            <div className="checkout-address-block">
              <label htmlFor="address">Where will you use Arizona Network?</label>
              <div className="checkout-address-field">
                <input
                  ref={addressInputRef}
                  id="address"
                  name="address"
                  value={form.addressText}
                  onChange={(event) => setForm((current) => ({ ...current, addressText: event.target.value, address: null }))}
                  placeholder={placesReady ? "Start typing your service address" : "Google address autocomplete is loading"}
                  autoComplete="street-address"
                />
              </div>
              <button className="text-button" type="button" onClick={() => setStep(3)}>
                I cannot find my address
              </button>
            </div>

            {notice && <p className="notice">{notice}</p>}
            <div className="signup-flow-actions">
              <button type="submit" disabled={busy}>{busy ? "Checking..." : "Check Availability"}</button>
            </div>
          </form>
        </div>
      )}

      {step === 1 && (
        (!hasServiceAddress || !isServiceable) ? (
          <div className="checkout-success">
            <p className="eyebrow">Service check required</p>
            <h1 id={titleId}>Check your address before ordering.</h1>
            <p>We will confirm that your home is covered, then bring you back here to choose plan options and checkout.</p>
            <button type="button" onClick={() => openSignup(selectedPlanOption?.name || selectedPlan)}>Check Availability</button>
          </div>
        ) : (
          <div className="plan-options-step">
            <div className="signup-flow-heading">
              <p className="eyebrow">Select plan options</p>
              <h1 id={titleId}>Choose your router option.</h1>
              <p>Start with Residential Internet, then pick the WiFi hardware that best fits your home.</p>
            </div>

            <section className="internet-service-card" aria-labelledby="internetServiceTitle">
              <div>
                <p className="eyebrow">Residential Internet</p>
                <h2 id="internetServiceTitle">Up to 1 Gbps home internet</h2>
                <p>Unlimited data, local support, no long-term contract, and professional fixed-wireless installation.</p>
                <div className="service-highlights" aria-label="Residential Internet highlights">
                  <span>Up to 1 Gbps</span>
                  <span>Unlimited data</span>
                  <span>No contracts</span>
                </div>
              </div>
              <div className="internet-service-price">
                <span>Starts at</span>
                <strong>${internetBase.toFixed(0)}/mo</strong>
                <small>before fees and upgrades</small>
              </div>
            </section>

            <section className="shipping-address" aria-labelledby="planAddressTitle">
              <div>
                <h2 id="planAddressTitle">Service Address</h2>
                <button type="button" onClick={() => openSignup(selectedPlanOption?.name || selectedPlan)}>Change</button>
              </div>
              <p>{form.addressText}</p>
            </section>

            <section className="router-choice-panel" aria-labelledby="routerChoiceTitle">
              <div className="option-section-heading">
                <p className="eyebrow">Router</p>
                <h2 id="routerChoiceTitle">Choose included WiFi or upgraded coverage.</h2>
                <p>Compare the included WiFi hardware with the Pro upgrade, then add extra coverage if your home needs it.</p>
              </div>

              <div className="router-tab-list" role="tablist" aria-label="Router option">
                {planOptions.map((option) => {
                  const selected = form.speedPlan === option.value;
                  const routerUpgradeLabel = routerUpgradeAmount(option, internetBase) > 0 ? `+$${routerUpgradeAmount(option, internetBase).toFixed(2)}/mo` : "Included";
                  return (
                    <button
                      className={`router-tab ${selected ? "selected" : ""}`}
                      key={option.value}
                      type="button"
                      role="tab"
                      aria-selected={selected}
                      onClick={() => choosePlan(option)}
                    >
                      <span>{option.routerName || routerDisplayName(option.name)}</span>
                      <strong>{routerUpgradeLabel}</strong>
                    </button>
                  );
                })}
              </div>

              <div className="router-tab-panel" role="tabpanel">
                <div>
                  <span className="selected-choice-badge">Selected router</span>
                  <h3>{selectedRouterName}</h3>
                  <p>{selectedRouterDescription}</p>
                  <ul>
                    {selectedRouterBullets.map((bullet) => <li key={bullet}>{bullet}</li>)}
                  </ul>
                </div>
                <button
                  className={`router-extender-toggle ${extenderMonthly > 0 ? "selected" : ""}`}
                  type="button"
                  aria-pressed={extenderMonthly > 0}
                  onClick={() => updateForm("routerOption", extenderMonthly > 0 ? routerOptions[0].value : routerOptions[1].value)}
                >
                  <span>{extenderMonthly > 0 ? "Remove extender" : "Add Whole Home WiFi Extender"}</span>
                  <strong>+${routerOptions[1].price.toFixed(2)}/mo</strong>
                  <small>Optional add-on for larger homes, thick walls, or rooms farther from the main router.</small>
                </button>
              </div>
            </section>

            {notice && <p className="notice">{notice}</p>}
            <div className="signup-flow-actions">
              <button className="secondary-button" type="button" onClick={() => openSignup(selectedPlanOption?.name || selectedPlan)}>Change Address</button>
              <button type="button" onClick={() => setStep(4)}>Continue to Checkout</button>
            </div>
          </div>
        )
      )}

      {step === 4 && (
        <div className="checkout-layout">
          <form className="checkout-card" onSubmit={submitSignup}>
            <button className="checkout-back" type="button" onClick={() => setStep(1)} aria-label="Back to plan options">
              <span aria-hidden="true">‹</span>
              <span>Plan options</span>
            </button>
            <div className="checkout-head">
              <h1 id={titleId}>Checkout</h1>
            </div>

            <section className="checkout-service-review" aria-labelledby="checkoutServiceTitle">
              <div>
                <p className="eyebrow">Selected service</p>
                <h2 id="checkoutServiceTitle">Residential Internet</h2>
                <p>Up to 1 Gbps home internet with unlimited data, local support, and no long-term contract.</p>
              </div>
              <div className="checkout-service-details">
                <span>Base service: ${internetBase.toFixed(2)}/mo</span>
                <span>{selectedRouterName}: {routerUpgrade > 0 ? `+$${routerUpgrade.toFixed(2)}/mo` : "included"}</span>
                <span>{extenderMonthly > 0 ? `${selectedExtenderOption.label}: +$${extenderMonthly.toFixed(2)}/mo` : "No WiFi extender added"}</span>
              </div>
            </section>
            <button className="broadband-label-link" type="button" onClick={() => setBroadbandLabelOpen(true)}>
              View Broadband Facts
            </button>

            <fieldset>
              <legend>Contact Information</legend>
              <input id="emailInput" type="email" placeholder="Email" value={form.email} onChange={(event) => updateForm("email", event.target.value)} autoComplete="email" />
              <div className="checkout-two-col">
                <input id="firstNameInput" placeholder="First Name" value={form.firstName} onChange={(event) => updateForm("firstName", event.target.value)} autoComplete="given-name" />
                <input id="lastNameInput" placeholder="Last Name" value={form.lastName} onChange={(event) => updateForm("lastName", event.target.value)} autoComplete="family-name" />
              </div>
              <input id="phoneInput" type="tel" placeholder="Phone Number" value={form.phone} onChange={(event) => updateForm("phone", event.target.value)} autoComplete="tel" />
            </fieldset>

            <section className="shipping-address" aria-labelledby="serviceAddressTitle">
              <div>
                <h2 id="serviceAddressTitle">Service Address</h2>
                <button type="button" onClick={() => openSignup(selectedPlanOption?.name || selectedPlan)}>Change</button>
              </div>
              <p>{form.addressText}</p>
            </section>

            <section className="checkout-referral-card" aria-labelledby="referralCodeTitle">
              <div>
                <h2 id="referralCodeTitle">Referral Code</h2>
                <p>Have a referral or discount code? Add it here before payment.</p>
              </div>
              <div className="referral-code-entry">
                <div className="referral-code-controls">
                  <input id="referralCode" placeholder="Referral or discount code" value={form.referralCode} onChange={(event) => updateForm("referralCode", event.target.value)} />
                  <button type="button" disabled={referralBusy || !form.referralCode} onClick={() => validateReferralCode()}>
                    {referralBusy ? "Checking..." : "Apply"}
                  </button>
                </div>
                {referralStatus && <p className={appliedReferralDiscount ? "referral-status success" : "referral-status"}>{referralStatus}</p>}
              </div>
            </section>

            <fieldset>
              <legend>Payment</legend>
              <input placeholder="Name (As it appears on card)" value={form.cardName} onChange={(event) => updateForm("cardName", event.target.value)} autoComplete="cc-name" />
              <label className="compact-label" htmlFor="cardNumber">Card Number</label>
              <input id="cardNumber" inputMode="numeric" placeholder="4444 3333 2222 1111" value={form.cardNumber} onChange={(event) => updateForm("cardNumber", event.target.value)} autoComplete="cc-number" />
              <div className="card-brand-strip" aria-label="Accepted card types">
                {cardBrandLogos.map((card) => (
                  <img key={card.name} src={card.src} alt={card.name} width="48" height="31" loading="lazy" />
                ))}
              </div>
              <div className="checkout-two-col">
                <label className="compact-label" htmlFor="cardExpiry">
                  MM/YY
                  <input id="cardExpiry" placeholder="03/30" value={form.cardExpiry} onChange={(event) => updateForm("cardExpiry", event.target.value)} autoComplete="cc-exp" />
                </label>
                <label className="compact-label" htmlFor="cardCvc">
                  CVC
                  <input id="cardCvc" inputMode="numeric" placeholder="123" value={form.cardCvc} onChange={(event) => updateForm("cardCvc", event.target.value)} autoComplete="cc-csc" />
                </label>
              </div>
            </fieldset>

            {notice && <p className="notice">{notice}</p>}
          </form>

          <aside className="order-summary" aria-labelledby="orderSummaryTitle">
            <h2 id="orderSummaryTitle">Order summary</h2>
            <div className="summary-section">
              <h3>Monthly Service</h3>
              <LineItem label="Monthly Total" value={`$${monthly.toFixed(2)}/mo`} strong />
              <details className="summary-accordion">
                <summary>View monthly breakdown</summary>
                <div>
                  <LineItem label="Residential Internet - up to 1 Gbps" value={`$${internetBase.toFixed(2)}/mo`} />
                  <LineItem label={selectedRouterName} value={routerUpgrade > 0 ? `+$${routerUpgrade.toFixed(2)}/mo` : "$0/mo"} />
                  {extenderMonthly > 0 && <LineItem label={selectedExtenderOption.label} value={`+$${extenderMonthly.toFixed(2)}/mo`} />}
                  <LineItem label="Regulatory Recovery Fee" value={`$${regulatory.toFixed(2)}/mo`} />
                </div>
              </details>
            </div>
            <div className="summary-section">
              <h3>One-Time Payment</h3>
              <LineItem label="Standard Installation" value={`$${installFee.toFixed(2)}`} />
              {appliedReferralDiscount && (
                <LineItem label={appliedReferralDiscount.label || "Referral Discount"} value={`-$${installDiscount.toFixed(2)}`} />
              )}
            </div>
            <LineItem label="Total Due Upon Install" value={`$${totalDueUponInstall.toFixed(2)}`} strong />
            <section className="install-schedule-summary" aria-labelledby="installScheduleTitle">
              <div>
                <h3 id="installScheduleTitle">Installation Schedule</h3>
                <p>Choose a date, then select an available installation window.</p>
              </div>
              <label className="appointment-date-link" htmlFor="appointmentDate">
                <span>Need a later install date?</span>
                {appointmentDateChanged && <strong>Show appointments on or after {formatDateInputDisplay(appointmentDate)}</strong>}
                <input
                  className="appointment-date-native"
                  id="appointmentDate"
                  type="date"
                  min={formatDateInputValue()}
                  value={appointmentDate}
                  aria-label="Preferred install date"
                  onClick={openDatePicker}
                  onChange={(event) => updateAppointmentDate(event.target.value)}
                />
              </label>
              {appointmentOptions.length > 0 && (
                <div className="appointment-slot-list" role="radiogroup" aria-label="Installation appointment">
                  {appointmentOptions.map((appointment) => {
                    const selected = form.appointmentTime === appointment.time;
                    return (
                      <button
                        className={`appointment-slot ${selected ? "selected" : ""}`}
                        key={`${appointment.time}-${appointment.installer_group}`}
                        type="button"
                        role="radio"
                        aria-checked={selected}
                        onClick={() => chooseAppointment(appointment)}
                      >
                        <span>{formatAppointmentDay(appointment.time)}</span>
                        <strong>{formatAppointmentTime(appointment.time)}</strong>
                      </button>
                    );
                  })}
                </div>
              )}
              {appointmentStatus && <p className="appointment-status">{appointmentStatus}</p>}
              <p className="install-expectations">
                Your technician will arrive at the appointment time. Most installations take about two hours and require access inside your home and to the roof.
              </p>
            </section>
            <button className="place-order-button" type="button" disabled={busy} onClick={submitSignup}>
              {busy ? "Placing Order..." : "Place Order"}
            </button>
            <p className="terms-copy">
              By placing this order, you agree to the Arizona Network <a href="/residential-internet-agreement" target="_blank" rel="noopener noreferrer">Residential Internet Agreement</a>, <a href="/cancellation-terms" target="_blank" rel="noopener noreferrer">Cancellation Terms</a>, <a href="/equipment-return-terms" target="_blank" rel="noopener noreferrer">Equipment Return Terms</a>, and <a href="/privacy-policy" target="_blank" rel="noopener noreferrer">Privacy Policy</a>. You also authorize billing for monthly service, installation, applicable equipment charges, and electronic service notices. Your installation timing will be confirmed by Arizona Network.
            </p>
          </aside>
          {broadbandLabelOpen && (
            <BroadbandFactsModal
              identifier={broadbandPlanIdentifier}
              monthlyBase={monthlyBase}
              regulatory={regulatory}
              installFee={installFee}
              extenderMonthly={extenderMonthly}
              selectedRouterName={selectedRouterName}
              selectedExtenderOption={selectedExtenderOption}
              onClose={() => setBroadbandLabelOpen(false)}
            />
          )}
        </div>
      )}

      {step === 2 && (
        <div className="checkout-success">
          <p className="eyebrow">{completionType === "review" ? "Address review" : "Order received"}</p>
          <h1>{completionType === "review" ? "Your address review request was submitted." : "Your order has been placed."}</h1>
          <p>{completionType === "review" ? "Our team will check service availability and follow up with next steps." : "We will send account paperwork and installation details to your email."}</p>
          <button type="button" onClick={resetSignup}>{completionType === "review" ? "Check Another Address" : "Start Another Sign-Up"}</button>
        </div>
      )}

      {step === 3 && (
        <form className="manual-review-card" onSubmit={submitManualReview}>
          <p className="eyebrow">Address review</p>
          <h1>Send your address to our team for a service availability review.</h1>
          <p>It looks like we need to review your address before we can confirm service. Send the details below and the team will check it.</p>
          <label htmlFor="manualReviewAddress">
            Address
            <input id="manualReviewAddress" value={form.addressText} onChange={(event) => setForm((current) => ({ ...current, addressText: event.target.value }))} />
          </label>
          <div className="checkout-two-col">
            <label htmlFor="manualReviewName">
              Name
              <input id="manualReviewName" value={form.manualName} onChange={(event) => updateForm("manualName", event.target.value)} />
            </label>
            <label htmlFor="manualReviewPhone">
              Phone
              <input id="manualReviewPhone" type="tel" value={form.manualPhone} onChange={(event) => updateForm("manualPhone", event.target.value)} />
            </label>
          </div>
          <label htmlFor="manualReviewEmail">
            Email
            <input id="manualReviewEmail" type="email" value={form.manualEmail} onChange={(event) => updateForm("manualEmail", event.target.value)} />
          </label>
          {notice && <p className="notice">{notice}</p>}
          <div className="signup-flow-actions">
            <button className="secondary-button" type="button" onClick={() => setStep(0)}>Back</button>
            <button type="submit" disabled={busy}>Request Address Review</button>
          </div>
          <p className="terms-copy">By submitting this request, you agree to be contacted by Arizona Network about service availability at this address.</p>
        </form>
      )}
    </section>
  );
}

function PricingBreakdown({ monthly, regulatory, installFee, base, routerName, routerUpgrade, extender }) {
  const extenderFee = extender === "whole-home" ? 10 : 0;
  return (
    <div className="pricing-grid">
      <article>
        <h3>Monthly Pricing Breakdown</h3>
        <LineItem label="Residential Internet" value={`$${base.toFixed(2)}`} />
        <LineItem label={routerName || "Router"} value={routerUpgrade > 0 ? `$${routerUpgrade.toFixed(2)}` : "Included"} />
        {extenderFee > 0 && <LineItem label="Whole Home WiFi Extender" value="$10.00" />}
        <LineItem label="Regulatory Recovery Fee" value={`$${regulatory.toFixed(2)}`} />
        <LineItem label="Monthly Total" value={`$${monthly.toFixed(2)}`} strong />
      </article>
      <article>
        <h3>First Bill Estimate</h3>
        <LineItem label="One-Time Installation" value={`$${installFee.toFixed(2)}`} />
        <LineItem label="Estimated First Bill" value={`$${(monthly + installFee).toFixed(2)}`} strong />
      </article>
    </div>
  );
}

function LineItem({ label, value, strong = false }) {
  return <p className={strong ? "line-item total" : "line-item"}><span>{label}</span><span>{value}</span></p>;
}

function BroadbandFactsRow({ label, value, detail }) {
  return (
    <div className="broadband-facts-row">
      <span>{label}</span>
      <strong>{value}</strong>
      {detail && <small>{detail}</small>}
    </div>
  );
}

function BroadbandFactsSection({ title, children }) {
  return (
    <section className="broadband-facts-section">
      <h3>{title}</h3>
      {children}
    </section>
  );
}

function BroadbandFactsModal({ identifier, monthlyBase, regulatory, installFee, extenderMonthly, selectedRouterName, selectedExtenderOption, onClose }) {
  return (
    <div className="broadband-label-backdrop" onMouseDown={(event) => {
      if (event.target === event.currentTarget) onClose();
    }}>
      <section className="broadband-label-modal" role="dialog" aria-modal="true" aria-labelledby="broadbandFactsTitle">
        <button className="broadband-label-close" type="button" onClick={onClose} aria-label="Close Broadband Facts label">x</button>
        <div className="broadband-label-note">
          <p className="eyebrow">Generated disclosure</p>
          <p>Based on the selected checkout options for this order.</p>
        </div>
        <article className="broadband-facts-label">
          <div className="broadband-facts-header">
            <h2 id="broadbandFactsTitle">Broadband Facts</h2>
            <p>Arizona Network</p>
            <strong>Residential Internet with {selectedRouterName}</strong>
            <span>Fixed Broadband Consumer Disclosure</span>
          </div>

          <BroadbandFactsSection title="Monthly Price">
            <BroadbandFactsRow label="Residential Internet" value={`$${monthlyBase.toFixed(2)}/mo`} />
            <p className="broadband-facts-copy">This monthly price is not an introductory rate. No long-term contract is required.</p>
          </BroadbandFactsSection>

          <BroadbandFactsSection title="Additional Charges & Terms">
            <BroadbandFactsRow label="Provider Monthly Fees" value={`$${regulatory.toFixed(2)}/mo`} detail="Regulatory Recovery Fee" />
            <BroadbandFactsRow label="Router" value={selectedRouterName} detail="Included in the selected monthly price" />
            {extenderMonthly > 0 && (
              <BroadbandFactsRow label={selectedExtenderOption.label} value={`$${extenderMonthly.toFixed(2)}/mo`} />
            )}
            <BroadbandFactsRow label="Government Taxes" value="Vary by location" />
            <BroadbandFactsRow label="One-Time Fees at Purchase" value={`$${installFee.toFixed(2)}`} detail="Standard professional installation" />
            <BroadbandFactsRow label="Early Termination Fee" value="$0" />
          </BroadbandFactsSection>

          <BroadbandFactsSection title="Discounts & Bundles">
            <BroadbandFactsRow label="Required Bundle" value="None" />
            <BroadbandFactsRow label="Referral Discounts" value="Applied if eligible" />
          </BroadbandFactsSection>

          <BroadbandFactsSection title="Speeds Provided with Plan">
            <BroadbandFactsRow label="Typical Download Speed" value="300 Mbps - 1 Gbps" />
            <BroadbandFactsRow label="Typical Upload Speed" value="300 Mbps - 1 Gbps" />
            <BroadbandFactsRow label="Typical Latency" value="5 ms" />
          </BroadbandFactsSection>

          <BroadbandFactsSection title="Data Included with Monthly Price">
            <BroadbandFactsRow label="Data Allowance" value="Unlimited" />
            <BroadbandFactsRow label="Charges for Additional Data Usage" value="$0" />
          </BroadbandFactsSection>

          <BroadbandFactsSection title="Policies & Support">
            <BroadbandFactsRow
              label="Network Management Policy"
              value={<a href="/acceptable-use-policy" target="_blank" rel="noopener noreferrer">View policy</a>}
            />
            <BroadbandFactsRow
              label="Privacy Policy"
              value={<a href="/privacy-policy" target="_blank" rel="noopener noreferrer">View policy</a>}
            />
            <BroadbandFactsRow label="Customer Support" value={supportPhone} detail={supportEmail} />
          </BroadbandFactsSection>

          <div className="broadband-facts-footer">
            <p>
              Learn more about the terms used on this label at the <a href="https://www.fcc.gov/consumers" target="_blank" rel="noopener noreferrer">FCC Consumer Resource Center</a>.
            </p>
            <p>Unique Plan Identifier: {identifier}</p>
          </div>
        </article>
      </section>
    </div>
  );
}

function PerformanceSection() {
  const rows = [
    ["Minimum Download Speed", "300 Mbps"],
    ["Maximum Download Speed", "1 Gbps"],
    ["Minimum Upload Speed", "300 Mbps"],
    ["Maximum Upload Speed", "1 Gbps"],
    ["Data Included Monthly", "Unlimited, no throttling"],
    ["Internet Edge Latency", "5ms"],
  ];
  return (
    <section className="spec-section">
      <h2>Internet Performance</h2>
      <div className="spec-list">
        {rows.map(([label, value]) => <LineItem key={label} label={label} value={value} />)}
      </div>
    </section>
  );
}

function RouterSpecs() {
  const standard = [
    ["Make / Model", "MikroTik hAP ax2"],
    ["CPU", "arm64 / 4 Cores / 864 MHz"],
    ["RAM", "1 GB"],
    ["WiFi Max Data Rate", "5 GHz - 1200 Mbps, 2.4 GHz - 574 Mbps"],
    ["Antenna Gain", "5 GHz - 2 dBi, 2.4 GHz - 4 dBi"],
    ["WiFi Version", "802.11ax / WiFi 6"],
    ["Number of LAN Ports", "4"],
  ];
  const pro = [
    ["Make / Model", "MikroTik Chateau PRO ax"],
    ["CPU", "arm64 / 4 Cores / 2208 MHz"],
    ["RAM", "1 GB"],
    ["WiFi Max Data Rate", "5 GHz - 2400 Mbps, 2.4 GHz - 1148 Mbps"],
    ["Antenna Gain", "5 GHz - 6 dBi, 2.4 GHz - 5 dBi"],
    ["WiFi Version", "802.11ax / WiFi 6"],
    ["Number of LAN Ports", "4"],
  ];
  return (
    <section className="router-specs">
      <h2>Router Specs</h2>
      <div className="router-grid">
        <RouterCard name="Standard Router" image={media.standardRouter} rows={standard} />
        <RouterCard name="Pro Router" image={media.proRouter} rows={pro} />
      </div>
      <a className="advanced-link" href="/homelab">Advanced Features for Power Users</a>
    </section>
  );
}

function RouterCard({ name, image, rows }) {
  return (
    <article className="router-card">
      <img src={image} alt={name} />
      <div>
        <h3>{name}</h3>
        {rows.map(([label, value]) => <LineItem key={label} label={label} value={value} />)}
      </div>
    </article>
  );
}

function InstallProcess() {
  const steps = [
    ["Sign Up and Schedule - On Your Terms", "Sign up from your phone or computer, then pick a real appointment time you can rely on."],
    ["Your Technician Arrives On Time", "A certified technician arrives ready to complete your installation. Most installs take about 1-2 hours depending on roof type and cabling."],
    ["On-Site Survey and Signal Check", "Before anything goes up, the technician confirms your home can receive a strong signal and selects a clean, discreet mounting location."],
    ["Low-Profile Antenna Install", "Antennas are small, low-profile, and placed out of sight whenever possible. Clay tile roofs use a specialized non-penetrating mount."],
    ["Clean, Professional Cabling", "Weather-rated cable is routed neatly to your home connection point with lightning protection and hidden tie-ins where possible."],
    ["Router Setup and Configuration", "Your router is placed for coverage and configured with either your chosen WiFi name and password or secure generated credentials."],
    ["Device Setup and Transition Support", "The technician helps devices reconnect automatically or manually and can help you disconnect old ISP equipment."],
    ["Installation Complete", "Everything is tested and verified before the technician leaves, so your home is online and ready."],
  ];
  return (
    <section className="install-process">
      <div className="process-copy">
        <h2>How Our Installation and Sign-Up Process Works</h2>
        <p>Getting connected is simple, transparent, and designed around your schedule. Here is exactly what to expect from sign-up through installation.</p>
      </div>
      <ol>
        {steps.map(([title, text]) => (
          <li key={title}>
            <h3>{title}</h3>
            <p>{text}</p>
          </li>
        ))}
      </ol>
    </section>
  );
}

function MiniStep({ title, text }) {
  return (
    <article>
      <h3>{title}</h3>
      <p>{text}</p>
    </article>
  );
}

function Testimonial() {
  return (
    <section className="testimonial" id="reviews">
      <div className="testimonial-inner">
        <div>
          <p className="quote">"When I talk to Arizona Network's customer service, it feels super personal. They've resolved any issues I've had right away, even on holidays and weekends."</p>
          <h2>Member since 2022</h2>
          <h3>-- Paul B.</h3>
        </div>
        <div className="review-card">
          <p>Want to hear more of what our customers have to say?</p>
          <a className="button" href="/reviews">Read Reviews</a>
        </div>
      </div>
    </section>
  );
}

function Header({ active, simple = false }) {
  const { openSignup } = useSignup();
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    if (!menuOpen) return undefined;

    function closeOnEscape(event) {
      if (event.key === "Escape") setMenuOpen(false);
    }

    window.addEventListener("keydown", closeOnEscape);
    return () => window.removeEventListener("keydown", closeOnEscape);
  }, [menuOpen]);

  if (simple) {
    return (
      <header className="checkout-header">
        <div className="header-inner checkout-header-inner">
          <a className="brand" href="/"><img src={media.logo} alt="Arizona Network" /></a>
        </div>
      </header>
    );
  }

  return (
    <header className={`site-header${menuOpen ? " menu-open" : ""}`}>
      <div className="header-inner">
        <a className="brand" href="/"><img src={media.logo} alt="Arizona Network" /></a>
        <button
          className="mobile-menu-toggle"
          type="button"
          aria-controls="site-navigation"
          aria-expanded={menuOpen}
          aria-label="Toggle menu"
          onClick={() => setMenuOpen((current) => !current)}
        >
          <span aria-hidden="true" />
          <span aria-hidden="true" />
          <span aria-hidden="true" />
        </button>
        <nav id="site-navigation" aria-label="Site">
          <a className={active === "home" ? "active" : ""} href="/" onClick={() => setMenuOpen(false)}>Home</a>
          <a className={active === "plans" ? "active" : ""} href="/our-plans" onClick={() => setMenuOpen(false)}>Internet Options</a>
          <a className={active === "about" ? "active" : ""} href="/about-us" onClick={() => setMenuOpen(false)}>About Us</a>
          <a className={active === "reviews" ? "active" : ""} href="/reviews" onClick={() => setMenuOpen(false)}>Reviews</a>
          <a className={active === "help" ? "active" : ""} href="/help" onClick={() => setMenuOpen(false)}>Help</a>
          <details className={active === "resources" || active === "speed" || active === "status" ? "tools-menu active" : "tools-menu"}>
            <summary>Tools</summary>
            <div className="tools-menu-panel">
              <a className={active === "resources" ? "active" : ""} href="/resources" onClick={() => setMenuOpen(false)}>Resources</a>
              <a className={active === "status" ? "active" : ""} href="/status" onClick={() => setMenuOpen(false)}>Network Status</a>
              <a className={active === "speed" ? "active" : ""} href="/speed-test" onClick={() => setMenuOpen(false)}>Speed Test</a>
              <a href="https://portal.arizonanetwork.com/" onClick={() => setMenuOpen(false)}>Customer Portal</a>
            </div>
          </details>
        </nav>
        <button
          className="signup-link"
          type="button"
          onClick={() => {
            setMenuOpen(false);
            openSignup();
          }}
        >
          Sign Up
        </button>
      </div>
    </header>
  );
}

function Feature({ title, text, accent, images = [], highlights = [], ctaHref, ctaLabel, className = "", showBackground = true }) {
  return (
    <article className={`feature ${className}`.trim()}>
      {showBackground && <div className="feature-bg" style={{ backgroundImage: `url(${media.gradient})` }} />}
      <h2>{title}</h2>
      <p>{text}</p>
      {highlights.length > 0 && (
        <div className="feature-highlights" aria-label={`${title} highlights`}>
          {highlights.map(([label, value]) => (
            <span key={`${label}-${value}`}>
              <small>{label}</small>
              <strong>{value}</strong>
            </span>
          ))}
        </div>
      )}
      {accent && <strong>{accent}</strong>}
      {ctaHref && <a className="button feature-action" href={ctaHref}>{ctaLabel || "Learn More"}</a>}
      {images.length > 0 && (
        <div className="feature-images">
          {images.map((src) => <img key={src} src={src} alt="" />)}
        </div>
      )}
    </article>
  );
}

function Footer({ simple = false }) {
  const footerGroups = [
    {
      title: "Customer Tools",
      links: [
        ["Billing Portal", "https://portal.arizonanetwork.com/"],
        ["Network Status", "/status"],
        ["Speed Test", "/speed-test"],
      ],
    },
    {
      title: "Programs",
      links: [
        ["Referral Program", "/referral-program"],
        ["Business Partners", "/partner"],
        ["Careers", "/careers"],
        ["Resources", "/resources"],
      ],
    },
    {
      title: "Policies",
      links: [
        ["Network Management", "/nmd"],
        ["Residential Agreement", "/residential-internet-agreement"],
        ["Acceptable Use", "/acceptable-use-policy"],
        ["Privacy", "/privacy-policy"],
      ],
    },
  ];

  if (simple) {
    return (
      <footer className="checkout-footer">
        <p className="copyright">&copy; 2026 Arizona Network.</p>
      </footer>
    );
  }

  return (
    <footer id="help">
      <div className="footer-inner">
        <div>
          <h2>Arizona Network</h2>
          <p><a href={`mailto:${supportEmail}`}>{supportEmail}</a></p>
          <p><a href="tel:14805821736">{supportPhone}</a></p>
        </div>
        <nav className="footer-links" aria-label="Footer navigation">
          {footerGroups.map(({ title, links }) => (
            <section key={title}>
              <h3>{title}</h3>
              <ul>
                {links.map(([label, href]) => (
                  <li key={label}>
                    <a href={href} target={href.startsWith("http") ? "_blank" : undefined} rel={href.startsWith("http") ? "noopener noreferrer" : undefined}>{label}</a>
                  </li>
                ))}
              </ul>
            </section>
          ))}
        </nav>
        <nav className="footer-link-accordions" aria-label="Footer navigation menu">
          {footerGroups.map(({ title, links }) => (
            <details key={title}>
              <summary>{title}</summary>
              <ul>
                {links.map(([label, href]) => (
                  <li key={label}>
                    <a href={href} target={href.startsWith("http") ? "_blank" : undefined} rel={href.startsWith("http") ? "noopener noreferrer" : undefined}>{label}</a>
                  </li>
                ))}
              </ul>
            </details>
          ))}
        </nav>
        <div>
          <h3>Monday - Friday</h3>
          <p>8am - 5pm</p>
          <p className="copyright">&copy; 2026 Arizona Network.</p>
        </div>
      </div>
    </footer>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
