// App-skall: hash-ruting (fungerer på ren statisk hosting uten rewrites),
// mørk header, handlevogn-skuff og forsiden med nordlys-hero + live-søk.
// Monterer først når alle globals fra de andre filene finnes.
import React, { useState, useEffect } from 'react';
import { createRoot } from 'react-dom/client';

const NS = window.STWORDER;

function useHashRoute() {
  const [route, setRoute] = useState(() => location.hash.replace(/^#\/?/, ''));
  useEffect(() => {
    const onChange = () => {
      setRoute(location.hash.replace(/^#\/?/, ''));
      window.scrollTo(0, 0);
    };
    window.addEventListener('hashchange', onChange);
    return () => window.removeEventListener('hashchange', onChange);
  }, []);
  return route;
}

function Home() {
  const { useI18n, nok, ProductCard, SectionTitle, TrustBar, MonoLabel } = NS.ui;
  const { t } = useI18n();
  const LiveSearch = NS.flows.LiveSearch;

  const cheapestWeb = Math.min(...NS.data.products.filter((p) => p.group === 'webhotell').map((p) => p.monthly));
  const cheapestVps = Math.min(...NS.data.vpsPlans.map((p) => p.monthly));
  const noPrice = NS.data.tlds.find((r) => r.tld === 'no').register;

  return (
    <div>
      {/* Nordlys-hero med live-søk i sentrum */}
      <section className="hero-bg relative overflow-hidden">
        <div className="hero-grid pointer-events-none absolute inset-0" />
        <div className="relative mx-auto max-w-3xl px-4 pb-20 pt-14 text-center sm:pt-20">
          <MonoLabel className="fade-up mb-4 text-brand">{t('home.heroLabel')}</MonoLabel>
          <h1 className="fade-up fade-up-1 font-display text-4xl font-bold leading-tight text-navy sm:text-6xl">
            {t('home.titleA')}{' '}
            <span className="bg-gradient-to-r from-emerald-600 to-lime-500 bg-clip-text text-transparent">
              {t('home.titleB')}
            </span>
          </h1>
          <p className="fade-up fade-up-2 mx-auto mt-4 max-w-xl text-base text-gray-600 sm:text-lg">
            {t('home.subtitle')}
          </p>
          <div className="fade-up fade-up-3 mt-9">
            <LiveSearch />
          </div>
          <TrustBar className="fade-up fade-up-4 mt-8" />
        </div>
      </section>

      {/* Produktinnganger */}
      <section className="mx-auto max-w-6xl px-4 py-16">
        <SectionTitle label={t('home.productsLabel')} title={t('home.productsTitle')} />
        <div className="grid gap-6 pt-3 md:grid-cols-3">
          <ProductCard
            badge={t('home.domainsBanner')}
            title={t('home.domainsTitle')}
            sub={t('home.domainsSub')}
            desc={t('home.domainsDesc')}
            priceLabel={t('common.from')}
            price={nok(noPrice) + t('common.perYear')}
            cta={t('home.explore')}
            onCta={() => { location.hash = '#/domener'; }}
          />
          <ProductCard
            badge={t('home.hostingBanner')}
            featured
            title={t('home.hostingTitle')}
            sub={t('home.hostingSub')}
            desc={t('home.hostingDesc')}
            priceLabel={t('common.from')}
            price={nok(cheapestWeb) + t('common.perMonth')}
            cta={t('home.explore')}
            onCta={() => { location.hash = '#/hosting'; }}
          />
          <ProductCard
            badge={t('home.vpsBanner')}
            tone="orange"
            title={t('home.vpsTitle')}
            sub={t('home.vpsSub')}
            desc={t('home.vpsDesc')}
            priceLabel={t('common.from')}
            price={nok(cheapestVps) + t('common.perMonth')}
            cta={t('home.explore')}
            onCta={() => { location.hash = '#/vps'; }}
          />
        </div>
      </section>

      {/* Slik fungerer det – redaksjonelle serif-tall */}
      <section className="border-y border-gray-200 bg-white py-16">
        <div className="mx-auto max-w-6xl px-4">
          <MonoLabel className="mb-8 text-brand">{t('home.stepsLabel')}</MonoLabel>
          <div className="grid gap-10 sm:grid-cols-3">
            {[1, 2, 3].map((n) => (
              <div key={n}>
                <div className="font-display text-5xl font-bold text-gray-200">0{n}</div>
                <div className="mt-3 h-px w-10 bg-accent" />
                <h3 className="mt-3 text-lg font-bold text-navy">{t('home.step' + n)}</h3>
                <p className="mt-1 text-sm leading-relaxed text-gray-600">{t('home.step' + n + 'd')}</p>
              </div>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

function App() {
  const route = useHashRoute();
  const [cartOpen, setCartOpen] = useState(false);
  const { DemoBanner, Header, Footer, CartDrawer, CheckoutToast } = NS.ui;

  useEffect(() => NS.bus.on('cart:open', () => setCartOpen(true)), []);
  // Lukk skuffen ved navigasjon – ellers blokkerer overlayet den nye siden.
  useEffect(() => { setCartOpen(false); }, [route]);

  let page;
  if (route.startsWith('domener')) page = <NS.flows.Domains />;
  else if (route.startsWith('hosting')) page = <NS.flows.Hosting />;
  else if (route.startsWith('vps')) page = <NS.flows.Vps />;
  else if (route.startsWith('kasse')) page = <NS.pages.Checkout />;
  else if (route.startsWith('kvittering')) page = <NS.pages.Receipt />;
  else page = <Home />;

  const routeKey = route.split('/')[0];

  return (
    <>
      <DemoBanner />
      <Header route={routeKey} onCart={() => setCartOpen(true)} />
      <main>{page}</main>
      <Footer />
      <CartDrawer open={cartOpen} onClose={() => setCartOpen(false)} />
      <NS.flows.UpsellDialog />
      <CheckoutToast />
    </>
  );
}

// Vent til alle filer har registrert seg på window.STWORDER før montering.
function ready() {
  return !!(
    NS.ui && NS.data && NS.api && NS.store && NS.i18n &&
    NS.flows && NS.flows.Domains && NS.flows.Hosting && NS.flows.Vps && NS.flows.LiveSearch &&
    NS.pages && NS.pages.Checkout && NS.pages.Receipt
  );
}

function mountWhenReady() {
  if (ready()) {
    createRoot(document.getElementById('root')).render(<App />);
  } else {
    setTimeout(mountWhenReady, 25);
  }
}
mountWhenReady();
