// Kasse: e-post først (skiller ny/eksisterende kunde), så betalingsmåte,
// så fullfør. Oppsummering alltid synlig. I produksjon kaller dette
// storeapi → whmcs-api (AddClient/AddOrder/CreateSsoToken).
import React, { useState } from 'react';

const NS = window.STWORDER;

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

function Field({ label, span2, children }) {
  return (
    <label className={'block ' + (span2 ? 'sm:col-span-2' : '')}>
      <div className="mb-1.5 text-sm font-semibold text-navy">{label}</div>
      {children}
    </label>
  );
}

function AccountStep({ account, setAccount }) {
  const { useI18n, Btn, Spinner, CheckIcon } = NS.ui;
  const { t } = useI18n();

  const [stage, setStage] = useState('email'); // email | login | register
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [busy, setBusy] = useState(false);
  const [reg, setReg] = useState({
    firstName: '', lastName: '', company: '', address: '',
    zip: '', city: '', country: 'Norge', phone: '',
  });

  async function lookup() {
    if (!/^\S+@\S+\.\S+$/.test(email)) return;
    setBusy(true);
    const r = await NS.api.customerLookup(email);
    setBusy(false);
    setStage(r.exists ? 'login' : 'register');
  }

  async function doLogin() {
    setBusy(true);
    const r = await NS.api.login(email, password);
    setBusy(false);
    if (r.ok) setAccount({ kind: 'existing', email: r.email, name: r.name });
  }

  const regOk = reg.firstName && reg.lastName && reg.address && reg.zip && reg.city && reg.phone;
  function doRegister() {
    setAccount({ kind: 'new', email: email.trim().toLowerCase(), details: reg });
  }

  if (account) {
    return (
      <div className="flex items-center justify-between rounded-lg border border-brand bg-emerald-50 px-4 py-3">
        <span className="flex items-center gap-2 text-sm font-semibold text-navy">
          <CheckIcon className="h-5 w-5 text-brand" />
          {account.kind === 'existing' ? t('checkout.loggedInAs') + ' ' : ''}{account.email}
        </span>
        <button
          onClick={() => { setAccount(null); setStage('email'); setPassword(''); }}
          className="cursor-pointer text-xs text-gray-500 hover:text-navy"
        >
          {t('checkout.change')}
        </button>
      </div>
    );
  }

  return (
    <div>
      <p className="mb-3 text-sm text-gray-600">{t('checkout.emailFirst')}</p>
      <div className="flex gap-2">
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') lookup(); }}
          placeholder={t('checkout.email')}
          disabled={stage !== 'email'}
          autoComplete="email"
          className={inputCls + ' disabled:bg-gray-50 disabled:text-gray-500'}
        />
        {stage === 'email' ? (
          <Btn variant="brand" onClick={lookup} disabled={busy || !/^\S+@\S+\.\S+$/.test(email)}>
            {busy ? <Spinner className="border-white/40 border-t-white" /> : null} {t('common.continue')}
          </Btn>
        ) : (
          <Btn variant="ghost" onClick={() => { setStage('email'); setPassword(''); }}>
            {t('checkout.change')}
          </Btn>
        )}
      </div>

      {stage === 'login' ? (
        <div className="mt-4 rounded-lg border border-gray-200 bg-gray-50 p-4">
          <p className="mb-3 text-sm font-medium text-navy">{t('checkout.welcomeBack')}</p>
          <div className="flex gap-2">
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') doLogin(); }}
              placeholder={t('checkout.password')}
              autoFocus
              className={inputCls}
            />
            <Btn variant="brand" onClick={doLogin} disabled={busy || !password}>
              {busy ? <Spinner className="border-white/40 border-t-white" /> : null} {t('checkout.login')}
            </Btn>
          </div>
          <p className="mt-2 text-xs text-gray-400">{t('checkout.demoPassword')}</p>
        </div>
      ) : null}

      {stage === 'register' ? (
        <div className="mt-4 rounded-lg border border-gray-200 bg-gray-50 p-4">
          <p className="mb-3 text-sm font-medium text-navy">{t('checkout.newCustomer')}</p>
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label={t('checkout.firstName')}>
              <input value={reg.firstName} onChange={(e) => setReg({ ...reg, firstName: e.target.value })} autoComplete="given-name" className={inputCls} />
            </Field>
            <Field label={t('checkout.lastName')}>
              <input value={reg.lastName} onChange={(e) => setReg({ ...reg, lastName: e.target.value })} autoComplete="family-name" className={inputCls} />
            </Field>
            <Field label={t('checkout.company')} span2>
              <input value={reg.company} onChange={(e) => setReg({ ...reg, company: e.target.value })} autoComplete="organization" className={inputCls} />
            </Field>
            <Field label={t('checkout.address')} span2>
              <input value={reg.address} onChange={(e) => setReg({ ...reg, address: e.target.value })} autoComplete="street-address" className={inputCls} />
            </Field>
            <Field label={t('checkout.zip')}>
              <input value={reg.zip} onChange={(e) => setReg({ ...reg, zip: e.target.value })} autoComplete="postal-code" className={inputCls} />
            </Field>
            <Field label={t('checkout.city')}>
              <input value={reg.city} onChange={(e) => setReg({ ...reg, city: e.target.value })} autoComplete="address-level2" className={inputCls} />
            </Field>
            <Field label={t('checkout.country')}>
              <select value={reg.country} onChange={(e) => setReg({ ...reg, country: e.target.value })} className={inputCls}>
                {NS.data.countries.map((c) => <option key={c} value={c}>{c}</option>)}
              </select>
            </Field>
            <Field label={t('checkout.phone')}>
              <input value={reg.phone} onChange={(e) => setReg({ ...reg, phone: e.target.value })} autoComplete="tel" className={inputCls} />
            </Field>
          </div>
          <Btn variant="brand" className="mt-4" onClick={doRegister} disabled={!regOk}>
            {t('common.continue')}
          </Btn>
        </div>
      ) : null}
    </div>
  );
}

function PaymentStep({ method, setMethod }) {
  const { useI18n, localName } = NS.ui;
  const { t, lang } = useI18n();
  return (
    <div className="grid gap-3 sm:grid-cols-2">
      {NS.data.paymentMethods.map((m) => (
        <button
          key={m.id}
          onClick={() => setMethod(m.id)}
          className={
            'flex cursor-pointer items-center gap-3 rounded-xl border p-4 text-left transition-colors ' +
            (method === m.id ? 'border-brand bg-emerald-50' : 'border-gray-200 bg-white hover:border-gray-300')
          }
        >
          <span
            className={
              'flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 ' +
              (method === m.id ? 'border-brand' : 'border-gray-300')
            }
          >
            {method === m.id ? <span className="h-2.5 w-2.5 rounded-full bg-brand" /> : null}
          </span>
          <span className="text-sm font-semibold text-navy">{localName(m.name, lang)}</span>
        </button>
      ))}
    </div>
  );
}

function CheckoutPage() {
  const { useI18n, useCart, nok, Btn, Spinner, StepHeading, PageHero, CartItems } = NS.ui;
  const { t } = useI18n();
  const cart = useCart();

  const [account, setAccount] = useState(null);
  const [method, setMethod] = useState(null);
  const [placing, setPlacing] = useState(false);
  const [placeError, setPlaceError] = useState(false);

  async function place() {
    setPlacing(true);
    setPlaceError(false);
    try {
      const result = await NS.api.checkout({
        customer: account,
        items: cart.items,
        paymentMethod: method,
      });
      sessionStorage.setItem('stworder.receipt', JSON.stringify(result));
      NS.store.clear();
      location.hash = '#/kvittering';
    } catch (e) {
      setPlaceError(true);
      setPlacing(false);
    }
  }

  if (cart.items.length === 0) {
    return (
      <div className="mx-auto max-w-6xl px-4 py-20 text-center">
        <p className="mb-4 text-gray-500">{t('cart.empty')}</p>
        <Btn variant="brand" onClick={() => { location.hash = '#/domener'; }}>
          {t('cart.emptyCta')}
        </Btn>
      </div>
    );
  }

  const canPlace = account && method && !placing;

  return (
    <div>
      <PageHero title={t('checkout.title')} />
      <div className="mx-auto max-w-6xl px-4 py-12">
      <div className="grid items-start gap-8 lg:grid-cols-[1fr_380px]">
        <div className="space-y-10">
          <section>
            <StepHeading n={1}>{t('checkout.stepAccount')}</StepHeading>
            <div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
              <AccountStep account={account} setAccount={setAccount} />
            </div>
          </section>

          <section className={account ? '' : 'pointer-events-none opacity-40'}>
            <StepHeading n={2}>{t('checkout.stepPayment')}</StepHeading>
            <div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
              <PaymentStep method={method} setMethod={setMethod} />
              <p className="mt-4 text-xs text-gray-500">{t('checkout.secure')}</p>
            </div>
          </section>
        </div>

        <aside className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm lg:sticky lg:top-24">
          <h2 className="mb-2 text-lg font-bold text-navy">{t('checkout.summary')}</h2>
          <CartItems compact={false} upsell />
          <div className="mt-3 flex items-center justify-between border-t border-gray-200 pt-4">
            <span className="text-sm font-medium text-gray-600">{t('cart.dueToday')}</span>
            <span className="text-2xl font-extrabold text-navy">{nok(NS.store.cartDue())}</span>
          </div>
          <Btn variant="brand" className="mt-4 w-full py-3 text-base" onClick={place} disabled={!canPlace}>
            {placing ? (
              <>
                <Spinner className="border-white/40 border-t-white" /> {t('checkout.placing')}
              </>
            ) : (
              <>{t('checkout.place')} <span aria-hidden>→</span></>
            )}
          </Btn>
          {placeError ? (
            <p className="mt-3 rounded-lg bg-red-50 px-3 py-2 text-center text-sm text-red-700">
              {t('checkout.failed')}
            </p>
          ) : null}
          <button
            onClick={() => NS.store.clear()}
            className="mt-3 w-full cursor-pointer text-center text-sm text-gray-400 hover:text-red-600"
          >
            {t('cart.clear')}
          </button>
        </aside>
      </div>
      </div>
    </div>
  );
}

function ReceiptPage() {
  const { useI18n, Btn, CheckIcon } = NS.ui;
  const { t } = useI18n();
  let receipt = null;
  try { receipt = JSON.parse(sessionStorage.getItem('stworder.receipt') || 'null'); } catch (e) {}

  return (
    <div className="mx-auto max-w-lg px-4 py-16 text-center">
      <div className="mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100">
        <CheckIcon className="h-9 w-9 text-brand" />
      </div>
      <h1 className="mb-2 font-display text-4xl font-bold text-navy">{t('receipt.title')}</h1>
      {receipt ? (
        <p className="mb-1 text-sm text-gray-500">
          {t('receipt.order')}: <span className="font-mono text-base font-bold text-navy">{receipt.orderId}</span>
        </p>
      ) : null}
      <p className="mb-8 text-sm text-gray-500">{t('receipt.note')}</p>
      <Btn variant="navy" onClick={() => { location.hash = '#/'; }}>
        {t('receipt.back')}
      </Btn>
    </div>
  );
}

NS.pages = NS.pages || {};
NS.pages.Checkout = CheckoutPage;
NS.pages.Receipt = ReceiptPage;
