'use client';

import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { useEffect, useRef } from 'react';
// Session S7 (a1) — THE VYNDR REPORT capture on the free-signup success path.
// This page (not the signup "done" card, which auto-redirects after 1.5s) is
// where a new free user actually lingers — the honest place for the ask.
import NewsletterCapture from '@/components/NewsletterCapture';

export default function WelcomePage() {
  const router = useRouter();
  const { user, session, loading } = useAuth();
  const welcomeFiredRef = useRef(false);

  useEffect(() => {
    if (!loading && !user) router.replace('/signup');
  }, [loading, user, router]);

  // Session 10 — trigger the welcome email exactly once per mount.
  // The server-side handler is idempotent via user_metadata
  // (welcome_email_sent flag), so re-triggers from a refresh are
  // safe; the ref is just a UX optimization to avoid duplicate
  // network requests on this page.
  useEffect(() => {
    if (welcomeFiredRef.current) return;
    if (loading || !user || !session) return;
    welcomeFiredRef.current = true;
    fetch('/api/welcome-email', {
      method: 'POST',
      headers: { Authorization: `Bearer ${session.access_token}` },
    }).catch(() => {
      // Fail silent — onboarding must not block on email outages.
    });
  }, [loading, user, session]);

  return (
    <section
      className="tex-scan"
      style={{
        position: 'relative',
        minHeight: 'calc(100vh - 144px)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        textAlign: 'center',
        padding: '40px 24px',
        overflow: 'hidden',
      }}
    >
      <span className="v-watermark" aria-hidden>V</span>

      <SlashedYMark />

      <h1
        style={{
          marginTop: 32,
          fontSize: 'clamp(26px, 4vw, 36px)',
          fontWeight: 700,
          letterSpacing: '-0.02em',
          color: 'var(--text-0)',
          zIndex: 1,
        }}
      >
        Welcome to VYNDR.
      </h1>
      <p
        style={{
          marginTop: 12,
          fontSize: 16,
          color: 'var(--text-1)',
          maxWidth: 460,
          zIndex: 1,
        }}
      >
        Intelligence the books don&apos;t want you to have.
      </p>

      <div style={{ marginTop: 28, display: 'grid', gap: 12, zIndex: 1 }}>
        <button
          type="button"
          className="btn-primary"
          style={{ padding: '14px 32px', fontSize: 15 }}
          onClick={() => router.push('/dashboard')}
        >
          Get Started →
        </button>
        <p className="lbl" style={{ color: 'var(--text-2)' }}>BUILT IN DETROIT</p>
      </div>

      {/* Session S7 (a1) — the daily wire, by email. Double opt-in via Listmonk. */}
      <div style={{ marginTop: 32, width: '100%', maxWidth: 440, textAlign: 'left', zIndex: 1 }}>
        <NewsletterCapture compact />
      </div>
    </section>
  );
}

function SlashedYMark() {
  return (
    <svg
      width="120"
      height="120"
      viewBox="0 0 120 120"
      aria-hidden
      style={{
        filter: 'drop-shadow(0 0 18px rgba(0, 212, 160, 0.55)) drop-shadow(0 0 36px rgba(0, 212, 160, 0.25))',
        animation: 'phosphor-pulse 2.4s ease-in-out infinite',
        zIndex: 1,
      }}
    >
      <defs>
        <linearGradient id="ymark-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#00FFB8" />
          <stop offset="100%" stopColor="#00D4A0" />
        </linearGradient>
      </defs>
      <g stroke="url(#ymark-grad)" strokeWidth="10" strokeLinecap="round" fill="none">
        <line x1="20" y1="20" x2="60" y2="64" />
        <line x1="60" y1="64" x2="60" y2="100" />
        <line x1="8" y1="110" x2="112" y2="6" strokeWidth="9" />
      </g>
    </svg>
  );
}
