// VPS-flyt: plan → OS/lokasjon/vertsnavn → handlevogn. Ingen domenesteg.
import React, { useState } from 'react';

const NS = window.STWORDER;

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

function Field({ label, hint, children }) {
  return (
    <label className="block">
      <div className="mb-1.5 text-sm font-semibold text-navy">{label}</div>
      {children}
      {hint ? <p className="mt-1.5 text-xs text-gray-500">{hint}</p> : null}
    </label>
  );
}

function VpsConfigurator({ plan }) {
  const { useI18n, nok, Btn, StepHeading, localName } = NS.ui;
  const { t, lang } = useI18n();

  const [os, setOs] = useState(NS.data.vpsOs[0]);
  const [loc, setLoc] = useState(NS.data.vpsLocations[0].id);
  const [hostname, setHostname] = useState('');
  const [cycle, setCycle] = useState('monthly');

  const hostnameOk = hostname.trim() === '' || HOSTNAME_RE.test(hostname.trim());
  const due = NS.store.cyclePrice(plan.monthly, cycle);
  const location = NS.data.vpsLocations.find((l) => l.id === loc);

  function add() {
    NS.store.add({
      type: 'vps',
      planId: plan.id,
      name: plan.name,
      cycle,
      monthly: plan.monthly,
      os,
      location: loc,
      hostname: hostname.trim() || null,
    });
    NS.bus.emit('cart:open');
  }

  const selectCls = 'w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-sm text-navy outline-none focus:border-brand';

  return (
    <section className="mt-10">
      <StepHeading n={2}>{t('vps.step2')} – {plan.name}</StepHeading>
      <div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
        <div className="grid gap-5 sm:grid-cols-2">
          <Field label={t('vps.os')}>
            <select value={os} onChange={(e) => setOs(e.target.value)} className={selectCls}>
              {NS.data.vpsOs.map((o) => <option key={o} value={o}>{o}</option>)}
            </select>
          </Field>
          <Field label={t('vps.location')}>
            <select value={loc} onChange={(e) => setLoc(e.target.value)} className={selectCls}>
              {NS.data.vpsLocations.map((l) => (
                <option key={l.id} value={l.id}>{localName(l.name, lang)}</option>
              ))}
            </select>
          </Field>
          <Field label={t('vps.hostname')} hint={t('vps.hostnameHint')}>
            <input
              value={hostname}
              onChange={(e) => setHostname(e.target.value)}
              placeholder="server1.mittdomene.no"
              autoCapitalize="none"
              spellCheck="false"
              className={selectCls + (hostnameOk ? '' : ' border-red-400')}
            />
          </Field>
          <Field label={t('hosting.cycle')}>
            <select value={cycle} onChange={(e) => setCycle(e.target.value)} className={selectCls}>
              <option value="monthly">{t('hosting.cycleMonthly')} – {nok(plan.monthly)}{t('common.perMonth')}</option>
              <option value="annually">{t('hosting.cycleAnnually')} – {nok(plan.monthly * 10)}{t('common.perYear')} ({t('hosting.cycleAnnualNote')})</option>
            </select>
          </Field>
        </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={!hostnameOk}>
            {t('common.addToCart')} <span aria-hidden>→</span>
          </Btn>
        </div>
      </div>
    </section>
  );
}

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

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

  return (
    <div>
      <PageHero title={t('vps.title')} />
      <div className="mx-auto max-w-6xl px-4 py-12">
      <section>
        <StepHeading n={1}>{t('vps.step1')}</StepHeading>
        <div className="grid gap-6 pt-3 sm:grid-cols-2 lg:grid-cols-4">
          {NS.data.vpsPlans.map((p) => (
            <ProductCard
              key={p.id}
              badge={p.badge ? localName(p.badge, lang) : null}
              tone="orange"
              featured={!!p.badge}
              title={p.name}
              sub={'EPYC 9275F · KVM'}
              features={[
                p.vcpu + ' vCPU',
                p.ram + ' GB RAM',
                p.disk + ' GB NVMe',
                t('vps.traffic'),
              ]}
              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 ? <VpsConfigurator key={selected.id} plan={selected} /> : null}
      </div>
    </div>
  );
}

NS.flows = NS.flows || {};
NS.flows.Vps = VpsFlow;
