// Hosting-flyt: pakke først (beslutningen kunden kom for å ta),
// deretter domene (nytt / flytt / eget), så rett i handlevognen.
import React, { useState, useMemo } from 'react';

const NS = window.STWORDER;

const DOMAIN_RE = /^([a-z0-9åøæ-]+\.)+[a-zæøå]{2,}$/i;

function CycleOption({ active, onClick, title, price, note }) {
  return (
    <button
      onClick={onClick}
      className={
        'flex-1 cursor-pointer rounded-xl border p-4 text-left transition-colors ' +
        (active ? 'border-brand bg-emerald-50' : 'border-gray-200 bg-white hover:border-gray-300')
      }
    >
      <div className="flex items-center justify-between">
        <span className="text-sm font-semibold text-navy">{title}</span>
        {note ? (
          <span className="rounded bg-brand px-1.5 py-0.5 font-mono text-[10px] font-medium uppercase tracking-wider text-white">
            {note}
          </span>
        ) : null}
      </div>
      <div className="mt-1 text-lg font-extrabold text-navy">{price}</div>
    </button>
  );
}

function DomainModeOption({ active, onClick, title, children }) {
  return (
    <div
      className={
        'rounded-xl border transition-colors ' +
        (active ? 'border-brand bg-emerald-50/50' : 'border-gray-200 bg-white hover:border-gray-300')
      }
    >
      <button onClick={onClick} className="flex w-full cursor-pointer items-center gap-3 p-4 text-left">
        <span
          className={
            'flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 ' +
            (active ? 'border-brand' : 'border-gray-300')
          }
        >
          {active ? <span className="h-2.5 w-2.5 rounded-full bg-brand" /> : null}
        </span>
        <span className="text-sm font-semibold text-navy">{title}</span>
      </button>
      {active && children ? <div className="px-4 pb-4 pl-12">{children}</div> : null}
    </div>
  );
}

function Configurator({ product }) {
  const { useI18n, nok, Btn, StepHeading } = NS.ui;
  const { t } = useI18n();
  const DomainPicker = NS.flows.DomainPicker;

  const [cycle, setCycle] = useState('annually');
  const [mode, setMode] = useState('new');
  const [newDomain, setNewDomain] = useState(null); // {name, price}
  const [transferName, setTransferName] = useState('');
  const [ownName, setOwnName] = useState('');

  const transferPriceFor = (name) => {
    const tld = name.slice(name.lastIndexOf('.') + 1).toLowerCase();
    const row = NS.data.tlds.find((r) => r.tld === tld);
    return row ? row.transfer : 0;
  };

  const domainOk =
    mode === 'new' ? !!newDomain
    : mode === 'transfer' ? DOMAIN_RE.test(transferName.trim())
    : DOMAIN_RE.test(ownName.trim());

  const cyclePrice = NS.store.cyclePrice(product.monthly, cycle);
  const annualSaving = product.monthly * 2;

  const due =
    cyclePrice +
    (mode === 'new' && newDomain ? newDomain.price : 0) +
    (mode === 'transfer' && domainOk ? transferPriceFor(transferName.trim()) : 0);

  function add() {
    const domain =
      mode === 'new'
        ? { mode: 'new', name: newDomain.name, price: newDomain.price, years: 1 }
        : mode === 'transfer'
        ? { mode: 'transfer', name: transferName.trim().toLowerCase(), price: transferPriceFor(transferName.trim()) }
        : { mode: 'own', name: ownName.trim().toLowerCase() };
    NS.store.add({
      type: 'product',
      productId: product.id,
      name: product.name,
      group: product.group,
      cycle,
      monthly: product.monthly,
      domain,
    });
    NS.bus.emit('cart:open');
  }

  return (
    <section className="mt-10">
      <StepHeading n={2}>{t('hosting.step2')} – {product.name}</StepHeading>
      <div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm">

        <div className="mb-2 text-sm font-semibold text-navy">{t('hosting.cycle')}</div>
        <div className="flex flex-col gap-3 sm:flex-row">
          <CycleOption
            active={cycle === 'monthly'}
            onClick={() => setCycle('monthly')}
            title={t('hosting.cycleMonthly')}
            price={nok(product.monthly) + t('common.perMonth')}
          />
          <CycleOption
            active={cycle === 'annually'}
            onClick={() => setCycle('annually')}
            title={t('hosting.cycleAnnually')}
            price={nok(product.monthly * 10) + t('common.perYear')}
            note={t('hosting.save', { amount: nok(annualSaving) })}
          />
        </div>

        <div className="mb-2 mt-6 text-sm font-semibold text-navy">{t('hosting.domainQ')}</div>
        <div className="space-y-3">
          <DomainModeOption active={mode === 'new'} onClick={() => setMode('new')} title={t('hosting.domNew')}>
            <DomainPicker picked={newDomain} onPick={setNewDomain} />
          </DomainModeOption>

          <DomainModeOption active={mode === 'transfer'} onClick={() => setMode('transfer')} title={t('hosting.domTransfer')}>
            <input
              value={transferName}
              onChange={(e) => setTransferName(e.target.value)}
              placeholder={t('hosting.domainPlaceholder')}
              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"
            />
            <p className="mt-1.5 text-xs text-gray-500">{t('hosting.transferHint')}</p>
          </DomainModeOption>

          <DomainModeOption active={mode === 'own'} onClick={() => setMode('own')} title={t('hosting.domOwn')}>
            <input
              value={ownName}
              onChange={(e) => setOwnName(e.target.value)}
              placeholder={t('hosting.domainPlaceholder')}
              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"
            />
            <p className="mt-1.5 text-xs text-gray-500">{t('hosting.domOwnHint')}</p>
          </DomainModeOption>
        </div>

        <div className="mt-6 flex flex-col items-stretch justify-between gap-3 border-t border-gray-100 pt-5 sm:flex-row sm:items-center">
          <div>
            <div className="font-mono text-[11px] uppercase tracking-[0.18em] text-gray-400">{t('cart.dueToday')}</div>
            <div className="text-2xl font-extrabold text-navy">{nok(due)}</div>
          </div>
          <Btn variant="brand" className="px-6 py-3 text-base" onClick={add} disabled={!domainOk}>
            {t('common.addToCart')} <span aria-hidden>→</span>
          </Btn>
        </div>
      </div>
    </section>
  );
}

function HostingFlow() {
  const { useI18n, nok, ProductCard, StepHeading, PageHero, localName } = NS.ui;
  const { t, lang } = useI18n();
  const [group, setGroup] = useState('webhotell');
  const [selId, setSelId] = useState(null);

  const products = NS.data.products.filter((p) => p.group === group);
  const selected = NS.data.products.find((p) => p.id === selId) || null;

  return (
    <div>
      <PageHero title={t('hosting.title')} />
      <div className="mx-auto max-w-6xl px-4 py-12">
      <section>
        <StepHeading
          n={1}
          right={
            <div className="flex gap-2 rounded-lg bg-gray-200/70 p-1">
              {NS.data.productGroups.map((g) => (
                <button
                  key={g.id}
                  onClick={() => { setGroup(g.id); setSelId(null); }}
                  className={
                    'cursor-pointer rounded-md px-3 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>
          }
        >
          {t('hosting.step1')}
        </StepHeading>

        <div className="grid gap-6 pt-3 md:grid-cols-3">
          {products.map((p) => (
            <ProductCard
              key={p.id}
              badge={p.badge ? localName(p.badge, lang) : null}
              featured={!!p.badge}
              title={p.name}
              sub={p.sub}
              features={p.features[lang] || p.features.no}
              priceLabel={t('common.from')}
              price={nok(p.monthly) + t('common.perMonth')}
              cta={selId === p.id ? t('common.selected') : t('common.select')}
              onCta={() => setSelId(p.id)}
              selected={selId === p.id}
            />
          ))}
        </div>
      </section>

      {selected ? <Configurator key={selected.id} product={selected} /> : null}
      </div>
    </div>
  );
}

NS.flows = NS.flows || {};
NS.flows.Hosting = HostingFlow;
