// Domeneflyt: nordlys-hero med LiveSearch (AI-boks med resultater som faller ut
// av boksen, tier 1 øyeblikkelig + tier 2 async-bekreftelse), diskret hosting-
// upsell (GH30–32 / WP20–22) når et domene legges i vognen.
// Domenesøket er butikkens inngang og bor på rot-ruten (#/ → #/domener).
// TLD-pristabellen er flyttet til Kirby-domenesiden (SEO-innhold).
import React, { useState, useEffect, useMemo } from 'react';

const NS = window.STWORDER;

// Norids offisielle oppslagstjeneste – eneste lovlige vei til innehaver for
// .no (RDAP publiserer den ikke, og web-oppslaget har bruksvilkår mot scraping).
// Vi lenker dit i stedet for å hente det selv. ?query=<domene> er Norids EGET
// URL-mønster (deres lookUpUrl bygger det, og siden kjører checkForQuery() ved
// mount) – så domenet forhåndsutfylles. Dette er en enkelt, bruker-initiert
// oppslag på Norids side, ikke scraping.
const NORID_LOOKUP_URL = 'https://www.norid.no/en/domeneoppslag/oppslagstjeneste/';
const noridLookup = (domain) => NORID_LOOKUP_URL + '?query=' + encodeURIComponent(NS.api.toAce(domain));

function useDebounced(value, ms) {
  const [v, setV] = useState(value);
  useEffect(() => {
    const id = setTimeout(() => setV(value), ms);
    return () => clearTimeout(id);
  }, [value, ms]);
  return v;
}

// Async tier 1-søk. Forrige resultat står til nytt svar er inne (ingen
// flimring), og svar som er utdatert når de kommer kastes – nettverket
// garanterer ikke rekkefølge.
function useSearch(q) {
  const [results, setResults] = useState(null);
  useEffect(() => {
    let stale = false;
    NS.api.search(q).then((r) => {
      if (!stale) setResults(r);
    });
    return () => { stale = true; };
  }, [q]);
  return results;
}

// Bekreftelses-cache (tier 2) deles mellom komponenter i økten.
const confirmCache = {};
function useConfirmations(results) {
  const [, bump] = useState(0);
  useEffect(() => {
    if (!results) return;
    results.filter((r) => r.status === 'free' && !confirmCache[r.domain]).forEach((r) => {
      confirmCache[r.domain] = { state: 'checking' };
      NS.api.confirm(r.domain).then((v) => {
        confirmCache[r.domain] = Object.assign({ state: 'done' }, v);
        bump((n) => n + 1);
      });
    });
  }, [results]);
  return confirmCache;
}

function statusFor(r, conf) {
  if (r.status === 'taken') return { kind: 'taken' };
  // 'unknown' = backenden har ikke sonen lastet (eller .no-miss): tentativt
  // "Ledig?", ingen tier 2-confirm. Itereres senere (EPP-bekreftelse).
  if (r.status === 'unknown') return { kind: 'maybe', price: r.price, premium: r.premium };
  const c = conf[r.domain];
  if (!c || c.state === 'checking') return { kind: 'checking' };
  return c.available
    ? { kind: 'free', price: c.price, premium: c.premium }
    : { kind: 'taken' };
}

// Tilgjengelighet skannes nedover venstrekanten: fylt emerald = ledig (også
// tentativt "maybe"/seed-bom – vises optimistisk), hul grå = opptatt,
// pulserende = sjekker.
function StatusDot({ kind }) {
  const base = 'h-2.5 w-2.5 shrink-0 rounded-full ';
  if (kind === 'free' || kind === 'maybe') return <span className={base + 'bg-brand'} />;
  if (kind === 'checking') return <span className={base + 'animate-pulse bg-gray-300'} />;
  return <span className={base + 'border border-gray-300'} />; // opptatt: hul
}

function ResultRow({ r, conf, big }) {
  const { useI18n, useCart, nok, Btn, Spinner, CheckIcon } = NS.ui;
  const { t } = useI18n();
  useCart(); // re-render når vognen endres (inCart-status)
  const st = statusFor(r, conf);
  const inCart = NS.store.hasDomain(r.domain);
  const inTransfer = NS.store.hasTransfer(r.domain);
  const rdapSupported = !!(NS.data.rdapServers && NS.data.rdapServers[r.tld]);

  // Overføringspris (inkl. 1 års fornyelse) fra katalogen – vises i pillen
  // og sendes til transfer-dialogen.
  const transferPrice = (() => {
    const row = NS.data.tlds.find((tt) => tt.tld === r.tld);
    return row ? row.transfer : 0;
  })();

  // Opptatt domene → tilbud om overføring. Åpner en dialog som ber om EPP-koden
  // (autorisasjonskoden) før domenet legges i vognen.
  function openTransfer() {
    NS.bus.emit('transfer:open', { domain: r.domain, tld: r.tld, price: transferPrice });
  }

  function add() {
    NS.store.add({
      type: 'domain',
      domain: r.domain,
      years: 1,
      pricePerYear: st.price !== undefined ? st.price : r.price,
      premium: !!st.premium,
    });
    NS.bus.emit('domain:added', r.domain);
  }

  return (
    <div className={'flex items-center justify-between gap-3 px-4 transition-colors hover:bg-gray-50 ' + (big ? 'py-4' : 'py-3')}>
      <div className="flex min-w-0 items-center gap-2.5">
        <StatusDot kind={st.kind} />
        <span
          className={
            'truncate font-semibold ' +
            (big ? 'text-xl ' : 'text-base ') +
            (st.kind === 'taken' ? 'text-gray-400/70' : 'text-navy')
          }
        >
          {r.domain.slice(0, r.domain.indexOf('.'))}
          <span className={st.kind === 'taken' ? '' : 'text-brand'}>
            {r.domain.slice(r.domain.indexOf('.'))}
          </span>
        </span>
        {(st.kind === 'free' || st.kind === 'maybe') && st.premium ? (
          <span className="shrink-0 rounded-full bg-orange-100 px-2 py-0.5 font-mono text-[10px] uppercase tracking-wider text-orange-700">
            {t('common.premium')}
          </span>
        ) : null}
      </div>
      <div className="flex shrink-0 items-center">
        {st.kind === 'taken' ? (
          <div className="flex items-center gap-3.5">
            {inTransfer ? (
              <span className="flex items-center gap-1.5 rounded-full bg-emerald-50 px-3 py-1.5 text-sm font-medium text-emerald-700">
                <CheckIcon className="h-4 w-4" /> {t('common.inCart')}
              </span>
            ) : (
              <button
                onClick={openTransfer}
                className="flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full px-3.5 py-1.5 text-sm font-semibold text-navy ring-1 ring-gray-300 transition-all hover:bg-navy hover:text-white hover:ring-navy"
              >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden className="h-4 w-4">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3 12h12M10 7l5 5-5 5M21 4v16" />
                </svg>
                {t('domains.transfer')} {nok(transferPrice)}{t('common.perYear')}
              </button>
            )}
            {rdapSupported ? (
              <button
                onClick={() => NS.bus.emit('rdap:open', r.domain)}
                aria-label={t('rdap.title')}
                title={t('rdap.title')}
                className="cursor-pointer text-gray-300 transition-colors hover:text-navy"
              >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="h-[18px] w-[18px]">
                  <circle cx="12" cy="12" r="9" />
                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 11v5M12 8h.01" />
                </svg>
              </button>
            ) : null}
          </div>
        ) : st.kind === 'checking' ? (
          <Spinner />
        ) : inCart ? (
          <span className="flex items-center gap-1.5 rounded-full bg-emerald-50 px-3.5 py-1.5 text-sm font-medium text-emerald-700">
            <CheckIcon className="h-4 w-4" /> {t('common.inCart')}
          </span>
        ) : (
          <button
            onClick={add}
            className="cursor-pointer rounded-full px-3.5 py-1.5 text-sm font-semibold text-brand ring-1 ring-emerald-600/30 transition-all hover:bg-brand hover:text-white hover:ring-brand"
          >
            {nok(st.price)}{t('common.perYear')} <span aria-hidden className="ml-0.5">+</span>
          </button>
        )}
      </div>
    </div>
  );
}

/* Hosting-upsell som dialog: dukker opp når et domene legges i vognen.
   WordPress er standardfane; full plan-info så valget blir informert.
   Rendres på App-nivå (lytter selv på 'domain:added'). */
function UpsellDialog() {
  const { useI18n, nok, Btn, CheckIcon, MonoLabel, localName } = NS.ui;
  const { t, lang } = useI18n();
  const [domain, setDomain] = useState(null);
  const [group, setGroup] = useState('wordpress');
  const [addedId, setAddedId] = useState(null);

  useEffect(() => {
    const open = (d) => {
      setDomain(d);
      setGroup('wordpress');
      setAddedId(null);
      NS.bus.emit('upsell:shown'); // modalen tar over → skjul evt. checkout-toast
    };
    // Auto-trigger når et domene legges til: hopp over hvis kunden har valgt
    // "ikke spør igjen" for denne ordren – men nudge fortsatt mot kassen.
    const autoOpen = (d) => {
      if (NS.store.upsellDismissed()) { NS.bus.emit('checkout:nudge', { name: d }); return; }
      open(d);
    };
    const off1 = NS.bus.on('domain:added', autoOpen);
    const off2 = NS.bus.on('upsell:open', open); // eksplisitt fra "Legg til webhotell" – alltid
    return () => { off1(); off2(); };
  }, []);

  // Lukk uten hosting-kjøp → nudge for domenet som nettopp ble lagt til.
  // stopAsking=true demper auto-upsellen ut resten av ordren.
  function dismiss(stopAsking) {
    if (stopAsking) NS.store.dismissUpsell();
    setDomain((d) => {
      if (d) NS.bus.emit('checkout:nudge', { name: d });
      return null;
    });
  }

  useEffect(() => {
    if (!domain) return;
    const onKey = (e) => { if (e.key === 'Escape') dismiss(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [domain]);

  if (!domain) return null;

  const tabs = [
    NS.data.productGroups.find((g) => g.id === 'wordpress'),
    NS.data.productGroups.find((g) => g.id === 'webhotell'),
  ];
  const products = NS.data.products.filter((p) => p.group === group);

  function add(p) {
    NS.store.add({
      type: 'product',
      productId: p.id,
      name: p.name,
      group: p.group,
      cycle: 'monthly',
      monthly: p.monthly,
      domain: { mode: 'cart', name: domain },
    });
    setAddedId(p.id);
    setTimeout(() => {
      setDomain(null);
      NS.bus.emit('checkout:nudge', { name: p.name });
    }, 900);
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-navy/30 backdrop-blur-sm" onClick={() => dismiss()} />
      <div className="fade-up relative max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-2xl bg-white/95 p-6 shadow-[0_24px_80px_-20px_rgba(16,185,129,0.4)] ring-1 ring-gray-200 backdrop-blur-md">
        <div className="flex items-start justify-between gap-4">
          <div>
            <h2 className="text-xl font-bold text-navy">{t('domains.upsell', { domain })}</h2>
            <p className="mt-1 text-sm text-gray-500">{t('upsell.hint')}</p>
          </div>
          <button
            onClick={() => dismiss()}
            className="cursor-pointer rounded-md p-1 text-gray-400 hover:text-navy"
            aria-label="Close"
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="h-6 w-6">
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="mt-4 inline-flex gap-1 rounded-full bg-gray-100 p-1 ring-1 ring-gray-200">
          {tabs.map((g) => (
            <button
              key={g.id}
              onClick={() => setGroup(g.id)}
              className={
                'cursor-pointer rounded-full px-4 py-1.5 text-sm font-semibold transition-colors ' +
                (group === g.id ? 'bg-white text-navy shadow-sm' : 'text-gray-500 hover:text-navy')
              }
            >
              {t(g.labelKey)}
            </button>
          ))}
        </div>

        <div className="mt-5 grid gap-3 sm:grid-cols-3">
          {products.map((p) => {
            const hot = !!p.badge;
            return (
              <div
                key={p.id}
                className={
                  'relative flex flex-col rounded-xl p-4 pt-5 ring-1 transition-all ' +
                  (addedId === p.id || hot
                    ? 'bg-emerald-50/70 ring-emerald-500/40 shadow-[0_12px_40px_-14px_rgba(16,185,129,0.45)]'
                    : 'bg-white ring-gray-200 hover:ring-gray-300')
                }
              >
                {p.badge ? (
                  <div className="absolute -top-2.5 left-4 rounded-full bg-brand px-2.5 py-0.5">
                    <MonoLabel className="text-[9px] text-white">{localName(p.badge, lang)}</MonoLabel>
                  </div>
                ) : null}
                <div className="text-lg font-bold text-navy">{p.name}</div>
                <MonoLabel className="mt-0.5 text-[9px] text-gray-400">{p.sub}</MonoLabel>
                <div className="mt-2 flex items-baseline gap-1">
                  <span className="text-2xl font-bold tracking-tight text-navy">{nok(p.monthly)}</span>
                  <span className="text-sm text-gray-500">{t('common.perMonth')}</span>
                </div>
                <ul className="mt-3 flex-1 space-y-1.5">
                  {(p.features[lang] || p.features.no).map((f, i) => (
                    <li key={i} className="flex items-start gap-1.5 text-xs text-gray-700">
                      <CheckIcon className="mt-px h-3.5 w-3.5 shrink-0 text-brand" />
                      {f}
                    </li>
                  ))}
                </ul>
                <button
                  onClick={() => add(p)}
                  disabled={!!addedId}
                  className={
                    'mt-4 w-full cursor-pointer rounded-full px-3 py-2 text-sm font-semibold transition-all disabled:cursor-default ' +
                    (addedId === p.id
                      ? 'bg-emerald-100 text-emerald-700'
                      : hot
                      ? 'bg-brand text-white hover:bg-emerald-700'
                      : 'text-brand ring-1 ring-emerald-600/30 hover:bg-brand hover:text-white hover:ring-brand')
                  }
                >
                  {addedId === p.id ? t('upsell.added') : t('common.select')}
                </button>
              </div>
            );
          })}
        </div>

        <div className="mt-5 flex flex-col items-center gap-2">
          <button
            onClick={() => dismiss()}
            className="cursor-pointer text-sm text-gray-500 underline-offset-2 transition-colors hover:text-navy hover:underline"
          >
            {t('upsell.skip')}
          </button>
          <button
            onClick={() => dismiss(true)}
            className="cursor-pointer text-xs text-gray-400 underline-offset-2 transition-colors hover:text-gray-600 hover:underline"
          >
            {t('upsell.dontAskAgain')}
          </button>
        </div>
      </div>
    </div>
  );
}

/* "Se eier": RDAP-eieroppslag som dialog. Åpnes via bussen ('rdap:open' med
   domenenavn) fra en opptatt resultatrad. Henter klientside (NS.api.rdap, rett
   mot registret) og viser det registret faktisk gir ut – innehaver er ofte
   skjult av personvernhensyn. Rendres på App-nivå. */
function RdapDialog() {
  const { useI18n, useCart, Spinner, MonoLabel, CheckIcon } = NS.ui;
  const { t } = useI18n();
  useCart(); // oppdater "i handlevognen"-knappen når vognen endres
  const [domain, setDomain] = useState(null);
  const [data, setData] = useState(null); // null = laster

  useEffect(() => NS.bus.on('rdap:open', (d) => { setDomain(d); setData(null); }), []);

  useEffect(() => {
    if (!domain) return;
    let stale = false;
    NS.api.rdap(domain).then((r) => { if (!stale) setData(r); });
    const onKey = (e) => { if (e.key === 'Escape') setDomain(null); };
    window.addEventListener('keydown', onKey);
    return () => { stale = true; window.removeEventListener('keydown', onKey); };
  }, [domain]);

  if (!domain) return null;

  const close = () => setDomain(null);
  const fmtDate = (s) => (typeof s === 'string' && s.length >= 10 ? s.slice(0, 10) : null);

  function transfer() {
    const dot = domain.indexOf('.');
    const tld = dot > 0 ? domain.slice(dot + 1) : '';
    const row = NS.data.tlds.find((tt) => tt.tld === tld);
    close();
    NS.bus.emit('transfer:open', { domain, tld, price: row ? row.transfer : 0 });
  }

  // Navn + org.nr (når registret oppgir det) på samme linje.
  const withOrg = (name, orgNo) =>
    name ? (orgNo ? name + ' · ' + t('rdap.orgNo') + ' ' + orgNo : name) : null;

  // [etikett, verdi, erInnehaver] – tomme felt vises som "skjult"/"—".
  const rows = data && data.found ? [
    [t('rdap.holder'), withOrg(data.registrant, data.registrantOrgNo), true],
    [t('rdap.registrar'), withOrg(data.registrar, data.registrarOrgNo), false],
    [t('rdap.status'), (data.statuses || []).join(', ') || null, false],
    [t('rdap.created'), fmtDate(data.created), false],
    [t('rdap.updated'), fmtDate(data.updated), false],
    [t('rdap.expires'), fmtDate(data.expires), false],
    [t('rdap.nameservers'), (data.nameservers || []).join(' · ') || null, false],
  ] : [];

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-navy/30 backdrop-blur-sm" onClick={close} />
      <div className="fade-up relative max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-2xl bg-white/95 p-6 shadow-[0_24px_80px_-20px_rgba(16,185,129,0.4)] ring-1 ring-gray-200 backdrop-blur-md">
        <div className="flex items-start justify-between gap-4">
          <div className="min-w-0">
            <MonoLabel className="text-brand">{t('rdap.source')}</MonoLabel>
            <h2 className="mt-1 truncate text-xl font-bold text-navy">{domain}</h2>
          </div>
          <button onClick={close} className="cursor-pointer rounded-md p-1 text-gray-400 hover:text-navy" aria-label="Close">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="h-6 w-6">
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="mt-4">
          {data === null ? (
            <div className="flex items-center gap-2 py-8 text-sm text-gray-500">
              <Spinner /> {t('common.checking')}
            </div>
          ) : !data.found ? (
            <p className="rounded-xl bg-gray-50 px-4 py-6 text-center text-sm text-gray-500">
              {data.error ? t('rdap.error') : t('rdap.none')}
            </p>
          ) : (
            <>
              <dl className="divide-y divide-gray-100">
                {rows.map(([label, value, isHolder]) => (
                  <div key={label} className="flex items-start justify-between gap-4 py-2.5">
                    <dt className="shrink-0 text-sm font-medium text-gray-500">{label}</dt>
                    <dd className={'min-w-0 break-words text-right text-sm ' + (value ? 'font-semibold text-navy' : 'italic text-gray-400')}>
                      {value || (isHolder ? t('rdap.redacted') : '—')}
                    </dd>
                  </div>
                ))}
              </dl>
              <p className="mt-3 text-xs text-gray-400">{t('rdap.privacy')}</p>
            </>
          )}
        </div>

        {domain.endsWith('.no') ? (
          <a
            href={noridLookup(domain)}
            target="_blank"
            rel="noopener noreferrer"
            className="mt-4 flex items-center justify-between gap-2 rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-sm font-medium text-navy transition-colors hover:border-emerald-300 hover:bg-emerald-50"
          >
            {t('rdap.norid')}
            <span aria-hidden>↗</span>
          </a>
        ) : null}

        <div className="mt-5">
          <button
            onClick={transfer}
            className="flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-full bg-brand px-4 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-emerald-700"
          >
            {NS.store.hasTransfer(domain)
              ? <><CheckIcon className="h-4 w-4" /> {t('common.inCart')}</>
              : t('rdap.transferCta')}
          </button>
        </div>
      </div>
    </div>
  );
}

/* Domeneoverføring: ber om EPP-/autorisasjonskoden før domenet legges i vognen.
   Åpnes via bussen ('transfer:open' med {domain, tld, price}) fra en opptatt
   resultatrad eller fra "Se mer"-dialogen. Oppdaterer koden hvis domenet alt
   ligger i vognen. Rendres på App-nivå. */
function TransferDialog() {
  const { useI18n, useCart, nok, Btn, MonoLabel } = NS.ui;
  const { t } = useI18n();
  useCart();
  const [info, setInfo] = useState(null); // {domain, tld, price}
  const [epp, setEpp] = useState('');

  useEffect(() => NS.bus.on('transfer:open', (i) => {
    const ex = NS.store.get().items.find((it) => it.type === 'transfer' && it.domain === i.domain);
    setInfo(i);
    setEpp((ex && ex.epp) || ''); // forhåndsutfyll hvis koden alt er lagt inn
  }), []);

  useEffect(() => {
    if (!info) return;
    const onKey = (e) => { if (e.key === 'Escape') setInfo(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [info]);

  if (!info) return null;
  const close = () => setInfo(null);

  function confirm() {
    const code = epp.trim() || undefined;
    const ex = NS.store.get().items.find((it) => it.type === 'transfer' && it.domain === info.domain);
    if (ex) NS.store.update(ex.id, { epp: code });
    else NS.store.add({ type: 'transfer', domain: info.domain, tld: info.tld, price: info.price, epp: code });
    close();
    NS.bus.emit('checkout:nudge', { name: info.domain });
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-navy/30 backdrop-blur-sm" onClick={close} />
      <div className="fade-up relative w-full max-w-md rounded-2xl bg-white/95 p-6 shadow-[0_24px_80px_-20px_rgba(16,185,129,0.4)] ring-1 ring-gray-200 backdrop-blur-md">
        <div className="flex items-start justify-between gap-4">
          <div className="min-w-0">
            <MonoLabel className="text-brand">{t('transfer.label')}</MonoLabel>
            <h2 className="mt-1 truncate text-xl font-bold text-navy">{info.domain}</h2>
          </div>
          <button onClick={close} className="cursor-pointer rounded-md p-1 text-gray-400 hover:text-navy" aria-label="Close">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="h-6 w-6">
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <p className="mt-3 text-sm text-gray-600">{t('transfer.eppHint')}</p>

        <label className="mt-4 block">
          <span className="mb-1 block text-sm font-medium text-navy">{t('transfer.eppLabel')}</span>
          <input
            autoFocus
            value={epp}
            onChange={(e) => setEpp(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') confirm(); }}
            placeholder={t('transfer.eppPlaceholder')}
            autoCapitalize="none"
            spellCheck="false"
            className="w-full rounded-lg border border-gray-300 px-3 py-2.5 font-mono text-sm text-navy outline-none focus:border-brand"
          />
        </label>
        <p className="mt-2 text-xs text-gray-400">{t('transfer.eppLater')}</p>

        <div className="mt-5 flex items-center justify-between gap-3">
          <span className="text-sm text-gray-500">
            {t('cart.domainTransfer')} · <span className="font-semibold text-navy">{nok(info.price)}</span>
          </span>
          <Btn variant="brand" onClick={confirm}>{t('common.addToCart')}</Btn>
        </div>
      </div>
    </div>
  );
}

/* Hovedsøket – brukes både på forsiden (hero) og på domenesiden. */
function LiveSearch({ initialQuery }) {
  const { useI18n, AISearchBox, MailIcon } = NS.ui;
  const { t, lang } = useI18n();
  const [q, setQ] = useState(initialQuery || '');
  const dq = useDebounced(q, 200);
  const results = useSearch(dq);
  const conf = useConfirmations(results ? results.results : null);

  const chips = ['minbedrift', 'kaffebar-oslo', 'fjellhytte'];

  return (
    <AISearchBox
      value={q}
      onChange={setQ}
      placeholder={t('home.searchPlaceholder')}
      chips={chips}
      onChip={setQ}
      label={t('common.search')}
    >
      {results ? (
        <div>
          {/* Konverteringsdetalj: vis den faktiske adressen kunden får. */}
          <div className="flex items-center gap-2 border-b border-emerald-100 bg-emerald-50 px-4 py-2.5 text-sm font-medium text-emerald-800">
            <MailIcon className="h-4 w-4 shrink-0" />
            <span className="min-w-0 truncate">
              {t('domains.emailStrip1')}{' '}
              <span className="font-bold">
                {(lang === 'no' ? 'post@' : 'you@') + results.results[0].domain}
              </span>{' '}
              {t('domains.emailStrip2')}
            </span>
          </div>
          <div className="divide-y divide-gray-100">
            {results.results.map((r, i) => (
              <ResultRow key={r.domain} r={r} conf={conf} big={i === 0} />
            ))}
          </div>
        </div>
      ) : null}
    </AISearchBox>
  );
}

// Gjenbrukbar enkelt-domene-velger for hosting-flyten ("registrer nytt").
function DomainPicker({ onPick, picked }) {
  const { useI18n, nok, Btn, Spinner, CheckIcon } = NS.ui;
  const { t } = useI18n();
  const [q, setQ] = useState('');
  const dq = useDebounced(q, 250);
  const results = useSearch(dq);
  const conf = useConfirmations(results ? results.results : null);

  if (picked) {
    return (
      <div className="flex items-center justify-between rounded-lg border border-brand bg-emerald-50 px-3 py-2.5">
        <span className="flex items-center gap-2 text-sm font-semibold text-navy">
          <CheckIcon className="h-4 w-4 text-brand" /> {picked.name}
          <span className="font-normal text-gray-500">{nok(picked.price)}{t('common.perYear')}</span>
        </span>
        <button onClick={() => onPick(null)} className="cursor-pointer text-xs text-gray-500 hover:text-navy">
          {t('checkout.change')}
        </button>
      </div>
    );
  }

  return (
    <div>
      <input
        value={q}
        onChange={(e) => setQ(e.target.value)}
        placeholder={t('domains.searchPlaceholder')}
        autoCapitalize="none"
        spellCheck="false"
        className="w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm text-navy outline-none focus:border-brand"
      />
      {results ? (
        <div className="mt-2 max-h-56 divide-y divide-gray-50 overflow-y-auto rounded-lg border border-gray-200 bg-white">
          {results.results.map((r) => {
            const st = statusFor(r, conf);
            return (
              <div key={r.domain} className="flex items-center justify-between px-3 py-2">
                <span className="text-sm font-semibold text-navy">{r.domain}</span>
                {st.kind === 'taken' ? (
                  <span className="text-xs text-gray-400">{t('common.taken')}</span>
                ) : st.kind === 'checking' ? (
                  <Spinner />
                ) : (
                  <span className="flex items-center gap-2">
                    <span className="text-xs font-bold text-navy">{nok(st.price)}{t('common.perYear')}</span>
                    <Btn
                      variant="brand"
                      className="px-2.5 py-1 text-xs"
                      onClick={() => onPick({ name: r.domain, price: st.price })}
                    >
                      {t('common.select')}
                    </Btn>
                  </span>
                )}
              </div>
            );
          })}
        </div>
      ) : null}
    </div>
  );
}

function DomainsFlow() {
  const { useI18n, MonoLabel, TrustBar } = NS.ui;
  const { t } = useI18n();
  const initialQuery = useMemo(() => {
    const v = sessionStorage.getItem('stworder.q') || '';
    sessionStorage.removeItem('stworder.q');
    return v;
  }, []);

  return (
    <div>
      {/* Nordlys-hero med live-søk i sentrum – domenesøk er butikkens inngang. */}
      <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('domains.heroLabel')}</MonoLabel>
          <h1 className="fade-up fade-up-1 font-display text-4xl font-bold leading-tight text-navy sm:text-6xl">
            {t('domains.heroTitleA')}{' '}
            <span className="bg-gradient-to-r from-emerald-600 to-lime-500 bg-clip-text text-transparent">
              {t('domains.heroTitleB')}
            </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('domains.heroSubtitle')}
          </p>
          <div className="fade-up fade-up-3 mt-9">
            <LiveSearch initialQuery={initialQuery} />
          </div>
          <TrustBar className="fade-up fade-up-4 mt-8" />
        </div>
      </section>
    </div>
  );
}

NS.flows = NS.flows || {};
NS.flows.Domains = DomainsFlow;
NS.flows.DomainPicker = DomainPicker;
NS.flows.LiveSearch = LiveSearch;
NS.flows.UpsellDialog = UpsellDialog;
NS.flows.RdapDialog = RdapDialog;
NS.flows.TransferDialog = TransferDialog;
