<script setup lang="ts">
/**
 * EarlyAccess signup page.
 * Backend endpoint: POST /api/early-access — live and functional.
 */
import { ref, onMounted, onUnmounted } from 'vue'
import { RouterLink } from 'vue-router'
import Icon from '@/components/ds/core/Icon.vue'
import CorrosionMark from '@/components/brand/CorrosionMark.vue'

const panelUrl = import.meta.env.VITE_PANEL_URL ?? ''

// Form state
const email = ref('')
const name = ref('')
const gameInterest = ref('')
const submitting = ref(false)
const submitted = ref(false)
const errorMsg = ref('')

const GAME_OPTIONS = [
  { value: 'rust', label: 'Rust' },
  { value: 'dune', label: 'Dune: Awakening' },
  { value: 'conan', label: 'Conan Exiles' },
  { value: 'soulmask', label: 'Soulmask' },
  { value: 'multiple', label: 'Multiple games' },
]

async function handleSubmit(): Promise<void> {
  if (!email.value) return
  errorMsg.value = ''
  submitting.value = true
  try {
    const res = await fetch('/api/early-access', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: email.value,
        // server_count column stores game interest (varchar 10) — no dedicated name column in DB
        server_count: gameInterest.value || 'not specified',
      }),
    })
    if (!res.ok) {
      const data = await res.json().catch(() => ({ message: 'Something went wrong' }))
      throw new Error((data as { message?: string }).message ?? `HTTP ${res.status}`)
    }
    submitted.value = true
  } catch (err: unknown) {
    errorMsg.value = err instanceof Error ? err.message : 'Something went wrong'
  } finally {
    submitting.value = false
  }
}

// Scroll-reveal
let io: IntersectionObserver | null = null

function initReveal(): void {
  if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return
  io = new IntersectionObserver(
    (entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in')
          io?.unobserve(e.target)
        }
      })
    },
    { threshold: 0.1 },
  )
  document.querySelectorAll('.reveal').forEach((el) => io?.observe(el))
}

onMounted(() => { initReveal() })
onUnmounted(() => { io?.disconnect() })
</script>

<template>
  <!-- PAGE HEADER -->
  <section class="hero" style="padding-bottom:0; border-bottom:none;">
    <div class="hero__atmo" />
    <div class="hero__grid" />
    <div class="hero__grain" />
    <div class="wrap hero__in" style="padding-bottom:52px;">
      <div class="hero__mark">
        <CorrosionMark :size="56" />
      </div>
      <span class="eyebrow">Early access</span>
      <h1 style="font-size:var(--text-5xl)">
        Take control of your servers.
        <span class="accent">Starting now.</span>
      </h1>
      <p class="hero__sub">
        Corrosion is in early access. Join the list to be notified when your access opens.
        No spam. No fabricated scarcity.
      </p>
    </div>
  </section>

  <!-- WHAT YOU GET -->
  <section class="sec" id="access">
    <div class="wrap">
      <div class="sec__head reveal">
        <span class="eyebrow">What early access means</span>
        <h2 class="title">Real access to a real platform.</h2>
        <p class="lead">
          Early access is not a waitlist gimmick. It is how we manage onboarding while the
          platform stabilizes. You get the full Catalyst Console control plane — one tier at a time
          as capacity opens.
        </p>
      </div>

      <div class="infra reveal">
        <div class="icard">
          <div class="icard__ic"><Icon name="cpu" :size="16" /></div>
          <b>Full control plane</b>
          <p>re-Agent, Catalyst Console, wipes, plugins, schedules — all of it. Not a trimmed preview.</p>
        </div>
        <div class="icard">
          <div class="icard__ic"><Icon name="shield" :size="16" /></div>
          <b>Pricing you can lock in</b>
          <p>Early access pricing is the live pricing. No bait-and-switch after launch.</p>
        </div>
        <div class="icard">
          <div class="icard__ic"><Icon name="message-square" :size="16" /></div>
          <b>Direct feedback channel</b>
          <p>Early access operators have a direct feedback channel for platform bug reports and feature input.</p>
        </div>
        <div class="icard">
          <div class="icard__ic"><Icon name="box" :size="16" /></div>
          <b>Multi-game</b>
          <p>Rust is fully operational today. Dune: Awakening, Conan Exiles, and Soulmask support is in active development.</p>
        </div>
        <div class="icard">
          <div class="icard__ic"><Icon name="users" :size="16" /></div>
          <b>RBAC team access</b>
          <p>Add your admin team from day one. Fine-grained permission roles are built in.</p>
        </div>
      </div>
    </div>
  </section>

  <!-- SIGNUP FORM -->
  <section class="sec" id="join">
    <div class="wrap">
      <div class="ea-form-wrap reveal">
        <!-- Success state -->
        <div v-if="submitted" class="ea-success">
          <div class="ea-success__ic">
            <Icon name="check" :size="28" />
          </div>
          <h2 class="ea-success__title">You are on the list.</h2>
          <p class="ea-success__body">
            We will reach out when your access slot opens. In the meantime, read the
            <RouterLink :to="{ name: 'how-it-works' }" class="ea-link">how it works</RouterLink>
            guide or review the
            <RouterLink :to="{ name: 'faq' }" class="ea-link">FAQ</RouterLink>.
          </p>
          <RouterLink class="btn btn--ghost" :to="{ name: 'landing' }">
            Back to home
          </RouterLink>
        </div>

        <!-- Form state -->
        <form v-else @submit.prevent="handleSubmit" class="ea-form">
          <div class="ea-form__head">
            <h2>Join the early access list</h2>
            <p>Required: email address. Everything else is optional but helps us prioritise.</p>
          </div>

          <!-- Error banner -->
          <div v-if="errorMsg" class="ea-error">
            <Icon name="triangle-alert" :size="15" />
            {{ errorMsg }}
          </div>

          <!-- Email (required) -->
          <div class="ea-field">
            <label class="ea-field__label" for="ea-email">
              Email address <span class="ea-field__req">*</span>
            </label>
            <input
              id="ea-email"
              v-model="email"
              type="email"
              required
              autocomplete="email"
              placeholder="admin@example.com"
              class="ea-input"
            />
          </div>

          <!-- Name (optional) -->
          <div class="ea-field">
            <label class="ea-field__label" for="ea-name">
              Your name <span class="ea-field__optional">(optional)</span>
            </label>
            <input
              id="ea-name"
              v-model="name"
              type="text"
              autocomplete="name"
              placeholder="Server admin name or handle"
              class="ea-input"
            />
          </div>

          <!-- Game interest (optional) -->
          <div class="ea-field">
            <label class="ea-field__label">
              Primary game interest <span class="ea-field__optional">(optional)</span>
            </label>
            <div class="ea-pills">
              <button
                v-for="opt in GAME_OPTIONS"
                :key="opt.value"
                type="button"
                class="ea-pill"
                :class="{ 'ea-pill--on': gameInterest === opt.value }"
                @click="gameInterest = gameInterest === opt.value ? '' : opt.value"
              >
                {{ opt.label }}
              </button>
            </div>
          </div>

          <button
            type="submit"
            class="btn btn--primary btn--lg ea-submit"
            :disabled="submitting || !email"
          >
            <Icon v-if="submitting" name="loader" :size="16" />
            <Icon v-else name="send" :size="16" />
            {{ submitting ? 'Submitting…' : 'Join early access' }}
          </button>

          <p class="ea-privacy">
            We store your email to contact you when access opens. We do not sell or share it.
            No newsletters unless you opt in separately.
          </p>
        </form>
      </div>
    </div>
  </section>

  <!-- HOW IT WORKS TEASER -->
  <section class="sec" id="teaser">
    <div class="wrap">
      <div class="sec__head reveal">
        <span class="eyebrow">How it works</span>
        <h2 class="title">Install re-Agent. Never SSH again.</h2>
      </div>
      <div class="steps reveal">
        <div class="step">
          <div class="step__n">1</div>
          <b>Install re-Agent</b>
          <p>Download re-Agent from your dashboard. Run it on Windows or Linux. One agent per machine.</p>
        </div>
        <div class="step">
          <div class="step__n">2</div>
          <b>re-Agent connects to Corrosion</b>
          <p>Single outbound NATS connection. No inbound ports. No exposed management panel on your machine.</p>
        </div>
        <div class="step">
          <div class="step__n">3</div>
          <b>Manage from the browser</b>
          <p>Console, wipes, plugins, schedules, file manager, player management — all at panel.corrosionmgmt.com.</p>
        </div>
      </div>
      <div class="closing reveal">
        <RouterLink :to="{ name: 'how-it-works' }" class="btn btn--ghost btn--lg">
          <Icon name="chevron-right" :size="17" />Read the full walkthrough
        </RouterLink>
      </div>
    </div>
  </section>

  <!-- FINAL CTA -->
  <section class="finalcta">
    <div class="finalcta__atmo" />
    <div class="wrap finalcta__in reveal">
      <h2>Ready to stop babysitting<br>your servers?</h2>
      <div class="cta-row">
        <a href="#join" class="btn btn--primary btn--lg">
          Sign up above
        </a>
        <a class="btn btn--ghost btn--lg" :href="panelUrl + '/login'">
          <Icon name="key" :size="17" />Sign in
        </a>
      </div>
    </div>
  </section>
</template>

<style scoped>
/* Form wrapper */
.ea-form-wrap {
  max-width: 520px;
  margin: 0 auto;
}

/* Success state */
.ea-success {
  text-align: center;
  padding: 48px 32px;
  background: var(--surface-base);
  border-radius: var(--radius-xl);
  box-shadow: inset 0 0 0 1px var(--accent-border);
}
.ea-success__ic {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--accent-soft);
  color: var(--accent-text);
  box-shadow: inset 0 0 0 1px var(--accent-border);
  margin: 0 auto 18px;
}
.ea-success__title {
  font-family: var(--font-brand);
  font-weight: 700;
  font-size: var(--text-2xl);
  margin: 0 0 10px;
}
.ea-success__body {
  color: var(--text-tertiary);
  font-size: var(--text-sm);
  line-height: 1.6;
  margin: 0 0 24px;
}
.ea-link {
  color: var(--accent-text);
  text-decoration: none;
  font-weight: 600;
}
.ea-link:hover { text-decoration: underline; }

/* Form */
.ea-form {
  background: var(--surface-base);
  border-radius: var(--radius-xl);
  box-shadow: var(--ring-default);
  padding: 36px 32px;
  display: flex;
  flex-direction: column;
  gap: 22px;
}
.ea-form__head h2 {
  font-family: var(--font-brand);
  font-weight: 700;
  font-size: var(--text-2xl);
  margin: 0 0 6px;
}
.ea-form__head p {
  color: var(--text-tertiary);
  font-size: var(--text-sm);
  margin: 0;
}

/* Error banner */
.ea-error {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 14px;
  background: color-mix(in srgb, var(--status-offline) 10%, transparent);
  box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--status-offline) 25%, transparent);
  border-radius: var(--radius-md);
  color: var(--status-offline);
  font-size: var(--text-sm);
}

/* Fields */
.ea-field { display: flex; flex-direction: column; gap: 7px; }
.ea-field__label {
  font-size: var(--text-sm);
  font-weight: 600;
  color: var(--text-secondary);
}
.ea-field__req { color: var(--status-offline); }
.ea-field__optional { color: var(--text-muted); font-weight: 400; }

.ea-input {
  height: 42px;
  padding: 0 13px;
  background: var(--surface-inset);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-md);
  color: var(--text-primary);
  font-size: var(--text-sm);
  font-family: var(--font-sans);
  transition: border-color var(--dur-fast), box-shadow var(--dur-fast);
  outline: none;
}
.ea-input::placeholder { color: var(--text-muted); }
.ea-input:focus {
  border-color: var(--accent-border);
  box-shadow: 0 0 0 3px var(--accent-soft);
}

/* Game pills */
.ea-pills {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.ea-pill {
  height: 34px;
  padding: 0 14px;
  border-radius: var(--radius-pill);
  background: var(--surface-raised);
  box-shadow: var(--ring-default);
  color: var(--text-secondary);
  font-size: var(--text-xs);
  font-weight: 600;
  cursor: pointer;
  border: none;
  transition: var(--transition-colors);
}
.ea-pill--on {
  background: var(--accent-soft);
  color: var(--accent-text);
  box-shadow: inset 0 0 0 1px var(--accent-border);
}

/* Submit */
.ea-submit {
  width: 100%;
  justify-content: center;
}
.ea-submit:disabled { opacity: 0.55; cursor: not-allowed; }

/* Privacy note */
.ea-privacy {
  font-size: var(--text-xs);
  color: var(--text-muted);
  text-align: center;
  line-height: 1.5;
  margin: 0;
}
</style>
