'use client';

import { PulseLink } from '@/components/pulse';
import { apiFetch } from '@/lib/api';
import { useEffect, useState } from 'react';

/**
 * Marketing-header CTA that reflects the session: logged-out visitors see a
 * "Login" button, signed-in users see "Dashboard". Same button slot so the
 * header layout doesn't shift between states.
 *
 * While the auth probe is in flight (`authed === null`) we default to the
 * logged-out label — most marketing-page visitors are anonymous, so this
 * avoids a "Dashboard → Login" flicker for them. Authed users see a single
 * "Login → Dashboard" swap once the /v1/auth/me round-trip completes.
 */
export function MarketingAuthButtons() {
  const [authed, setAuthed] = useState<boolean | null>(null);

  useEffect(() => {
    apiFetch('/v1/auth/me')
      .then(() => setAuthed(true))
      .catch(() => setAuthed(false));
  }, []);

  const showDashboard = authed === true;

  return (
    <PulseLink
      href={showDashboard ? '/dashboard' : '/login'}
      className="rounded-md bg-[--color-accent] px-3 py-1.5 text-[13px] font-medium text-white transition-colors duration-200 hover:bg-[#5557e8]"
    >
      {showDashboard ? 'Dashboard' : 'Login'}
    </PulseLink>
  );
}
