<script lang="ts">
  import { onMount } from 'svelte';
  import Icon from '$lib/components/Icon.svelte';
  import OnboardingSignaturePad from '$lib/components/OnboardingSignaturePad.svelte';
  import OnboardingAuth from '$lib/components/OnboardingAuth.svelte';
  import OnboardingFooter from '$lib/components/OnboardingFooter.svelte';
  import logoDesktop from '$lib/images/goodwalk-auckland-dog-walking-logo.png?enhanced';
  import logoMobile from '$lib/images/goodwalk-auckland-dog-walking-logo-mobile.png?enhanced';
  import type { Picture } from '@sveltejs/enhanced-img';

  const desktop = logoDesktop as Picture;
  const mobile = logoMobile as Picture;

  export let preview = false;

  const ownerEmail = 'info@goodwalk.co.nz';
  const ownerPhone = '(022) 642 1011';
  const services = ['Pack Walks', '1:1 Walks', 'Puppy Visits', 'Unsure yet'];
  const visitStartedStorageKey = 'goodwalk_visit_started_at';
  const draftStorageKey = 'goodwalk_onboarding_draft';

  const steps = [
    { icon: 'fas fa-user', title: 'Your details',           desc: 'The basics we need to contact you and identify the household.' },
    { icon: 'fas fa-paw',  title: 'Your dog',               desc: 'Enough background for us to understand the fit and any care notes.' },
    { icon: 'fas fa-shield-alt', title: 'Safety and access', desc: 'Who to call, which clinic to use, and how we access your dog safely.' },
    { icon: 'fas fa-file-signature', title: 'Sign and send', desc: 'Confirm these details are accurate and sign the onboarding declaration.' },
  ];

  let currentStep = 1;

  let fullName = '';
  let email = '';
  let phone = '';
  let address = '';
  let dogName = '';
  let dogBreed = '';
  let dogAge = '';
  let servicesNeeded: string[] = [];
  let temperament = '';
  let medicalNotes = '';
  let accessInstructions = '';
  let vetName = '';
  let vetPhone = '';
  let emergencyContactName = '';
  let emergencyContactPhone = '';
  let councilRegistrationConfirmed = false;
  let vaccinationsConfirmed = false;
  let emergencyVetConsent = false;
  let termsAccepted = false;
  let signatureDataUrl = '';
  let website = '';

  let formStartedAt = 0;
  let visitStartedAt = 0;
  let pageEnteredAt = 0;
  let firstInteractionAt = 0;
  let sendClickedAt = 0;
  let submitting = false;
  let submitted = false;
  let submitError = '';
  let signaturePad: OnboardingSignaturePad;

  let errors: Record<string, string> = {};

  let authChecking = true;
  let isAuthenticated = false;
  let userEmail = '';
  let onboardingCompleted = false;
  let contractCompleted = false;

  // Idle timeout
  const IDLE_TIMEOUT_MS = 20 * 60 * 1000;
  const IDLE_WARN_MS = 18 * 60 * 1000;
  let idleWarning = false;
  let idleLastActivity = Date.now();
  let idleInterval: ReturnType<typeof setInterval> | null = null;

  function resetIdle() {
    idleLastActivity = Date.now();
    idleWarning = false;
  }

  function startIdleTimer() {
    idleLastActivity = Date.now();
    idleInterval = setInterval(() => {
      const elapsed = Date.now() - idleLastActivity;
      if (elapsed >= IDLE_TIMEOUT_MS) {
        handleIdleLogout();
      } else if (elapsed >= IDLE_WARN_MS) {
        idleWarning = true;
      }
    }, 15_000);
  }

  function stopIdleTimer() {
    if (idleInterval) { clearInterval(idleInterval); idleInterval = null; }
    idleWarning = false;
  }

  async function handleIdleLogout() {
    stopIdleTimer();
    await saveDraft();
    try {
      const token = window.localStorage.getItem('gw_onboarding_session') ?? '';
      if (token) {
        await fetch('/api/auth/logout', { method: 'POST', headers: { Authorization: `Bearer ${token}` } }).catch(() => {});
      }
    } finally {
      try { window.localStorage.removeItem('gw_onboarding_session'); } catch { /* ignore */ }
      isAuthenticated = false;
      userEmail = '';
      idleWarning = false;
    }
  }

  async function saveDraft() {
    try {
      const token = window.localStorage.getItem('gw_onboarding_session');
      if (!token) return;
      await fetch('/api/save-draft', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({
          form: 'onboarding',
          data: {
            currentStep,
            fullName, email, phone, address,
            dogName, dogBreed, dogAge,
            servicesNeeded, temperament, medicalNotes, accessInstructions,
            vetName, vetPhone, emergencyContactName, emergencyContactPhone,
            councilRegistrationConfirmed, vaccinationsConfirmed, emergencyVetConsent, termsAccepted,
          },
        }),
      });
    } catch { /* ignore */ }
  }

  function applyDraft(draft: Record<string, unknown>) {
    currentStep = (draft.currentStep as number) ?? 1;
    fullName = (draft.fullName as string) ?? fullName;
    email = (draft.email as string) ?? email;
    phone = (draft.phone as string) ?? phone;
    address = (draft.address as string) ?? address;
    dogName = (draft.dogName as string) ?? dogName;
    dogBreed = (draft.dogBreed as string) ?? dogBreed;
    dogAge = (draft.dogAge as string) ?? dogAge;
    servicesNeeded = (draft.servicesNeeded as string[]) ?? servicesNeeded;
    temperament = (draft.temperament as string) ?? temperament;
    medicalNotes = (draft.medicalNotes as string) ?? medicalNotes;
    accessInstructions = (draft.accessInstructions as string) ?? accessInstructions;
    vetName = (draft.vetName as string) ?? vetName;
    vetPhone = (draft.vetPhone as string) ?? vetPhone;
    emergencyContactName = (draft.emergencyContactName as string) ?? emergencyContactName;
    emergencyContactPhone = (draft.emergencyContactPhone as string) ?? emergencyContactPhone;
    councilRegistrationConfirmed = (draft.councilRegistrationConfirmed as boolean) ?? councilRegistrationConfirmed;
    vaccinationsConfirmed = (draft.vaccinationsConfirmed as boolean) ?? vaccinationsConfirmed;
    emergencyVetConsent = (draft.emergencyVetConsent as boolean) ?? emergencyVetConsent;
    termsAccepted = (draft.termsAccepted as boolean) ?? termsAccepted;
  }

  $: if (typeof window !== 'undefined') {
    try {
      window.localStorage.setItem(draftStorageKey, JSON.stringify({
        currentStep,
        fullName, email, phone, address,
        dogName, dogBreed, dogAge,
        servicesNeeded, temperament, medicalNotes, accessInstructions,
        vetName, vetPhone, emergencyContactName, emergencyContactPhone,
        councilRegistrationConfirmed, vaccinationsConfirmed, emergencyVetConsent, termsAccepted,
      }));
    } catch { /* storage unavailable */ }
  }

  function applyProfile(serverEmail: string, profile: Record<string, string> = {}) {
    if (!email) email = serverEmail;
    if (!fullName) fullName = profile.fullName ?? '';
    if (!phone) phone = profile.phone ?? '';
    if (!address) address = profile.address ?? '';
    if (!dogName) dogName = profile.dogName ?? '';
    if (!dogBreed) dogBreed = profile.dogBreed ?? '';
    if (!dogAge) dogAge = profile.dogAge ?? '';
    onboardingCompleted = Boolean((profile as Record<string, unknown>).onboardingCompleted);
    contractCompleted = Boolean((profile as Record<string, unknown>).contractCompleted);
  }

  async function checkAuth() {
    try {
      const token = window.localStorage.getItem('gw_onboarding_session');
      if (token) {
        const res = await fetch('/api/auth/verify', {
          headers: { Authorization: `Bearer ${token}` },
        });
        if (res.ok) {
          const data = await res.json();
          isAuthenticated = true;
          userEmail = data.email;
          applyProfile(data.email, data.profile ?? {});
          if (data.draft?.onboarding) applyDraft(data.draft.onboarding);
        } else {
          window.localStorage.removeItem('gw_onboarding_session');
        }
      }
    } catch { /* ignore */ }
    authChecking = false;
  }

  function handleAuthenticated(e: CustomEvent<{ email: string; profile?: Record<string, string>; draft?: Record<string, unknown> }>) {
    isAuthenticated = true;
    userEmail = e.detail.email;
    applyProfile(e.detail.email, e.detail.profile ?? {});
    if (e.detail.draft?.onboarding) applyDraft(e.detail.draft.onboarding as Record<string, unknown>);
    startIdleTimer();
    const now = Date.now();
    formStartedAt = now;
    pageEnteredAt = now;
    visitStartedAt = readOrCreateVisitStartedAt(now);
  }

  function handleLogout() {
    stopIdleTimer();
    isAuthenticated = false;
    userEmail = '';
  }

  onMount(async () => {
    await checkAuth();

    if (!isAuthenticated) return;

    startIdleTimer();

    const now = Date.now();
    formStartedAt = now;
    pageEnteredAt = now;
    visitStartedAt = readOrCreateVisitStartedAt(now);

    try {
      const raw = window.localStorage.getItem(draftStorageKey);
      if (raw) {
        const d = JSON.parse(raw);
        currentStep = d.currentStep ?? 1;
        fullName = d.fullName ?? '';
        email = d.email ?? '';
        phone = d.phone ?? '';
        address = d.address ?? '';
        dogName = d.dogName ?? '';
        dogBreed = d.dogBreed ?? '';
        dogAge = d.dogAge ?? '';
        servicesNeeded = d.servicesNeeded ?? [];
        temperament = d.temperament ?? '';
        medicalNotes = d.medicalNotes ?? '';
        accessInstructions = d.accessInstructions ?? '';
        vetName = d.vetName ?? '';
        vetPhone = d.vetPhone ?? '';
        emergencyContactName = d.emergencyContactName ?? '';
        emergencyContactPhone = d.emergencyContactPhone ?? '';
        councilRegistrationConfirmed = d.councilRegistrationConfirmed ?? false;
        vaccinationsConfirmed = d.vaccinationsConfirmed ?? false;
        emergencyVetConsent = d.emergencyVetConsent ?? false;
        termsAccepted = d.termsAccepted ?? false;
      }
    } catch { /* storage unavailable */ }
  });

  function readOrCreateVisitStartedAt(fallback: number) {
    try {
      const raw = window.sessionStorage.getItem(visitStartedStorageKey);
      const parsed = raw ? Number(raw) : NaN;

      if (Number.isFinite(parsed) && parsed > 0) {
        return parsed;
      }

      window.sessionStorage.setItem(visitStartedStorageKey, String(fallback));
    } catch {
      return fallback;
    }

    return fallback;
  }

  function noteInteraction() {
    if (!firstInteractionAt) {
      firstInteractionAt = Date.now();
    }
  }

  function toggleService(service: string, checked: boolean) {
    noteInteraction();
    servicesNeeded = checked
      ? [...servicesNeeded, service]
      : servicesNeeded.filter((item) => item !== service);

    if (errors.servicesNeeded) {
      errors = { ...errors, servicesNeeded: '' };
    }
  }

  function validateEmail(raw: string): string {
    const value = raw.trim();
    if (!value) return 'Please enter your email address';
    if (!/^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$/.test(value)) {
      return 'Please enter a valid email address';
    }
    return '';
  }

  function validateStep(step: number): boolean {
    const next: Record<string, string> = {};

    if (step === 1) {
      if (!fullName.trim()) next.fullName = 'Please enter your full name';
      const emailError = validateEmail(email);
      if (emailError) next.email = emailError;
      if (!phone.trim()) next.phone = 'Please enter your phone number';
      if (!address.trim()) next.address = 'Please enter your address';
    } else if (step === 2) {
      if (!dogName.trim()) next.dogName = "Please enter your dog's name";
      if (!dogBreed.trim()) next.dogBreed = "Please enter your dog's breed";
      if (!servicesNeeded.length) next.servicesNeeded = 'Choose at least one service';
    } else if (step === 3) {
      if (!vetName.trim()) next.vetName = 'Please enter your vet clinic name';
      if (!vetPhone.trim()) next.vetPhone = 'Please enter your vet phone number';
      if (!emergencyContactName.trim()) next.emergencyContactName = 'Please add an emergency contact';
      if (!emergencyContactPhone.trim()) next.emergencyContactPhone = 'Please add an emergency contact number';
    } else if (step === 4) {
      if (!councilRegistrationConfirmed) next.councilRegistrationConfirmed = 'Please confirm council registration';
      if (!vaccinationsConfirmed) next.vaccinationsConfirmed = 'Please confirm vaccinations are current';
      if (!emergencyVetConsent) next.emergencyVetConsent = 'Please confirm emergency treatment consent';
      if (!termsAccepted) next.termsAccepted = 'Please confirm the onboarding declaration';
      if (!signatureDataUrl) next.signature = 'Please add your signature before sending';
    }

    errors = next;
    return Object.keys(next).length === 0;
  }

  function nextStep() {
    noteInteraction();
    if (!validateStep(currentStep)) return;
    currentStep += 1;
    void saveDraft();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }

  function prevStep() {
    errors = {};
    currentStep -= 1;
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }

  async function handleSubmit(event: SubmitEvent) {
    event.preventDefault();
    noteInteraction();
    sendClickedAt = Date.now();
    submitError = '';

    if (!validateStep(4)) return;

    submitting = true;

    try {
      const response = await fetch('/api/onboarding-submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          fullName, email, phone, address,
          dogName, dogBreed, dogAge,
          servicesNeeded, temperament, medicalNotes, accessInstructions,
          vetName, vetPhone, emergencyContactName, emergencyContactPhone,
          councilRegistrationConfirmed, vaccinationsConfirmed, emergencyVetConsent, termsAccepted,
          signatureDataUrl, website,
          formStartedAt, visitStartedAt, pageEnteredAt, firstInteractionAt, sendClickedAt,
          referrer: document.referrer,
          page: window.location.href,
        })
      });

      if (!response.ok) {
        const payload = await response.json().catch(() => null);
        throw new Error(payload?.detail?.message ?? payload?.detail ?? 'Submission failed');
      }

      submitted = true;
      try { window.localStorage.removeItem(draftStorageKey); } catch { /* ignore */ }
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (error) {
      submitError = error instanceof Error ? error.message : 'Submission failed';
    } finally {
      submitting = false;
    }
  }
</script>

<svelte:head>
  <title>Goodwalk Onboarding</title>
  <meta
    name="description"
    content="Complete your Goodwalk onboarding form, sign it online, and send it through for review."
  />
  <meta name="robots" content="noindex, nofollow" />
  <link rel="canonical" href="https://onboarding.goodwalk.co.nz/" />
</svelte:head>

<main class="onboarding-page">
  <div class="onboarding-topbar">
    <div class="onboarding-shell onboarding-topbar-inner">
      <div class="onboarding-brand">
        <span class="onboarding-pill">Onboarding</span>
        <a href="https://goodwalk.co.nz" class="onboarding-logo" aria-label="Goodwalk home">
          <picture>
            {#if desktop.sources?.webp}
              <source type="image/webp" srcset={desktop.sources.webp} />
            {/if}
            <img
              src={desktop.img.src}
              alt="Goodwalk logo"
              width={desktop.img.w}
              height={desktop.img.h}
              decoding="async"
            />
          </picture>
        </a>
      </div>
    </div>
  </div>

  {#if authChecking}
    <div class="onboarding-auth-checking">
      <Icon name="fas fa-circle-notch" className="auth-spinner" />
    </div>
  {:else if !isAuthenticated}
    <OnboardingAuth on:authenticated={handleAuthenticated} />
  {:else}

  <div class="journey-bar">
    <div class="onboarding-shell journey-bar-inner">
      <div class="journey-stage journey-stage-active">
        <span class="journey-stage-icon">
          {#if onboardingCompleted}
            <Icon name="fas fa-check" />
          {:else}
            <Icon name="fas fa-clipboard-list" />
          {/if}
        </span>
        <span class="journey-stage-label">Onboarding form</span>
        {#if onboardingCompleted}
          <span class="journey-badge journey-badge-done">Done</span>
        {:else}
          <span class="journey-badge journey-badge-current">In progress</span>
        {/if}
      </div>

      <div class="journey-connector" class:journey-connector-done={onboardingCompleted}></div>

      <a href="/contract?preview=contract" class="journey-stage" class:journey-done={contractCompleted}>
        <span class="journey-stage-icon">
          {#if contractCompleted}
            <Icon name="fas fa-check" />
          {:else}
            <Icon name="fas fa-file-signature" />
          {/if}
        </span>
        <span class="journey-stage-label">Service contract</span>
        {#if contractCompleted}
          <span class="journey-badge journey-badge-done">Signed</span>
        {:else}
          <span class="journey-badge journey-badge-todo">To do</span>
        {/if}
      </a>
    </div>
  </div>

  {#if idleWarning}
    <div class="idle-warning" role="alert">
      <div class="onboarding-shell idle-warning-inner">
        <Icon name="fas fa-clock" />
        <span>You'll be signed out in 2 minutes due to inactivity. Your progress has been saved.</span>
        <button class="idle-stay" on:click={resetIdle}>Stay signed in</button>
      </div>
    </div>
  {/if}

  <section class="onboarding-hero">
    <div class="onboarding-shell onboarding-hero-inner">
      <div class="onboarding-hero-copy">
        <span class="onboarding-eyebrow">Client onboarding</span>
        <h1>Tell us about your dog, sign the form, and we&rsquo;ll take it from there.</h1>
        <p>
          This gives us the details we need before your dog starts with Goodwalk. Once it is
          submitted, Aless receives it directly for review.
        </p>
      </div>

      <div class="onboarding-contact-card">
        <div class="onboarding-contact-title">Questions before you send it?</div>
        <a href={`mailto:${ownerEmail}`} class="onboarding-contact-link">
          <Icon name="fas fa-envelope" />
          {ownerEmail}
        </a>
        <a href={`tel:${ownerPhone.replace(/[^0-9+]/g, '')}`} class="onboarding-contact-link">
          <Icon name="fas fa-phone" />
          {ownerPhone}
        </a>
      </div>
    </div>
  </section>

  <section class="onboarding-form-section">
    <div class="onboarding-shell">
      {#if submitted}
        <div class="onboarding-success-card">
          <span class="onboarding-success-badge">Submitted</span>
          <h2>Thanks. Your onboarding form is with us.</h2>
          <p>
            Aless has received your signed onboarding form and will review it directly. If
            anything else is needed, we&rsquo;ll come back to you using the contact details you
            provided.
          </p>
        </div>
      {:else}
        <!-- Step progress indicator -->
        <div class="step-progress">
          {#each steps as step, i}
            <button
              type="button"
              class="step-indicator"
              class:active={currentStep === i + 1}
              class:completed={currentStep > i + 1}
              on:click={() => { if (currentStep > i + 1) { errors = {}; currentStep = i + 1; window.scrollTo({ top: 0, behavior: 'smooth' }); } }}
              disabled={currentStep <= i + 1}
              aria-label="Go to step {i + 1}: {step.title}"
            >
              <div class="step-indicator-circle">
                {#if currentStep > i + 1}
                  <Icon name="fas fa-check" />
                {:else}
                  <Icon name={step.icon} />
                {/if}
              </div>
              <span class="step-indicator-label">{step.title}</span>
            </button>
            {#if i < steps.length - 1}
              <div class="step-connector" class:filled={currentStep > i + 1}></div>
            {/if}
          {/each}
        </div>

        <form class="onboarding-form" novalidate on:submit={handleSubmit}>

          <!-- Step 1: Your details -->
          {#if currentStep === 1}
            <section class="onboarding-panel">
              <div class="onboarding-panel-head">
                <div class="onboarding-step-icon">
                  <Icon name="fas fa-user" />
                </div>
                <div>
                  <h2>{steps[0].title}</h2>
                  <p>{steps[0].desc}</p>
                </div>
              </div>

              <div class="onboarding-fields two-up">
                <label class="field">
                  <span>Full name</span>
                  <input bind:value={fullName} on:input={noteInteraction} />
                  {#if errors.fullName}<small>{errors.fullName}</small>{/if}
                </label>

                <label class="field">
                  <span>Email</span>
                  <input bind:value={email} type="email" on:input={noteInteraction} />
                  {#if errors.email}<small>{errors.email}</small>{/if}
                </label>

                <label class="field">
                  <span>Phone</span>
                  <input bind:value={phone} type="tel" on:input={noteInteraction} />
                  {#if errors.phone}<small>{errors.phone}</small>{/if}
                </label>

                <label class="field field-full">
                  <span>Home address</span>
                  <input bind:value={address} on:input={noteInteraction} />
                  {#if errors.address}<small>{errors.address}</small>{/if}
                </label>
              </div>

              <div class="panel-nav">
                <button class="btn btn-yellow panel-nav-next" type="button" on:click={nextStep}>
                  Save and continue <Icon name="fas fa-arrow-right" />
                </button>
              </div>
            </section>
          {/if}

          <!-- Step 2: Your dog -->
          {#if currentStep === 2}
            <section class="onboarding-panel">
              <div class="onboarding-panel-head">
                <div class="onboarding-step-icon">
                  <Icon name="fas fa-paw" />
                </div>
                <div>
                  <h2>{steps[1].title}</h2>
                  <p>{steps[1].desc}</p>
                </div>
              </div>

              <div class="onboarding-fields two-up">
                <label class="field">
                  <span>Dog name</span>
                  <input bind:value={dogName} on:input={noteInteraction} />
                  {#if errors.dogName}<small>{errors.dogName}</small>{/if}
                </label>

                <label class="field">
                  <span>Breed</span>
                  <input bind:value={dogBreed} on:input={noteInteraction} />
                  {#if errors.dogBreed}<small>{errors.dogBreed}</small>{/if}
                </label>

                <label class="field">
                  <span>Age</span>
                  <input bind:value={dogAge} placeholder="Optional" on:input={noteInteraction} />
                </label>
              </div>

              <div class="field">
                <span>Which service are you onboarding for?</span>
                <div class="chip-grid">
                  {#each services as service}
                    <label class:chip-selected={servicesNeeded.includes(service)} class="chip-option">
                      <input
                        type="checkbox"
                        checked={servicesNeeded.includes(service)}
                        on:change={(event) =>
                          toggleService(service, (event.currentTarget as HTMLInputElement).checked)}
                      />
                      <span>{service}</span>
                    </label>
                  {/each}
                </div>
                {#if errors.servicesNeeded}<small>{errors.servicesNeeded}</small>{/if}
              </div>

              <label class="field">
                <span>Temperament, routine, or handling notes</span>
                <textarea
                  bind:value={temperament}
                  rows="4"
                  placeholder="Confidence around other dogs, recall, triggers, pace, preferred handling, daily routine."
                  on:input={noteInteraction}
                ></textarea>
              </label>

              <label class="field">
                <span>Medical notes or medications</span>
                <textarea
                  bind:value={medicalNotes}
                  rows="4"
                  placeholder="Anything we should know about injuries, medications, allergies, or limitations."
                  on:input={noteInteraction}
                ></textarea>
              </label>

              <div class="panel-nav">
                <button class="panel-nav-back" type="button" on:click={prevStep}>
                  <Icon name="fas fa-arrow-left" /> Back
                </button>
                <button class="btn btn-yellow panel-nav-next" type="button" on:click={nextStep}>
                  Save and continue <Icon name="fas fa-arrow-right" />
                </button>
              </div>
            </section>
          {/if}

          <!-- Step 3: Safety and access -->
          {#if currentStep === 3}
            <section class="onboarding-panel">
              <div class="onboarding-panel-head">
                <div class="onboarding-step-icon">
                  <Icon name="fas fa-shield-alt" />
                </div>
                <div>
                  <h2>{steps[2].title}</h2>
                  <p>{steps[2].desc}</p>
                </div>
              </div>

              <div class="onboarding-fields two-up">
                <label class="field">
                  <span>Vet clinic</span>
                  <input bind:value={vetName} on:input={noteInteraction} />
                  {#if errors.vetName}<small>{errors.vetName}</small>{/if}
                </label>

                <label class="field">
                  <span>Vet phone</span>
                  <input bind:value={vetPhone} type="tel" on:input={noteInteraction} />
                  {#if errors.vetPhone}<small>{errors.vetPhone}</small>{/if}
                </label>

                <label class="field">
                  <span>Emergency contact</span>
                  <input bind:value={emergencyContactName} on:input={noteInteraction} />
                  {#if errors.emergencyContactName}<small>{errors.emergencyContactName}</small>{/if}
                </label>

                <label class="field">
                  <span>Emergency contact phone</span>
                  <input bind:value={emergencyContactPhone} type="tel" on:input={noteInteraction} />
                  {#if errors.emergencyContactPhone}<small>{errors.emergencyContactPhone}</small>{/if}
                </label>
              </div>

              <label class="field">
                <span>Home access instructions</span>
                <textarea
                  bind:value={accessInstructions}
                  rows="4"
                  placeholder="Keys, gate code, where to collect your dog, alarm notes, or anything else we should know."
                  on:input={noteInteraction}
                ></textarea>
              </label>

              <div class="panel-nav">
                <button class="panel-nav-back" type="button" on:click={prevStep}>
                  <Icon name="fas fa-arrow-left" /> Back
                </button>
                <button class="btn btn-yellow panel-nav-next" type="button" on:click={nextStep}>
                  Save and continue <Icon name="fas fa-arrow-right" />
                </button>
              </div>
            </section>
          {/if}

          <!-- Step 4: Declaration and signature -->
          {#if currentStep === 4}
            <section class="onboarding-panel onboarding-panel-signoff">
              <div class="onboarding-panel-head">
                <div class="onboarding-step-icon">
                  <Icon name="fas fa-file-signature" />
                </div>
                <div>
                  <h2>{steps[3].title}</h2>
                  <p>{steps[3].desc}</p>
                </div>
              </div>

              <div class="onboarding-confirm-list">
                <label class="confirm-row">
                  <input bind:checked={councilRegistrationConfirmed} type="checkbox" on:change={noteInteraction} />
                  <span>My dog has a current Auckland Council registration, where required.</span>
                </label>
                {#if errors.councilRegistrationConfirmed}<small>{errors.councilRegistrationConfirmed}</small>{/if}

                <label class="confirm-row">
                  <input bind:checked={vaccinationsConfirmed} type="checkbox" on:change={noteInteraction} />
                  <span>My dog is up to date with vaccinations.</span>
                </label>
                {#if errors.vaccinationsConfirmed}<small>{errors.vaccinationsConfirmed}</small>{/if}

                <label class="confirm-row">
                  <input bind:checked={emergencyVetConsent} type="checkbox" on:change={noteInteraction} />
                  <span>I authorise Goodwalk to seek urgent veterinary treatment if I cannot be reached in an emergency.</span>
                </label>
                {#if errors.emergencyVetConsent}<small>{errors.emergencyVetConsent}</small>{/if}

                <label class="confirm-row">
                  <input bind:checked={termsAccepted} type="checkbox" on:change={noteInteraction} />
                  <span>I confirm the information above is accurate and I understand Goodwalk will review this before service begins.</span>
                </label>
                {#if errors.termsAccepted}<small>{errors.termsAccepted}</small>{/if}
              </div>

              <div class="signature-wrap">
                <div class="signature-header">
                  <div>
                    <span>Signature</span>
                    <p>Draw your signature below.</p>
                  </div>
                  <button
                    class="signature-clear"
                    type="button"
                    on:click={() => {
                      noteInteraction();
                      signaturePad.clear();
                      errors = { ...errors, signature: '' };
                    }}
                  >
                    Clear
                  </button>
                </div>

                <div class:signature-error={Boolean(errors.signature)} class="signature-frame">
                  <OnboardingSignaturePad bind:this={signaturePad} bind:value={signatureDataUrl} />
                </div>
                {#if errors.signature}<small>{errors.signature}</small>{/if}
              </div>

              <input bind:value={website} class="honeypot" tabindex="-1" autocomplete="off" />

              {#if submitError}
                <div class="submit-error">{submitError}</div>
              {/if}

              <div class="panel-nav">
                <button class="panel-nav-back" type="button" on:click={prevStep}>
                  <Icon name="fas fa-arrow-left" /> Back
                </button>
                <div class="panel-nav-submit-group">
                  <button class="btn btn-yellow onboarding-submit" type="submit" disabled={submitting}>
                    {#if submitting}Sending…{:else}Send onboarding form{/if}
                  </button>
                  <p>This goes directly to Aless for review.</p>
                </div>
              </div>
            </section>
          {/if}

        </form>
      {/if}
    </div>
  </section>

  <OnboardingFooter email={userEmail} on:logout={handleLogout} />

  {/if}
</main>

<style>
  .onboarding-page {
    min-height: 100vh;
    background:
      radial-gradient(circle at top left, rgba(255, 209, 0, 0.14), transparent 28%),
      linear-gradient(180deg, #f6f5ef 0%, #fbfbf9 42%, #f3f1e8 100%);
    color: var(--gw-green);
  }

  .onboarding-shell {
    max-width: 1120px;
    margin: 0 auto;
    padding: 0 28px;
  }

  /* ── Journey bar ── */
  .journey-bar {
    background: #1a2a1a;
    border-bottom: 1px solid rgba(255, 255, 255, 0.06);
  }

  .journey-bar-inner {
    display: flex;
    align-items: center;
    height: 48px;
  }

  .journey-stage {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 0 4px;
    text-decoration: none;
    color: rgba(255, 255, 255, 0.45);
    font-family: var(--font-head);
    font-size: 13px;
    font-weight: 700;
    white-space: nowrap;
    transition: color 0.15s;
  }

  .journey-stage:hover {
    color: rgba(255, 255, 255, 0.7);
  }

  .journey-stage-active {
    color: rgba(255, 255, 255, 0.9);
    cursor: default;
  }

  .journey-stage-active:hover {
    color: rgba(255, 255, 255, 0.9);
  }

  .journey-done {
    color: rgba(255, 255, 255, 0.65);
  }

  .journey-stage-icon {
    width: 22px;
    height: 22px;
    border-radius: 50%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    background: rgba(255, 255, 255, 0.1);
    flex-shrink: 0;
  }

  .journey-done .journey-stage-icon {
    background: #213021;
    color: #7aaa7a;
  }

  .journey-stage-active .journey-stage-icon {
    background: linear-gradient(180deg, #ffe36b 0%, #ffd100 100%);
    color: #213021;
  }

  .journey-badge {
    padding: 2px 8px;
    border-radius: 999px;
    font-size: 10px;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
  }

  .journey-badge-done {
    background: rgba(122, 170, 122, 0.18);
    color: #7aaa7a;
  }

  .journey-badge-todo {
    background: rgba(255, 100, 60, 0.15);
    color: #ff8060;
  }

  .journey-badge-current {
    background: rgba(255, 209, 0, 0.18);
    color: #ffd100;
  }

  .journey-connector {
    flex: 1;
    height: 1px;
    background: rgba(255, 255, 255, 0.1);
    margin: 0 12px;
    max-width: 60px;
  }

  .journey-connector-done {
    background: rgba(122, 170, 122, 0.4);
  }

  /* ── Top nav bar ── */
  .onboarding-auth-checking {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 200px;
    color: rgba(33, 48, 33, 0.35);
    font-size: 24px;
  }

  :global(.auth-spinner) {
    animation: spin 0.8s linear infinite;
  }

  @keyframes spin {
    to { transform: rotate(360deg); }
  }

  .onboarding-topbar {
    background: #213021;
  }

  .onboarding-topbar-inner {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    height: 56px;
  }

  .onboarding-brand {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-shrink: 0;
  }

  .onboarding-logo {
    display: flex;
    align-items: center;
  }

  .onboarding-logo img {
    height: 28px;
    width: auto;
    display: block;
  }

  .onboarding-pill {
    padding: 4px 10px;
    border-radius: 999px;
    background: var(--yellow);
    font-family: var(--font-head);
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: var(--gw-green);
  }

  /* ── Idle warning ── */
  .idle-warning {
    background: rgba(255, 160, 60, 0.1);
    border-bottom: 1px solid rgba(255, 160, 60, 0.2);
  }

  .idle-warning-inner {
    display: flex;
    align-items: center;
    gap: 12px;
    padding-top: 12px;
    padding-bottom: 12px;
    font-size: 14px;
    color: #8a5a20;
  }

  .idle-stay {
    margin-left: auto;
    padding: 8px 16px;
    border-radius: 999px;
    border: 1px solid rgba(138, 90, 32, 0.3);
    background: #fff;
    font-family: var(--font-head);
    font-size: 13px;
    font-weight: 700;
    color: #8a5a20;
    cursor: pointer;
    white-space: nowrap;
    transition: background 0.15s;
  }

  .idle-stay:hover {
    background: rgba(255, 160, 60, 0.1);
  }

  /* ── Hero ── */
  .onboarding-hero {
    padding: 28px 0 22px;
  }

  .onboarding-hero-inner {
    display: grid;
    gap: 20px;
  }

  .onboarding-hero-copy {
    max-width: 760px;
  }

  .onboarding-eyebrow {
    display: inline-block;
    margin-bottom: 10px;
    font-family: var(--font-head);
    font-size: 12px;
    font-weight: 700;
    letter-spacing: 0.12em;
    text-transform: uppercase;
    color: #688568;
  }

  .onboarding-hero-copy h1 {
    margin: 0 0 12px;
    font-family: var(--font-head);
    font-size: clamp(22px, 2.6vw, 32px);
    font-weight: 800;
    line-height: 1.1;
    letter-spacing: -0.03em;
    max-width: 32ch;
  }

  .onboarding-hero-copy p {
    margin: 0;
    max-width: 620px;
    font-size: 15px;
    line-height: 1.65;
    color: rgba(33, 48, 33, 0.78);
  }

  .onboarding-contact-card {
    display: flex;
    align-items: center;
    gap: 14px;
    flex-wrap: wrap;
    padding: 22px 24px;
    border-radius: 24px;
    background: rgba(255, 255, 255, 0.72);
    border: 1px solid rgba(33, 48, 33, 0.08);
    box-shadow: 0 18px 40px rgba(33, 48, 33, 0.06);
  }

  .onboarding-contact-title {
    margin-right: auto;
    font-family: var(--font-head);
    font-size: 18px;
    font-weight: 700;
    letter-spacing: -0.02em;
  }

  .onboarding-contact-link {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 11px 18px;
    border-radius: 999px;
    background: #fff;
    border: 1px solid rgba(33, 48, 33, 0.1);
    font-family: var(--font-head);
    font-size: 14px;
    font-weight: 700;
    line-height: 1.2;
    letter-spacing: 0.01em;
    color: var(--gw-green);
  }

  /* ── Form section ── */
  .onboarding-form-section {
    padding: 0 0 64px;
  }

  /* ── Step progress ── */
  .step-progress {
    display: flex;
    align-items: center;
    gap: 0;
    margin-bottom: 24px;
    padding: 20px 24px;
    border-radius: 24px;
    background: rgba(255, 255, 255, 0.72);
    border: 1px solid rgba(33, 48, 33, 0.08);
    box-shadow: 0 8px 24px rgba(33, 48, 33, 0.05);
  }

  .step-indicator {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    flex: 1;
    background: none;
    border: none;
    padding: 0;
    cursor: default;
  }

  .step-indicator.completed {
    cursor: pointer;
  }

  .step-indicator-circle {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 17px;
    background: rgba(33, 48, 33, 0.07);
    color: rgba(33, 48, 33, 0.35);
    transition: background 0.2s, color 0.2s;
  }

  .step-indicator.active .step-indicator-circle {
    background: linear-gradient(180deg, #ffe36b 0%, #ffd100 100%);
    color: #213021;
  }

  .step-indicator.completed .step-indicator-circle {
    background: #213021;
    color: #fff;
  }

  .step-indicator-label {
    font-family: var(--font-head);
    font-size: 12px;
    font-weight: 700;
    letter-spacing: 0.01em;
    color: rgba(33, 48, 33, 0.4);
    text-align: center;
    transition: color 0.2s;
  }

  .step-indicator.active .step-indicator-label {
    color: #213021;
  }

  .step-indicator.completed .step-indicator-label {
    color: #213021;
  }

  .step-connector {
    flex: 1;
    height: 2px;
    background: rgba(33, 48, 33, 0.1);
    margin-bottom: 26px;
    transition: background 0.3s;
  }

  .step-connector.filled {
    background: #213021;
  }

  /* ── Panels ── */
  .onboarding-panel,
  .onboarding-success-card {
    padding: 30px;
    border-radius: 28px;
    background: rgba(255, 255, 255, 0.84);
    border: 1px solid rgba(33, 48, 33, 0.08);
    box-shadow: 0 20px 44px rgba(33, 48, 33, 0.07);
  }

  .onboarding-success-card {
    max-width: 760px;
    margin: 0 auto;
    text-align: center;
  }

  .onboarding-success-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 14px;
    padding: 8px 14px;
    border-radius: 999px;
    background: rgba(122, 170, 122, 0.14);
    font-family: var(--font-head);
    font-size: 12px;
    font-weight: 700;
    letter-spacing: 0.09em;
    text-transform: uppercase;
    color: #4d6d4d;
  }

  .onboarding-success-card h2,
  .onboarding-panel-head h2 {
    margin: 0;
    font-family: var(--font-head);
    font-size: clamp(26px, 3vw, 36px);
    font-weight: 700;
    line-height: 1.06;
    letter-spacing: -0.03em;
    text-wrap: balance;
  }

  .onboarding-success-card p,
  .onboarding-panel-head p {
    margin: 10px 0 0;
    font-size: 15px;
    line-height: 1.65;
    color: rgba(33, 48, 33, 0.7);
  }

  .onboarding-panel-head {
    display: flex;
    gap: 18px;
    align-items: flex-start;
    margin-bottom: 28px;
  }

  .onboarding-step-icon {
    flex: none;
    width: 48px;
    height: 48px;
    border-radius: 16px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    background: linear-gradient(180deg, #ffe36b 0%, #ffd100 100%);
    color: #213021;
  }

  /* ── Fields ── */
  .onboarding-fields {
    display: grid;
    gap: 16px;
  }

  .two-up {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .field {
    display: grid;
    gap: 8px;
    margin-top: 16px;
  }

  .field:first-child,
  .onboarding-fields .field {
    margin-top: 0;
  }

  .field-full {
    grid-column: 1 / -1;
  }

  .field span,
  .signature-header span {
    font-family: var(--font-head);
    font-size: 15px;
    font-weight: 700;
    letter-spacing: -0.01em;
  }

  .field input,
  .field textarea {
    width: 100%;
    padding: 15px 16px;
    border: 1px solid rgba(33, 48, 33, 0.14);
    border-radius: 18px;
    background: #fff;
    font: inherit;
    color: var(--gw-green);
    outline: none;
    transition: border-color 0.18s ease, box-shadow 0.18s ease;
  }

  .field input:focus,
  .field textarea:focus {
    border-color: rgba(255, 209, 0, 0.9);
    box-shadow: 0 0 0 4px rgba(255, 209, 0, 0.16);
  }

  .field textarea {
    resize: vertical;
    min-height: 120px;
  }

  .field small,
  .onboarding-confirm-list small,
  .signature-wrap small {
    color: #b4422f;
    font-size: 12px;
    line-height: 1.4;
  }

  /* ── Service chips ── */
  .chip-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .chip-option {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 12px 16px;
    border-radius: 999px;
    border: 1px solid rgba(33, 48, 33, 0.12);
    background: #fff;
    font-family: var(--font-head);
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    transition: transform 0.16s ease, border-color 0.16s ease, background 0.16s ease;
  }

  .chip-option input {
    position: absolute;
    opacity: 0;
    pointer-events: none;
  }

  .chip-option.chip-selected {
    background: #213021;
    border-color: #213021;
    color: #ffd100;
    transform: translateY(-1px);
  }

  /* ── Declaration ── */
  .onboarding-confirm-list {
    display: grid;
    gap: 12px;
  }

  .confirm-row {
    display: grid;
    grid-template-columns: 20px 1fr;
    gap: 12px;
    align-items: start;
    padding: 14px 16px;
    border-radius: 18px;
    background: #fff;
    border: 1px solid rgba(33, 48, 33, 0.08);
  }

  .confirm-row input {
    margin-top: 3px;
  }

  /* ── Signature ── */
  .signature-wrap {
    margin-top: 24px;
  }

  .signature-header {
    display: flex;
    align-items: end;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: 12px;
  }

  .signature-header p {
    margin: 5px 0 0;
    font-size: 13px;
    line-height: 1.5;
    color: rgba(33, 48, 33, 0.65);
  }

  .signature-frame {
    padding: 6px;
    border-radius: 24px;
    background: rgba(33, 48, 33, 0.05);
    border: 1px solid rgba(33, 48, 33, 0.1);
  }

  .signature-frame.signature-error {
    border-color: rgba(180, 66, 47, 0.5);
  }

  .signature-clear {
    padding: 10px 14px;
    border-radius: 999px;
    border: 1px solid rgba(33, 48, 33, 0.12);
    background: #fff;
    font-family: var(--font-head);
    font-size: 13px;
    font-weight: 700;
    color: var(--gw-green);
    cursor: pointer;
  }

  /* ── Submit error ── */
  .submit-error {
    margin-top: 18px;
    padding: 14px 16px;
    border-radius: 16px;
    background: #fff3ef;
    color: #a43f2c;
    font-size: 14px;
    line-height: 1.55;
  }

  /* ── Panel navigation ── */
  .panel-nav {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-top: 28px;
    padding-top: 24px;
    border-top: 1px solid rgba(33, 48, 33, 0.07);
  }

  .panel-nav-back {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    padding: 12px 18px;
    border-radius: 999px;
    border: 1px solid rgba(33, 48, 33, 0.14);
    background: #fff;
    font-family: var(--font-head);
    font-size: 14px;
    font-weight: 700;
    color: var(--gw-green);
    cursor: pointer;
    transition: background 0.15s, border-color 0.15s;
  }

  .panel-nav-back:hover {
    background: rgba(33, 48, 33, 0.05);
    border-color: rgba(33, 48, 33, 0.22);
  }

  .panel-nav-next {
    margin-left: auto;
    display: inline-flex;
    align-items: center;
    gap: 8px;
  }

  .panel-nav-submit-group {
    margin-left: auto;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 8px;
  }

  .panel-nav-submit-group p {
    margin: 0;
    font-size: 13px;
    line-height: 1.5;
    color: rgba(33, 48, 33, 0.6);
  }

  .onboarding-submit {
    min-width: 220px;
  }

  .honeypot {
    position: absolute;
    left: -9999px;
    opacity: 0;
    pointer-events: none;
  }

  /* ── Mobile ── */
  @media (max-width: 768px) {
    .onboarding-shell {
      padding: 0 18px;
    }

    .onboarding-topbar-inner {
      height: 50px;
    }

    .journey-bar-inner {
      height: auto;
      padding: 12px 0;
    }

    .journey-stage-label {
      display: none;
    }

    .onboarding-hero {
      padding: 20px 0 16px;
    }

    .onboarding-contact-card {
      align-items: stretch;
    }

    .onboarding-contact-title {
      width: 100%;
      margin-right: 0;
    }

    .onboarding-contact-link {
      justify-content: center;
      width: 100%;
    }

    .step-progress {
      padding: 16px 12px;
      gap: 0;
    }

    .step-indicator-label {
      font-size: 10px;
    }

    .step-indicator-circle {
      width: 36px;
      height: 36px;
      font-size: 14px;
    }

    .step-connector {
      margin-bottom: 22px;
    }

    .two-up {
      grid-template-columns: 1fr;
    }

    .onboarding-panel,
    .onboarding-success-card {
      padding: 22px 18px;
      border-radius: 22px;
    }

    .onboarding-panel-head {
      gap: 14px;
      margin-bottom: 20px;
    }

    .signature-header {
      align-items: start;
      flex-direction: column;
    }

    .panel-nav {
      flex-wrap: wrap;
    }

    .panel-nav-next,
    .onboarding-submit {
      width: 100%;
      justify-content: center;
    }

    .panel-nav-submit-group {
      width: 100%;
      align-items: stretch;
    }
  }
</style>
