'use client';

import { useState, useEffect, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { apiFetch } from '@/lib/api';
import {
  MapPin,
  Bell,
  Home,
  Clock,
  Calendar,
  MessageSquare,
  LogIn,
  LogOut,
  Check,
  Smartphone,
  Share2,
  AlertTriangle,
  Loader,
  ChevronRight,
} from 'lucide-react';

// ─── Hjälpare ───────────────────────────────────────────────────────────────
function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
  const base64  = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
  const raw     = atob(base64);
  return new Uint8Array([...raw].map(c => c.charCodeAt(0)));
}

function detectStandalone() {
  if (typeof window === 'undefined') return false;
  if (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) return true;
  // iOS Safari
  if (window.navigator && window.navigator.standalone === true) return true;
  return false;
}

function detectPlatform() {
  if (typeof navigator === 'undefined') return 'other';
  const ua = navigator.userAgent || '';
  if (/iPhone|iPad|iPod/i.test(ua)) return 'ios';
  if (/Android/i.test(ua))          return 'android';
  return 'other';
}

// ─── Steg-definition ────────────────────────────────────────────────────────
// 'welcome' → 'pwa-intro' (om ej standalone) → 'pwa-howto' (om valt) →
// 'location-prime' → 'notifications-prime' → 'checkin-intro' → 'auto-alarm' → 'done'
const STEPS = {
  WELCOME:             'welcome',
  PWA_INTRO:           'pwa-intro',
  PWA_HOWTO:           'pwa-howto',
  LOCATION_PRIME:      'location-prime',
  NOTIFICATIONS_PRIME: 'notifications-prime',
  CHECKIN_INTRO:       'checkin-intro',
  AUTO_ALARM:          'auto-alarm',
};

// Progress-procent per steg (välkomsten har ingen progressbar)
const PROGRESS = {
  [STEPS.PWA_INTRO]:           15,
  [STEPS.PWA_HOWTO]:           25,
  [STEPS.LOCATION_PRIME]:      45,
  [STEPS.NOTIFICATIONS_PRIME]: 60,
  [STEPS.CHECKIN_INTRO]:       85,
  [STEPS.AUTO_ALARM]:         100,
};

// Steg-etikett (1 av 3 etc.) — mappar huvudfaser
const STEP_LABEL = {
  [STEPS.PWA_INTRO]:           'Steg 1 av 3',
  [STEPS.PWA_HOWTO]:           'Steg 1 av 3',
  [STEPS.LOCATION_PRIME]:      'Steg 2 av 3',
  [STEPS.NOTIFICATIONS_PRIME]: 'Steg 2 av 3',
  [STEPS.CHECKIN_INTRO]:       'Steg 3 av 3',
  [STEPS.AUTO_ALARM]:          'Steg 3 av 3',
};

export default function OnboardingPage() {
  const router = useRouter();

  const [user, setUser]               = useState(null);
  const [isLoading, setIsLoading]     = useState(true);
  const [step, setStep]               = useState(STEPS.WELCOME);
  const [finishing, setFinishing]     = useState(false);

  // PWA
  const [isStandalone, setIsStandalone] = useState(false);
  const [platform, setPlatform]         = useState('other');

  // Auth + onboarding-status — vid mount
  useEffect(() => {
    let cancelled = false;
    const init = async () => {
      try {
        const r = await apiFetch('/api/auth/session');
        if (!r.ok) { router.replace('/login'); return; }
        const d = await r.json();
        if (!d.authenticated || d.user?.portalRole !== 'handlaggare') {
          router.replace('/login');
          return;
        }
        if (cancelled) return;
        setUser(d.user);

        // Om redan slutförd → skicka direkt till appen
        try {
          const or = await apiFetch('/api/handlaggare/onboarding');
          if (or.ok) {
            const od = await or.json();
            if (od.completed) { router.replace('/handlaggare'); return; }
          }
        } catch { /* tyst — fortsätt visa onboarding */ }

        setIsStandalone(detectStandalone());
        setPlatform(detectPlatform());
      } catch {
        router.replace('/login');
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    };
    init();
    return () => { cancelled = true; };
  }, [router]);

  const firstName = useMemo(() => (user?.name || '').split(' ')[0] || '', [user]);

  // ─── Stegnavigation ───────────────────────────────────────────────────────
  const goToNextAfterPwa = () => setStep(STEPS.LOCATION_PRIME);

  const handleStart = () => {
    // Om appen redan körs som installerad PWA — hoppa över hela PWA-fasen
    if (isStandalone) setStep(STEPS.LOCATION_PRIME);
    else              setStep(STEPS.PWA_INTRO);
  };

  // ─── Platsbehörighet ──────────────────────────────────────────────────────
  const requestLocation = async () => {
    if (typeof navigator === 'undefined' || !navigator.geolocation) {
      setStep(STEPS.NOTIFICATIONS_PRIME);
      return;
    }
    navigator.geolocation.getCurrentPosition(
      () => setStep(STEPS.NOTIFICATIONS_PRIME),
      () => setStep(STEPS.NOTIFICATIONS_PRIME), // användaren kan aktivera senare i inställningarna
      { enableHighAccuracy: false, timeout: 10000, maximumAge: 60000 }
    );
  };

  // ─── Notisbehörighet + push-prenumeration ────────────────────────────────
  const requestNotifications = async () => {
    try {
      if (typeof window === 'undefined' || !('Notification' in window)) {
        setStep(STEPS.CHECKIN_INTRO);
        return;
      }
      const permission = await Notification.requestPermission();
      if (permission === 'granted'
          && 'serviceWorker' in navigator
          && 'PushManager' in window) {
        try {
          const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';
          const reg      = await navigator.serviceWorker.register(`${basePath}/sw.js`);
          const existing = await reg.pushManager.getSubscription();
          if (!existing) {
            const vapidKey = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY || '';
            if (vapidKey) {
              const sub = await reg.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: urlBase64ToUint8Array(vapidKey),
              });
              await apiFetch('/api/push/subscribe', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ subscription: sub.toJSON() }),
              });
            }
          }
        } catch (err) {
          console.error('Push-prenumeration misslyckades:', err);
        }
      }
    } finally {
      setStep(STEPS.CHECKIN_INTRO);
    }
  };

  // ─── Slutför onboarding ───────────────────────────────────────────────────
  const finishOnboarding = async () => {
    setFinishing(true);
    try {
      await apiFetch('/api/handlaggare/onboarding', { method: 'POST' });
    } catch (e) {
      console.error('Kunde inte markera onboarding som slutförd:', e);
    }
    router.replace('/handlaggare');
  };

  // ─── Rendering ────────────────────────────────────────────────────────────
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <Loader className="w-6 h-6 text-indigo-600 animate-spin" />
      </div>
    );
  }

  // Välkomstskärmen har egen bakgrund (matchar login)
  if (step === STEPS.WELCOME) {
    return <WelcomeScreen firstName={firstName} onStart={handleStart} />;
  }

  return (
    <div className="min-h-screen bg-slate-50 flex flex-col">
      <StepHeader step={step} />
      <main className="flex-1 flex flex-col px-6 pt-2 pb-8 max-w-md mx-auto w-full">
        {step === STEPS.PWA_INTRO && (
          <PwaIntroScreen
            onContinue={() => setStep(STEPS.PWA_HOWTO)}
            onSkip={goToNextAfterPwa}
          />
        )}
        {step === STEPS.PWA_HOWTO && (
          <PwaHowtoScreen
            platform={platform}
            onDone={goToNextAfterPwa}
            onSkip={goToNextAfterPwa}
          />
        )}
        {step === STEPS.LOCATION_PRIME && (
          <LocationPrimeScreen
            onEnable={requestLocation}
            onSkip={() => setStep(STEPS.NOTIFICATIONS_PRIME)}
          />
        )}
        {step === STEPS.NOTIFICATIONS_PRIME && (
          <NotificationsPrimeScreen
            onEnable={requestNotifications}
            onSkip={() => setStep(STEPS.CHECKIN_INTRO)}
          />
        )}
        {step === STEPS.CHECKIN_INTRO && (
          <CheckinIntroScreen onNext={() => setStep(STEPS.AUTO_ALARM)} />
        )}
        {step === STEPS.AUTO_ALARM && (
          <AutoAlarmScreen onFinish={finishOnboarding} finishing={finishing} />
        )}
      </main>
    </div>
  );
}

// ─── Delade komponenter ─────────────────────────────────────────────────────

function StepHeader({ step }) {
  const pct   = PROGRESS[step] ?? 0;
  const label = STEP_LABEL[step] ?? '';
  return (
    <div className="w-full max-w-md mx-auto px-6 pt-6">
      {/* Liten brand-wordmark — håller kvar den känsla av "samma app som login" som
          välkomstskärmen etablerade, även när bakgrunden växlar till ljust. */}
      <div className="flex justify-center mb-5">
        <p className="text-xs leading-none tracking-tight select-none">
          <span style={{ fontWeight: 900, letterSpacing: '-0.03em', color: '#9ca3af' }}>TILLSYNS</span><span style={{ fontWeight: 300, letterSpacing: '-0.03em', color: '#9ca3af' }}>APPEN</span><span style={{ fontWeight: 900, letterSpacing: '-0.03em', color: '#9ca3af' }}>.</span>
        </p>
      </div>
      <div className="h-1 bg-slate-200 rounded-full overflow-hidden">
        <div
          className="h-full bg-indigo-600 transition-all duration-500"
          style={{ width: `${pct}%` }}
        />
      </div>
      {label && (
        <div className="mt-3 text-xs font-semibold tracking-wide uppercase text-indigo-600">
          {label}
        </div>
      )}
    </div>
  );
}

function FeatIcon({ children, variant = 'indigo' }) {
  const bg = variant === 'warn' ? 'bg-amber-50' : 'bg-indigo-50';
  const fg = variant === 'warn' ? 'text-amber-600' : 'text-indigo-600';
  return (
    <div className={`w-14 h-14 rounded-2xl flex items-center justify-center mx-auto mb-5 ${bg} ${fg}`}>
      {children}
    </div>
  );
}

function FeatureRow({ icon, title, body, variant = 'indigo' }) {
  const bg = variant === 'warn' ? 'bg-amber-50' : 'bg-indigo-50';
  const fg = variant === 'warn' ? 'text-amber-700' : 'text-indigo-600';
  return (
    <div className="flex items-start gap-3 bg-white border border-slate-200 rounded-xl p-3">
      <div className={`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 ${bg} ${fg}`}>
        {icon}
      </div>
      <div className="text-sm leading-snug">
        <strong className="font-semibold text-slate-900 mr-1">{title}</strong>
        <span className="text-slate-600">{body}</span>
      </div>
    </div>
  );
}

function PrimaryButton({ children, onClick, disabled = false }) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      className="w-full px-4 py-3 rounded-xl bg-indigo-600 text-white font-semibold text-[15px] hover:bg-indigo-700 active:bg-indigo-800 disabled:opacity-60 disabled:cursor-not-allowed transition-all duration-200 btn-portal-shadow btn-portal-handlaggare"
    >
      {children}
    </button>
  );
}

function SecondaryButton({ children, onClick }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="w-full px-4 py-3 rounded-xl bg-transparent text-slate-600 font-medium text-[14px] hover:text-slate-900 transition"
    >
      {children}
    </button>
  );
}

// ─── Skärmar ────────────────────────────────────────────────────────────────

// Liten logo för welcome-skärmen — samma SVG-clipboard som login men i mindre format,
// utan den fulla 3D-animationen. Knyter visuellt till login som man precis kom från.
function WelcomeLogo() {
  const iconSize = 80;
  return (
    <div className="flex flex-col items-center gap-2 mb-8">
      <svg
        width={iconSize}
        height={iconSize}
        viewBox="0 0 40 40"
        fill="none"
        aria-hidden="true"
        style={{
          filter:
            'drop-shadow(0 1px 1px rgba(0,0,0,0.18)) ' +
            'drop-shadow(0 6px 12px rgba(0,0,0,0.40)) ' +
            'drop-shadow(0 18px 32px rgba(0,0,0,0.42))',
        }}
      >
        <defs>
          <linearGradient id="welcomeBodyGrad" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" stopColor="#ffffff" stopOpacity="0.96"/>
            <stop offset="100%" stopColor="#ebebf2" stopOpacity="0.94"/>
          </linearGradient>
          <linearGradient id="welcomeTopHL" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" stopColor="#ffffff" stopOpacity="0.45"/>
            <stop offset="100%" stopColor="#ffffff" stopOpacity="0"/>
          </linearGradient>
          <clipPath id="welcomeBodyClip"><rect x="7" y="9" width="26" height="29" rx="7"/></clipPath>
        </defs>
        <rect x="7" y="9" width="26" height="29" rx="7" fill="url(#welcomeBodyGrad)"/>
        <g clipPath="url(#welcomeBodyClip)">
          <rect x="7" y="9" width="26" height="13" fill="url(#welcomeTopHL)"/>
        </g>
        <rect x="7" y="35" width="26" height="3" rx="3" fill="rgba(0,0,0,0.08)"/>
        <rect x="14" y="5" width="12" height="8" rx="4" fill="url(#welcomeBodyGrad)"/>
        <line x1="12" y1="19" x2="28" y2="19" stroke="rgba(79,70,229,0.36)" strokeWidth="1.7" strokeLinecap="round"/>
        <line x1="12" y1="25" x2="28" y2="25" stroke="rgba(79,70,229,0.36)" strokeWidth="1.7" strokeLinecap="round"/>
        <path d="M 12,31 L 18,31 L 21,34.5 L 29,25.5" stroke="rgba(79,70,229,0.78)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
      </svg>
      <h1 className="text-xl leading-none text-white" style={{ letterSpacing: '-0.03em' }}>
        <span style={{ fontWeight: 900 }}>TILLSYNS</span><span style={{ fontWeight: 300 }}>APPEN</span><span style={{ fontWeight: 900 }}>.</span>
      </h1>
      <p className="text-white/55 text-xs font-light italic" style={{ letterSpacing: '0.01em' }}>
        För en tryggare myndighetsutövning
      </p>
    </div>
  );
}

function WelcomeScreen({ firstName, onStart }) {
  return (
    <div
      className="min-h-screen flex items-center justify-center p-6"
      style={{
        background: `
          radial-gradient(ellipse 60% 50% at 18% 8%, rgba(99, 102, 241, 0.16) 0%, transparent 55%),
          radial-gradient(ellipse 55% 45% at 88% 92%, rgba(99, 102, 241, 0.08) 0%, transparent 55%),
          linear-gradient(165deg, #141726 0%, #0f1220 55%, #0a0c16 100%)
        `,
      }}
    >
      <div className="w-full max-w-md text-center text-white">
        <WelcomeLogo />
        <h2 className="text-[22px] font-extrabold mb-2">
          {firstName ? `Välkommen, ${firstName}` : 'Välkommen'}
        </h2>
        <p className="text-[14px] text-white/70 leading-relaxed mb-10 px-2">
          Kul att ha dig ombord. Innan du börjar jobba behöver vi göra några
          snabba inställningar — det tar cirka 3 minuter.
        </p>
        <button
          type="button"
          onClick={onStart}
          className="w-full px-4 py-3 rounded-xl bg-indigo-600 text-white font-semibold text-[15px] hover:bg-indigo-700 active:bg-indigo-800 transition-all duration-200 btn-portal-shadow btn-portal-handlaggare"
        >
          Kom igång
        </button>
      </div>
    </div>
  );
}

function PwaIntroScreen({ onContinue, onSkip }) {
  return (
    <>
      <FeatIcon>
        <Smartphone className="w-7 h-7" />
      </FeatIcon>
      <h2 className="text-[20px] font-extrabold text-center text-slate-900 mb-2">
        Lägg till på hemskärmen
      </h2>
      <p className="text-[14px] text-slate-600 text-center leading-relaxed mb-6">
        Tillsynsappen fungerar bäst som en installerad app — snabbare start,
        färre distraktioner och möjlighet att ta emot notiser i fält.
      </p>
      <div className="flex-1" />
      <div className="space-y-2">
        <PrimaryButton onClick={onContinue}>Visa hur jag gör</PrimaryButton>
        <SecondaryButton onClick={onSkip}>Jag har redan installerat</SecondaryButton>
      </div>
    </>
  );
}

function PwaHowtoScreen({ platform, onDone, onSkip }) {
  const [tab, setTab] = useState(platform === 'android' ? 'android' : 'ios');
  return (
    <>
      <h2 className="text-[20px] font-extrabold text-slate-900 mb-4 text-center">
        Så installerar du
      </h2>

      <div className="flex bg-slate-100 rounded-xl p-1 mb-5">
        <button
          type="button"
          onClick={() => setTab('ios')}
          className={`flex-1 py-2 text-sm font-semibold rounded-lg transition ${tab === 'ios' ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500'}`}
        >iPhone</button>
        <button
          type="button"
          onClick={() => setTab('android')}
          className={`flex-1 py-2 text-sm font-semibold rounded-lg transition ${tab === 'android' ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500'}`}
        >Android</button>
      </div>

      {tab === 'ios' ? (
        <div className="space-y-3">
          <HowtoStep n={1}>
            Tryck på <strong>delningsikonen</strong> <Share2 className="w-4 h-4 inline -mt-0.5" /> nere i Safari
          </HowtoStep>
          <HowtoStep n={2}>
            Välj <strong>&quot;Lägg till på hemskärmen&quot;</strong>
          </HowtoStep>
          <HowtoStep n={3}>
            Tryck <strong>&quot;Lägg till&quot;</strong> uppe till höger
          </HowtoStep>
        </div>
      ) : (
        <div className="space-y-3">
          <HowtoStep n={1}>
            Tryck på <strong>menyn</strong> (tre prickar) uppe till höger i Chrome
          </HowtoStep>
          <HowtoStep n={2}>
            Välj <strong>&quot;Installera app&quot;</strong> eller <strong>&quot;Lägg till på startskärmen&quot;</strong>
          </HowtoStep>
          <HowtoStep n={3}>
            Bekräfta <strong>&quot;Installera&quot;</strong>
          </HowtoStep>
        </div>
      )}

      <div className="mt-4 p-3 rounded-lg bg-indigo-50 text-[13px] text-indigo-900 leading-relaxed">
        Starta appen från hemskärmen nästa gång så hamnar du rakt där du slutade.
      </div>

      <div className="flex-1" />
      <div className="space-y-2 mt-6">
        <PrimaryButton onClick={onDone}>Jag har installerat</PrimaryButton>
        <SecondaryButton onClick={onSkip}>Hoppa över (rekommenderas ej)</SecondaryButton>
      </div>
    </>
  );
}

function HowtoStep({ n, children }) {
  return (
    <div className="flex items-start gap-3">
      <div className="w-7 h-7 rounded-full bg-indigo-600 text-white font-bold text-sm flex items-center justify-center flex-shrink-0">{n}</div>
      <div className="text-[14px] text-slate-700 leading-relaxed pt-0.5">{children}</div>
    </div>
  );
}

function LocationPrimeScreen({ onEnable, onSkip }) {
  return (
    <>
      <FeatIcon>
        <MapPin className="w-7 h-7" />
      </FeatIcon>
      <h2 className="text-[20px] font-extrabold text-center text-slate-900 mb-2">
        Aktivera platsdata
      </h2>
      <p className="text-[14px] text-slate-600 text-center leading-relaxed mb-5">
        Vi använder din plats i två situationer — båda för att stötta din
        arbetsdag.
      </p>

      <div className="space-y-2.5">
        <FeatureRow
          icon={<Home className="w-4 h-4" />}
          title="Påminnelse att checka in"
          body="När du är tillbaka på kontoret får du en diskret notis om att checka in efter tillsyn. Delas inte med någon."
        />
        <FeatureRow
          icon={<Clock className="w-4 h-4" />}
          title="Säkerhet vid försenad incheckning"
          body="Om du inte checkar in i tid efter en tillsyn delas din position med din chef för att hjälpa till vid eftersökning."
          variant="warn"
        />
      </div>

      <div className="flex-1" />
      <div className="space-y-2 mt-6">
        <PrimaryButton onClick={onEnable}>Aktivera platsdata</PrimaryButton>
        <SecondaryButton onClick={onSkip}>Senare</SecondaryButton>
      </div>
    </>
  );
}

function NotificationsPrimeScreen({ onEnable, onSkip }) {
  return (
    <>
      <FeatIcon>
        <Bell className="w-7 h-7" />
      </FeatIcon>
      <h2 className="text-[20px] font-extrabold text-center text-slate-900 mb-2">
        Aktivera notiser
      </h2>
      <p className="text-[14px] text-slate-600 text-center leading-relaxed mb-5">
        Få vänliga påminnelser och viktig information direkt i telefonen.
      </p>

      <div className="space-y-2.5">
        <FeatureRow
          icon={<Home className="w-4 h-4" />}
          title="Påminnelse att checka in"
          body="När du är tillbaka på arbetsplatsen"
        />
        <FeatureRow
          icon={<Calendar className="w-4 h-4" />}
          title="Morgondagens tillsyner"
          body="Sammanfattning kvällen innan"
        />
        <FeatureRow
          icon={<MessageSquare className="w-4 h-4" />}
          title="Viktiga meddelanden"
          body="När något kräver din uppmärksamhet"
        />
      </div>

      <div className="flex-1" />
      <div className="space-y-2 mt-6">
        <PrimaryButton onClick={onEnable}>Aktivera notiser</PrimaryButton>
        <SecondaryButton onClick={onSkip}>Senare</SecondaryButton>
      </div>
    </>
  );
}

function CheckinIntroScreen({ onNext }) {
  return (
    <>
      <FeatIcon>
        <LogIn className="w-7 h-7" />
      </FeatIcon>
      <h2 className="text-[20px] font-extrabold text-center text-slate-900 mb-2">
        Checka in och ut
      </h2>
      <p className="text-[14px] text-slate-600 text-center leading-relaxed mb-5">
        På varje tillsyn trycker du &quot;Checka in&quot; när du är på plats och
        &quot;Checka ut&quot; när du lämnar. Din chef ser realtidsstatus under
        tiden.
      </p>

      <div className="space-y-2.5">
        <FeatureRow
          icon={<Check className="w-4 h-4" />}
          title="Checka in"
          body="Bekräftar att du är på rätt adress"
        />
        <FeatureRow
          icon={<LogOut className="w-4 h-4" />}
          title="Checka ut"
          body="Meddelar att tillsynen är klar"
        />
      </div>

      <div className="flex-1" />
      <div className="mt-6">
        <PrimaryButton onClick={onNext}>
          <span className="inline-flex items-center justify-center gap-1.5">
            Nästa <ChevronRight className="w-4 h-4" />
          </span>
        </PrimaryButton>
      </div>
    </>
  );
}

function AutoAlarmScreen({ onFinish, finishing }) {
  return (
    <>
      <FeatIcon variant="warn">
        <AlertTriangle className="w-7 h-7" />
      </FeatIcon>
      <h2 className="text-[20px] font-extrabold text-center text-slate-900 mb-2">
        Automatiskt larm
      </h2>
      <p className="text-[14px] text-slate-600 text-center leading-relaxed mb-4">
        Om du inte checkar in inom utsatt tid utlöses ett larm hos din chef.
        Det är din säkerhet ifall något oförutsett händer på vägen.
      </p>

      <div className="p-3.5 rounded-lg bg-amber-50 border border-amber-200 text-[13px] text-amber-900 leading-relaxed mb-3">
        <strong className="block mb-1">Om något akut händer i fält:</strong>
        Använd telefonens inbyggda SOS-funktion (tryck sidoknappen 5 gånger
        på iPhone).
      </div>

      <div className="bg-white border border-slate-200 rounded-xl p-3 flex items-start gap-3">
        <div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 bg-indigo-50 text-indigo-600">
          <Check className="w-4 h-4" />
        </div>
        <div className="text-sm leading-snug text-slate-700 pt-0.5">
          Glöm inte att checka ut efter tillsynen.
        </div>
      </div>

      <div className="flex-1" />
      <div className="mt-6">
        <PrimaryButton onClick={onFinish} disabled={finishing}>
          {finishing ? (
            <span className="inline-flex items-center justify-center gap-2">
              <Loader className="w-4 h-4 animate-spin" /> Slutför…
            </span>
          ) : (
            'Slutför onboarding'
          )}
        </PrimaryButton>
      </div>
    </>
  );
}
