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",
  hero: "/assets/install-assets/Kaufman_compilation.mp4",
  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: "Fast and Affordable",
    price: 54,
    router: media.standardRouter,
    bullets: ["Standard Router Included", "up to 1 Gbps Download Speed", "Great for homes with a smaller footprint, or fewer devices"],
  },
  {
    name: "Pro",
    value: "8",
    kicker: "Great for large homes with many devices",
    price: 64,
    router: media.proRouter,
    bullets: ["New Pro Router Included", "up to 1 Gbps Download Speed", "Expansive WiFi coverage", "Many devices"],
  },
];

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 signupCompleteStep = 6;
const routerOptions = [
  { value: "1", label: "No Extender - $0.00/Month", price: 0 },
  { value: "104", label: "Whole Home WiFi Extender - $10.00/Month", price: 10 },
];

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;
}

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 [signupOpen, setSignupOpen] = useState(() => window.location.hash === "#signup");
  const [signupDockVisible, setSignupDockVisible] = useState(false);
  const [signupPlan, setSignupPlan] = useState("Standard");
  const isPlansPage = path === "/our-plans";
  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 activeArticle = resourceArticles.find((article) => article.path === path);
  const isResourceArticlePage = Boolean(activeArticle);
  const isHomePage = path === "";
  const isKnownPage = isHomePage || isPlansPage || isAboutPage || isReviewsPage || isFeedbackPage || isHelpPage || isNmdPage || isPartnerPage || isCareersPage || isHomelabPage || isGilbertTrialPage || isReferralPage || isSpeedTestPage || isStatusPage || isResourcesPage || isResourceArticlePage;

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

  function openSignup(planName) {
    if (planName) setSignupPlan(planName);
    setSignupOpen(true);
    setSignupDockVisible(false);
  }

  function closeSignup() {
    const currentSignupStep = Number(localStorage.getItem("aznCurrentStep") || 0);
    setSignupOpen(false);
    setSignupDockVisible(currentSignupStep !== signupCompleteStep);
  }

  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", signupOpen);
    return () => document.body.classList.remove("signup-modal-open");
  }, [signupOpen]);

  return (
    <SignupContext.Provider value={{ openSignup }}>
      <Header
        active={path === "" ? "home" : isPlansPage ? "plans" : isAboutPage ? "about" : isReviewsPage ? "reviews" : isHelpPage ? "help" : (isResourcesPage || isResourceArticlePage) ? "resources" : isSpeedTestPage ? "speed" : isStatusPage ? "status" : ""}
      />
      <main>
        {isPlansPage ? <PlansPage /> :
          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} /> :
          isHomePage ? <HomePage /> :
          <NotFoundPage />}
      </main>
      <Footer />
      <SignupModal
        isOpen={signupOpen}
        onClose={closeSignup}
        selectedPlan={signupPlan}
        setSelectedPlan={setSignupPlan}
      />
      {signupDockVisible && !signupOpen && (
        <SignupDock
          onOpen={() => openSignup(signupPlan)}
          onDismiss={() => setSignupDockVisible(false)}
        />
      )}
    </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 address is not on our map.</h1>
          <p>
            The link may have moved, the URL may have a typo, or this page may be outside our current route table.
          </p>
          <div className="not-found-actions">
            <a className="button" href="/">Go Home</a>
            <a className="button secondary-button" href="/our-plans">View Plans</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>No route</strong>
          <p>Try a known Arizona Network address.</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">Add GOOGLE_MAPS_API_KEY to enable the live map.</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>Add GOOGLE_MAPS_API_KEY to enable the live map.</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 is 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} Status is informed by {monitors.length} live site {monitors.length === 1 ? "check" : "checks"}. 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" src={media.hero} autoPlay muted loop playsInline />
        <div className="hero-card">
          <div>
            <h1>Internet That Actually Works When You Need It</h1>
            <p>No contracts. No throttling. No surprise bills.</p>
            <p>Just fast, reliable internet built for Arizona.</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>Empowering Our Community</h2>
            <p>We believe everyone in Arizona deserves the freedom to explore, learn, and build, starting with fast, reliable internet.</p>
            <p>As a company owned and operated in Arizona, our mission goes beyond connectivity. We live here, we work here, and we're invested in helping our neighbors thrive.</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="24x7 Customer Support" text="Any problem, any time. Get the help you need, not a sales pitch." accent="480-582-1736" />
          <Feature title="All Gear Included" text="Every plan comes with a free router and the equipment required, so you can connect right away without extra purchases." images={[media.standardRouter, media.proRouter]} />
          <Feature title="Free Internet For Life" text="Refer friends and family to Arizona Network, and get credit for spreading the word. Give $100, and get $100. After 5, you get free internet for life." images={[media.freeInternet]} />
        </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 = selectedPlan === "Pro" ? 64 : 54;
  const regulatory = Number((base * 0.03).toFixed(2));
  const monthly = base + regulatory;
  const installFee = 74;

  return (
    <div className="plans-page">
      <section className="plans-hero" style={{ backgroundImage: `url(${media.plansBg})` }}>
        <div className="plans-hero-copy">
          <h1>Simple plans. Transparent pricing. Competitive speeds.</h1>
        </div>
      </section>

      <section className="plan-card-section" id="plans">
        <div className="plan-cards">
          {plans.map((plan) => (
            <PlanCard
              key={plan.name}
              plan={plan}
              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} monthly={monthly} installFee={installFee} onOpen={() => openSignup(selectedPlan)} />

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

function AboutPage() {
  const valueCards = [
    {
      title: "We always offer you 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: "We are willing to go above and beyond.",
      lead: "Getting the help you need should never be stressful or difficult.",
      text: "We are dedicated to providing personable and attentive customer service. We are here for you.",
      icon: "i",
    },
    {
      title: "We like to keep things simple.",
      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>A small company with big aspirations. Striving to bring you the best internet Arizona has to offer.</h1>
          <div className="risk-free">
            <h2>Try it risk-free</h2>
            <p>If your service doesn't meet your expectations within the first 30 days. We'll refund your installation fee and your first month no hassle, 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>The high-performance routers used by Arizona Network are both fast and secure, reflecting our commitment to bringing you the best internet service possible. Rest assured, when things aren't functioning as they should, we'll go above and beyond to serve you.</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's why we use the best tools available, whether it's cutting-edge 60GHz Ubiquiti Wave for ultra-high-speed connections or Cambium AX 6GHz 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>Want To See More?</p>
        <a className="button" href="/our-plans">Shop Our Plans</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 A. Davis",
      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 Wilkie",
      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 Winsor",
      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 Lutz",
      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 Caruso",
      since: "Google review",
      theme: "Clear communication",
    },
    {
      quote: "Technicians were on time, efficient, courteous, friendly and extremely helpful.",
      name: "Mary Ann Watson",
      since: "Google review",
      theme: "Helpful technicians",
    },
  ];
  const proofPoints = [
    ["24x7", "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 A. Davis, 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. We take your requests seriously and track them through our cataloging and mapping system.",
        "That helps us create heat maps showing where demand is highest, so we can prioritize expansion efforts. You can also encourage neighbors to fill out the request form.",
      ],
    },
    {
      question: "What kinds of routers do you use?",
      answer: ["We use a selection of Mikrotik routers: the Hap series for standard plans, and either the Chateau or Audience for upgraded service."],
    },
    {
      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 includes 4 Ethernet ports for wired devices.",
        "The premium router includes 1 Ethernet port and 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 is a readable first-pass copy of Arizona Network's disclosure for local review.</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() {
  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"]}
          buttonText="Submit Partnership Interest"
          successText="Thanks. Your partnership interest has been noted, and the Arizona Network team can follow up from here."
        />
        <div className="copy-panel">
          <h2>Benefits the program offers your business</h2>
          <ul className="check-list">
            <li>Free 1 GB 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 signups and installation scheduling.",
    "Troubleshoot basic service, account, and billing issues.",
    "Coordinate with technicians and internal 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, signups, 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("Sending your discount code...");
    try {
      await apiPost("/api/website/send-offer", {
        sessionID: sessionValue,
        email,
        referralPage: trialReferralLink,
        referralCode: trialReferralCode,
      });
      await apiPost("/api/email/subscribe", { email, name: "" }).catch(() => {});
      setOfferEmail("");
      setOfferMessage("Your discount code has been sent.");
    } 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 Signup</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 steps = [
    ["Step 1: Get Your Referral Code", "Log in to your billing portal to find your unique referral code. Copy your personal link and share it by text, email, or social media.", media.referralProgress],
    ["Step 2: Your Friend or Family Uses the Link", "When someone uses your referral link, they are automatically tied to your account. Phone signups can mention your name or code.", media.referralSignup],
    ["Step 3: Earn $100 for Each Referral", "Once your referral has been active for 30 days, you receive a $100 credit applied directly to your account.", media.referralCredit],
    ["Step 4: Refer 5, Pay $0 Forever", "After 5 successful referrals, your monthly internet bill drops to $0 permanently. No gimmicks. No expiration.", media.referralFree],
  ];

  return (
    <LandingPage className="referral-page" heroImage={media.referralBg} eyebrow="Referral Program" title="Refer 5, Free Internet For Life" subtitle="Help friends or family get connected and you could end up paying $0/month for life.">
      <section className="step-images">
        {steps.map(([title, text, image]) => <ImageFeature key={title} title={title} text={text} image={image} />)}
      </section>
      <section className="about-cta">
        <p>Ready to share or sign up?</p>
        <a className="button" href="/our-plans">Shop Our Plans</a>
      </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 plans 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 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, buttonText, successText }) {
  const [message, setMessage] = useState("");
  const fieldId = (field) => field.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");

  return (
    <form className="contact-form" onSubmit={(event) => { event.preventDefault(); setMessage(successText); }}>
      <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" : ""}
          />
        </label>
      ))}
      <button className="button" type="submit">{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">
      <div className="plan-cards">
        {plans.map((plan) => <PlanCard key={plan.name} plan={plan} selected={false} buttonHref="/our-plans" buttonLabel="View Plans" />)}
      </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>Member since {review.since}</span>
        </div>
      </div>
    </article>
  );
}

function PlanCard({ plan, selected, onChoose, buttonHref, buttonLabel }) {
  const { openSignup } = useSignup();

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

  return (
    <article className={`plan-card ${selected ? "selected" : ""}`}>
      <p className="plan-kicker">{plan.kicker}</p>
      <h2>{plan.name}</h2>
      <a className="plan-price" href="#signup" onClick={openPlanSignup}>${plan.price.toFixed(2)}</a>
      <p className="up-to">up to</p>
      <strong>1 Gbps</strong>
      <img src={plan.router} alt={`${plan.name} router`} />
      <ul>
        {plan.bullets.map((bullet) => <li key={bullet}>{bullet}</li>)}
      </ul>
      {buttonHref ? (
        <a className="plan-action" href={buttonHref}>{buttonLabel || "View Plans"}</a>
      ) : (
        <button onClick={onChoose}>{selected ? "Selected" : "Choose Plan"}</button>
      )}
    </article>
  );
}

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

function SignupModal({ isOpen, onClose, selectedPlan, setSelectedPlan }) {
  useEffect(() => {
    if (!isOpen) return;

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

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

  if (!isOpen) return null;

  return (
    <div className="signup-modal-backdrop" onMouseDown={(event) => {
      if (event.target === event.currentTarget) onClose();
    }}>
      <div className="signup-modal" role="dialog" aria-modal="true" aria-labelledby="signupModalTitle">
        <button className="signup-modal-close" type="button" onClick={onClose} aria-label="Close signup">
          <span aria-hidden="true">x</span>
        </button>
        <SignupPanel selectedPlan={selectedPlan} setSelectedPlan={setSelectedPlan} titleId="signupModalTitle" />
      </div>
    </div>
  );
}

function SignupDock({ onOpen, onDismiss }) {
  return (
    <div className="signup-dock" role="region" aria-label="Resume signup">
      <div>
        <strong>Signup paused</strong>
        <span>Pick up where you left off.</span>
      </div>
      <button className="button" type="button" onClick={onOpen}>Continue Signup</button>
      <button className="signup-dock-close" type="button" onClick={onDismiss} aria-label="Dismiss signup reminder">
        <span aria-hidden="true">x</span>
      </button>
    </div>
  );
}

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>
            {selectedPlan} starts at ${monthly.toFixed(2)}/month. Installation is ${installFee.toFixed(2)}.
          </p>
        )}
      </div>
      <button className="button shadow" type="button" onClick={action}>Start Signup</button>
    </section>
  );
}

function SignupPanel({ selectedPlan = "Standard", setSelectedPlan, titleId }) {
  const defaultPlan = plans.find((plan) => plan.name === selectedPlan) || plans[0];
  const [step, setStep] = useState(() => Number(localStorage.getItem("aznCurrentStep") || 0));
  const [notice, setNotice] = useState("");
  const [busy, setBusy] = useState(false);
  const [placesReady, setPlacesReady] = useState(false);
  const [browserID, setBrowserID] = useState("");
  const [sessionID, setSessionID] = useState("");
  const [planOptions, setPlanOptions] = useState(() => plans.map((plan) => ({
    value: plan.value,
    label: `${plan.name} 800 Mbps - $${plan.price}/Month`,
    name: plan.name,
    price: plan.price,
  })));
  const [appointments, setAppointments] = useState([]);
  const [form, setForm] = useState(() => ({
    addressText: localStorage.getItem("addressFormatted") || "",
    address: JSON.parse(localStorage.getItem("aznAddress") || "null"),
    speedPlan: localStorage.getItem("speedPlan") || defaultPlan.value,
    routerChoice: localStorage.getItem("routerChoice") || routerOptions[0].value,
    appointmentSoonest: new Date().toISOString().slice(0, 10),
    appointmentChoice: localStorage.getItem("appointmentChoice") || "",
    firstName: localStorage.getItem("firstName") || "",
    lastName: localStorage.getItem("lastName") || "",
    email: localStorage.getItem("email") || "",
    phone: localStorage.getItem("phone") || "",
    referralCode: localStorage.getItem("referralCode") || "",
    subscribed: localStorage.getItem("subscribed") !== "false",
    manualName: "",
    manualPhone: "",
    manualEmail: "",
  }));
  const addressInputRef = useRef(null);
  const progress = [10, 25, 50, 75, 85, 99, 100][Math.min(step, 6)] || 10;

  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 autocomplete;
    let listener;
    loadGooglePlaces()
      .then((ready) => {
        setPlacesReady(ready);
        if (!ready || !addressInputRef.current) return;
        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(() => {
    localStorage.setItem("aznCurrentStep", String(step));
    if (step > 0 && sessionID) {
      apiPost("/api/website/log-info", { sessionID, info: collectInfo() }).catch(() => {});
    }
    if (step === 3 && appointments.length === 0) {
      loadAppointments(form.appointmentSoonest);
    }
  }, [step, sessionID]);

  useEffect(() => {
    const matchingPlan = planOptions.find((plan) => plan.name === selectedPlan);
    if (matchingPlan && step <= 1 && form.speedPlan !== matchingPlan.value) {
      updateForm("speedPlan", matchingPlan.value);
    }
  }, [selectedPlan, planOptions, step, form.speedPlan]);

  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", "routerChoice", "firstName", "lastName", "email", "phone", "referralCode"].includes(field)) {
      localStorage.setItem(field, value);
    }
    if (field === "subscribed") {
      localStorage.setItem("subscribed", value ? "true" : "false");
    }
  }

  function collectInfo() {
    const selectedAppointment = appointments.find((item) => String(item.id) === String(form.appointmentChoice));
    const selectedPlanOption = planOptions.find((item) => item.value === form.speedPlan);
    const selectedRouter = routerOptions.find((item) => item.value === form.routerChoice);
    const address = form.address || {};
    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: selectedRouter?.value || form.routerChoice,
      installAppointment: {
        installer: selectedAppointment?.installer || "",
        time: selectedAppointment?.time || "",
      },
      customerStatus: 3,
      oneTimeDiscount: "",
      specialNotes: "",
      referralCode: form.referralCode || "",
    };
  }

  async function checkService(event) {
    event.preventDefault();
    if (!form.address?.location) {
      setNotice(placesReady ? "Select your address from the Google suggestions before checking availability." : "Google address autocomplete is not configured yet. Use manual review or add GOOGLE_MAPS_API_KEY to the server.");
      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: `${name} - $${price}/Month`,
          name,
          price: Number(price),
        })) : planOptions;
        setPlanOptions(remotePlans);
        updateForm("speedPlan", remotePlans[0]?.value || form.speedPlan);
        localStorage.setItem("serviceable", "true");
        setSelectedPlan?.(remotePlans[0]?.name?.includes("Premium") ? "Pro" : "Standard");
        setNotice("Great news. That address appears serviceable.");
        setStep(1);
      } else {
        localStorage.setItem("serviceable", "false");
        setNotice("That address needs a manual review before signup.");
        setStep(7);
      }
    } catch (error) {
      setNotice(error.message);
    } finally {
      setBusy(false);
    }
  }

  async function loadAppointments(dateValue) {
    setBusy(true);
    setNotice("Loading soonest appointments...");
    try {
      const date = new Date(`${dateValue}T12:00:00`);
      const soonestDate = `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
      const result = await apiPost("/api/signup/appts", { soonestDate });
      const appts = Array.isArray(result.data) ? result.data.map((item, index) => ({
        id: index,
        time: item.time,
        installer: item.installer_group,
      })) : [];
      setAppointments(appts);
      if (appts[0]) updateForm("appointmentChoice", String(appts[0].id));
      setNotice(appts.length ? "Choose an installation appointment that works for you." : "No appointments were returned for that date. Try a later date or call us.");
    } catch (error) {
      setNotice(error.message);
    } finally {
      setBusy(false);
    }
  }

  function nextFromPlan() {
    if (!form.speedPlan) {
      setNotice("Choose a speed plan to continue.");
      return;
    }
    setStep(2);
  }

  function nextFromRouter() {
    if (!form.routerChoice) {
      setNotice("Choose a router option to continue.");
      return;
    }
    setStep(3);
  }

  function nextFromAppointment() {
    if (!form.appointmentChoice) {
      setNotice("Choose an appointment time to continue.");
      return;
    }
    setStep(4);
  }

  function nextFromContact() {
    if (!form.email || !form.phone) {
      setNotice("Enter your email and phone number so we can set up the account.");
      return;
    }
    setStep(5);
  }

  async function submitSignup(event) {
    event.preventDefault();
    if (!form.firstName || !form.lastName) {
      setNotice("Enter your first and last name to finish signup.");
      return;
    }

    setBusy(true);
    setNotice("Submitting your signup...");
    try {
      const info = collectInfo();
      const result = await apiPost("/api/signup/submit", { info, userID: browserID });
      if (result.status === "failure") {
        setNotice(result.message || "Signup could not be completed.");
        return;
      }
      if (form.subscribed) {
        await apiPost("/api/email/subscribe", {
          email: form.email,
          name: `${form.firstName} ${form.lastName}`,
        }).catch(() => {});
      }
      localStorage.clear();
      localStorage.setItem("userID", browserID);
      localStorage.setItem("aznCurrentStep", String(signupCompleteStep));
      setStep(signupCompleteStep);
      setNotice("Success. Your signup has been submitted.");
    } 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 for manual review.");
      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 || "",
        },
      });
      if (form.subscribed) {
        await apiPost("/api/email/subscribe", { email, name }).catch(() => {});
      }
      setNotice(result.status === "failure" ? "Manual review was received, but the remote API did not return success." : "Thanks. Your address was submitted for manual review.");
      localStorage.setItem("aznCurrentStep", String(signupCompleteStep));
      setStep(signupCompleteStep);
    } 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,
      routerChoice: routerOptions[0].value,
      appointmentChoice: "",
      firstName: "",
      lastName: "",
      email: "",
      phone: "",
      subscribed: false,
      manualName: "",
      manualPhone: "",
      manualEmail: "",
    }));
    setAppointments([]);
    setNotice("");
    setStep(0);
  }

  const selectedPlanOption = planOptions.find((item) => item.value === form.speedPlan) || planOptions[0];
  const selectedRouter = routerOptions.find((item) => item.value === form.routerChoice) || routerOptions[0];
  const monthlyBase = selectedPlanOption?.price || defaultPlan.price;
  const regulatory = Number(((monthlyBase + selectedRouter.price) * 0.03).toFixed(2));
  const monthly = monthlyBase + selectedRouter.price + regulatory;
  const stageCopy = [
    ["Service address", "Start with the address where you want internet service."],
    ["Choose your plan", "Pick the internet plan that fits your home."],
    ["WiFi coverage", "Choose whether you want whole-home WiFi coverage."],
    ["Schedule install", "Pick an installation appointment that works for you."],
    ["Contact details", "Tell us where to send updates and account paperwork."],
    ["Finish signup", "Add your name and submit your signup request."],
    ["Signup submitted", "Your request is in. Watch your email for the next step."],
    ["Manual review", "Send your address to the team for a serviceability review."],
  ][step] || ["Sign up", "Signing up just takes a few minutes."];

  return (
    <section className="signup">
      <div className="signup-panel">
        <div className="signup-titlebar">
          <div>
            <p className="eyebrow">{stageCopy[0]}</p>
            <h2 id={titleId}>{stageCopy[1]}</h2>
          </div>
          <span>{Math.min(step + 1, 6)} / 6</span>
        </div>
        <div className="progress"><span style={{ width: `${progress}%` }} /></div>

        {step === 0 && (
          <form className="signup-step" onSubmit={checkService}>
            <label htmlFor="address">Service address</label>
            <div className="address-row">
              <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"
              />
              <button type="submit" disabled={busy}>Check Address</button>
            </div>
            <button className="text-button" type="button" onClick={() => setStep(7)}>
              I can't find my address
            </button>
          </form>
        )}

        {step === 1 && (
          <div className="signup-step">
            <label htmlFor="speedPlanChoice">Choose your speed plan</label>
            <select id="speedPlanChoice" value={form.speedPlan} onChange={(event) => updateForm("speedPlan", event.target.value)}>
              {planOptions.map((plan) => <option key={plan.value} value={plan.value}>{plan.label}</option>)}
            </select>
            <div className="signup-actions">
              <button className="secondary-button" type="button" onClick={() => setStep(0)}>Back</button>
              <button type="button" onClick={nextFromPlan}>Continue</button>
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="signup-step">
            <label htmlFor="routerChoice">Choose your WiFi option</label>
            <select id="routerChoice" value={form.routerChoice} onChange={(event) => updateForm("routerChoice", event.target.value)}>
              {routerOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
            </select>
            <div className="signup-actions">
              <button className="secondary-button" type="button" onClick={() => setStep(1)}>Back</button>
              <button type="button" onClick={nextFromRouter}>Continue</button>
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="signup-step">
            <div className="selectors">
              <label htmlFor="appointmentSoonest">
                Soonest install date
                <input id="appointmentSoonest" type="date" value={form.appointmentSoonest} onChange={(event) => {
                  updateForm("appointmentSoonest", event.target.value);
                  loadAppointments(event.target.value);
                }} />
              </label>
              <label htmlFor="appointmentChoice">
                Appointment
                <select id="appointmentChoice" value={form.appointmentChoice} onChange={(event) => updateForm("appointmentChoice", event.target.value)} disabled={busy || appointments.length === 0}>
                  {appointments.map((appointment) => (
                    <option key={appointment.id} value={appointment.id}>{new Date(appointment.time).toLocaleString()}</option>
                  ))}
                </select>
              </label>
            </div>
            <div className="signup-actions">
              <button className="secondary-button" type="button" onClick={() => setStep(2)}>Back</button>
              <button type="button" onClick={nextFromAppointment}>Continue</button>
            </div>
          </div>
        )}

        {step === 4 && (
          <div className="signup-step">
            <div className="selectors">
              <label htmlFor="emailInput">
                Email
                <input id="emailInput" type="email" value={form.email} onChange={(event) => updateForm("email", event.target.value)} autoComplete="email" />
              </label>
              <label htmlFor="phoneInput">
                Phone
                <input id="phoneInput" type="tel" value={form.phone} onChange={(event) => updateForm("phone", event.target.value)} autoComplete="tel" />
              </label>
            </div>
            <label className="checkbox-row">
              <input type="checkbox" checked={form.subscribed} onChange={(event) => updateForm("subscribed", event.target.checked)} />
              Send me Arizona Network updates and offers.
            </label>
            <div className="signup-actions">
              <button className="secondary-button" type="button" onClick={() => setStep(3)}>Back</button>
              <button type="button" onClick={nextFromContact}>Continue</button>
            </div>
          </div>
        )}

        {step === 5 && (
          <form className="signup-step" onSubmit={submitSignup}>
            <div className="selectors">
              <label htmlFor="firstNameInput">
                First name
                <input id="firstNameInput" value={form.firstName} onChange={(event) => updateForm("firstName", event.target.value)} autoComplete="given-name" />
              </label>
              <label htmlFor="lastNameInput">
                Last name
                <input id="lastNameInput" value={form.lastName} onChange={(event) => updateForm("lastName", event.target.value)} autoComplete="family-name" />
              </label>
            </div>
            <label htmlFor="referralCode">
              Referral code
              <input id="referralCode" value={form.referralCode} onChange={(event) => updateForm("referralCode", event.target.value)} />
            </label>
            <div className="signup-actions">
              <button className="secondary-button" type="button" onClick={() => setStep(4)}>Back</button>
              <button type="submit" disabled={busy}>Submit Signup</button>
            </div>
          </form>
        )}

        {step === 6 && (
          <div className="signup-step signup-success">
            <p>Your request has been submitted. We will send the signup paperwork and appointment details to your email.</p>
            <button type="button" onClick={resetSignup}>Start Another Signup</button>
          </div>
        )}

        {step === 7 && (
          <form className="signup-step" onSubmit={submitManualReview}>
            <p>It looks like we need to review your address manually. 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="selectors">
              <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>
            <label className="checkbox-row">
              <input type="checkbox" checked={form.subscribed} onChange={(event) => updateForm("subscribed", event.target.checked)} />
              Send me Arizona Network updates and offers.
            </label>
            <div className="signup-actions">
              <button className="secondary-button" type="button" onClick={() => setStep(0)}>Back</button>
              <button type="submit" disabled={busy}>Request Manual Review</button>
            </div>
          </form>
        )}

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

        {step > 0 && step < 6 && (
          <PricingBreakdown monthly={monthly} regulatory={regulatory} installFee={step === 7 ? 0 : 74} base={monthlyBase} extender={selectedRouter.value === "104" ? "whole-home" : "none"} />
        )}
      </div>
    </section>
  );
}

function PricingBreakdown({ monthly, regulatory, installFee, base, extender }) {
  const extenderFee = extender === "whole-home" ? 10 : 0;
  return (
    <div className="pricing-grid">
      <article>
        <h3>Monthly Pricing Breakdown</h3>
        <LineItem label="Base Internet Fee" value={`$${base.toFixed(2)}`} />
        {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>Installation Pricing Breakdown</h3>
        <LineItem label="Install Fee" value={`$${installFee.toFixed(2)}`} />
        <LineItem label="Total Due at Install" 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 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", "5Ghz - 1200 Mbps, 2.4Ghz - 574 Mbps"],
    ["Antenna Gain", "5Ghz - 2 dBi, 2.4Ghz - 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", "5Ghz - 2400 Mbps, 2.4Ghz - 1148 Mbps"],
    ["Antenna Gain", "5Ghz - 6 dBi, 2.4Ghz - 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 Pro 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 website, 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 demarcation 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 signup 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 }) {
  const { openSignup } = useSignup();

  return (
    <header>
      <div className="header-inner">
        <a className="brand" href="/"><img src={media.logo} alt="Arizona Network" /></a>
        <nav aria-label="Site">
          <a className={active === "home" ? "active" : ""} href="/">Home</a>
          <a className={active === "plans" ? "active" : ""} href="/our-plans">Our Plans</a>
          <a className={active === "about" ? "active" : ""} href="/about-us">About Us</a>
          <a className={active === "reviews" ? "active" : ""} href="/reviews">Reviews</a>
          <a className={active === "help" ? "active" : ""} href="/help">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">Resources</a>
              <a className={active === "status" ? "active" : ""} href="/status">Network Status</a>
              <a className={active === "speed" ? "active" : ""} href="/speed-test">Speed Test</a>
              <a href="https://portal.arizonanetwork.com/">Customer Portal</a>
            </div>
          </details>
        </nav>
        <button className="signup-link" type="button" onClick={() => openSignup()}>Sign Up</button>
      </div>
    </header>
  );
}

function Feature({ title, text, accent, images = [] }) {
  return (
    <article className="feature">
      <div className="feature-bg" style={{ backgroundImage: `url(${media.gradient})` }} />
      <h2>{title}</h2>
      <p>{text}</p>
      {accent && <strong>{accent}</strong>}
      {images.length > 0 && (
        <div className="feature-images">
          {images.map((src) => <img key={src} src={src} alt="" />)}
        </div>
      )}
    </article>
  );
}

function Footer() {
  const links = [
    ["Network Status and Uptime", "/status"],
    ["Manage My Billing Account", "https://portal.arizonanetwork.com/"],
    ["Run a Speed Test", "/speed-test"],
    ["Internet Resource Center", "/resources"],
    ["Network Management Disclosure", "/nmd"],
    ["Business Partnership Program", "/partner"],
    ["Careers", "/careers"],
    ["Referral Program", "/referral-program"],
  ];

  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>
        <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>
        <div>
          <h3>Monday - Friday</h3>
          <p>8am - 5pm</p>
          <p className="copyright">(c) 2026 by Arizona Network</p>
        </div>
      </div>
    </footer>
  );
}

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