import { type ReactElement, type SVGProps, useEffect, useState } from 'react';
import { APIProvider } from '@vis.gl/react-google-maps';
import {
  AlertCircle,
  ArrowRight,
  Briefcase,
  Building2,
  Check,
  LogIn,
  Map,
  MapPinned,
  Search,
  ShieldAlert,
  Sparkles,
  User,
  UserPlus,
} from 'lucide-react';
import { Layout, type AppTab } from './components/Layout';
import { Dashboard } from './components/Dashboard';
import { MapView } from './components/MapView';
import { ResearchWorkspace } from './components/ResearchWorkspace';
import { ResultsWorkspace } from './components/ResultsWorkspace';
import type { SessionUser } from '../shared/types';
import { getLocalSessionUser, signInWithLocalAuth, signOutWithLocalAuth, signUpWithLocalAuth } from './lib/auth';
import { hasApiConfig } from './lib/api';

const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_PLATFORM_KEY ?? '';
const hasValidMapsKey = Boolean(GOOGLE_MAPS_API_KEY) && GOOGLE_MAPS_API_KEY !== 'YOUR_API_KEY';

export default function App() {
  const [publicPage, setPublicPage] = useState<'landing' | 'auth'>(() => getPublicPageFromLocation());
  const [user, setUser] = useState<SessionUser | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<AppTab>('setup');
  const [selectedJobIds, setSelectedJobIds] = useState<string[]>([]);
  const [authError, setAuthError] = useState<string | null>(null);
  const [authNotice, setAuthNotice] = useState<string | null>(null);
  const [isAuthenticating, setIsAuthenticating] = useState(false);
  const [authMode, setAuthMode] = useState<'sign_in' | 'sign_up'>('sign_in');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [displayName, setDisplayName] = useState('');

  useEffect(() => {
    const handlePopState = () => {
      setPublicPage(getPublicPageFromLocation());
    };

    window.addEventListener('popstate', handlePopState);

    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, []);

  useEffect(() => {
    let isMounted = true;

    const loadSession = async () => {
      try {
        const sessionUser = await getLocalSessionUser();

        if (!isMounted) {
          return;
        }

        setUser(sessionUser);
      } catch (error) {
        if (!isMounted) {
          return;
        }

        setAuthError(error instanceof Error ? error.message : 'Failed to load session.');
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    void loadSession();

    return () => {
      isMounted = false;
    };
  }, []);

  const handleToggleJobSelection = (jobId: string) => {
    setSelectedJobIds((currentJobIds) =>
      currentJobIds.includes(jobId) ? currentJobIds.filter((currentJobId) => currentJobId !== jobId) : [...currentJobIds, jobId],
    );
  };

  const handleSelectCreatedJob = (jobId: string) => {
    setSelectedJobIds((currentJobIds) => (currentJobIds.includes(jobId) ? currentJobIds : [...currentJobIds, jobId]));
  };

  const handleShowSelectedOnMap = () => {
    if (selectedJobIds.length === 0) {
      return;
    }

    setActiveTab('map');
  };

  const handleClearSelectedJobs = () => {
    setSelectedJobIds([]);
  };

  const handleShowJobIdsOnMap = (jobIds: string[]) => {
    setSelectedJobIds(jobIds);
    setActiveTab('map');
  };

  const handleLogin = async () => {
    setAuthError(null);
    setAuthNotice(null);
    setIsAuthenticating(true);

    try {
      if (authMode === 'sign_up') {
        const nextUser = await signUpWithLocalAuth({
          email,
          password,
          displayName: displayName.trim() || undefined,
        });

        setUser(nextUser);
        setAuthNotice('Account created and signed in.');
        return;
      }

      const nextUser = await signInWithLocalAuth({
        email,
        password,
      });

      setUser(nextUser);
      navigatePublicPage('landing', setPublicPage);
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : 'Authentication failed.');
    } finally {
      setIsAuthenticating(false);
    }
  };

  const handleLogout = async () => {
    const sessionId = user?.sessionId;

    setAuthError(null);
    setAuthNotice(null);
    setSelectedJobIds([]);
    setUser(null);
    setActiveTab('setup');

    try {
      await signOutWithLocalAuth(sessionId);
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : 'Failed to sign out.');
    }
  };

  if (loading) {
    return (
      <div className="flex h-screen items-center justify-center bg-stone-50">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-emerald-500 border-t-transparent"></div>
      </div>
    );
  }

  if (!hasApiConfig) {
    return (
      <ConfigScreen
        icon={<ShieldAlert className="h-8 w-8" />}
        title="Local API Config Required"
        description="Add your local API base URL before running the app."
        steps={[
          'Start the local Fastify API server.',
          'Add VITE_API_BASE_URL to your local environment.',
          'Ensure the API can reach your local PostgreSQL database.',
          'Restart the Vite dev server after updating env vars.',
        ]}
        footer="The app now uses a local API, PostgreSQL, and local session auth."
      />
    );
  }

  if (!user) {
    const handleSetAuthMode = (mode: 'sign_in' | 'sign_up') => {
      setAuthMode(mode);
      setAuthError(null);
      setAuthNotice(null);
    };

    if (publicPage === 'auth') {
      return (
        <AuthPage
          authMode={authMode}
          authError={authError}
          authNotice={authNotice}
          displayName={displayName}
          email={email}
          isAuthenticating={isAuthenticating}
          password={password}
          onDisplayNameChange={setDisplayName}
          onEmailChange={setEmail}
          onPasswordChange={setPassword}
          onGoHome={() => navigatePublicPage('landing', setPublicPage)}
          onSetAuthMode={handleSetAuthMode}
          onSubmit={() => void handleLogin()}
        />
      );
    }

    return (
      <LandingPage
        onGoToAuth={(mode) => {
          handleSetAuthMode(mode);
          navigatePublicPage('auth', setPublicPage);
        }}
      />
    );
  }

  if (!hasValidMapsKey) {
    return (
      <ConfigScreen
        icon={<MapIcon className="h-8 w-8" />}
        title="Google Maps API Key Required"
        description="Add a browser key for map rendering and a server key for the local search API."
        steps={[
          'Create a Google Maps Platform API key for the browser app.',
          'Set VITE_GOOGLE_MAPS_PLATFORM_KEY locally for the frontend.',
          'Set GOOGLE_MAPS_SERVER_KEY for the local API server.',
          'Enable Geocoding API and Places API in Google Cloud.',
        ]}
        footer="You can create a local account without the maps key, but the workspace needs it before loading." 
      />
    );
  }

  return (
    <APIProvider apiKey={GOOGLE_MAPS_API_KEY} version="weekly">
      <Layout
        user={user}
        activeTab={activeTab}
        setActiveTab={setActiveTab}
        onLogout={() => void handleLogout()}
      >
        {activeTab === 'setup' && (
          <ResearchWorkspace
            user={user}
            selectedJobIds={selectedJobIds}
            onToggleJobSelection={handleToggleJobSelection}
            onSelectCreatedJob={handleSelectCreatedJob}
            onShowSelectedOnMap={handleShowSelectedOnMap}
            onClearSelection={handleClearSelectedJobs}
            onShowBatchOnMap={handleShowJobIdsOnMap}
          />
        )}
        {activeTab === 'results' && (
          <ResultsWorkspace
            user={user}
            selectedJobIds={selectedJobIds}
            onToggleJobSelection={handleToggleJobSelection}
            onShowSelectedOnMap={handleShowSelectedOnMap}
            onClearSelection={handleClearSelectedJobs}
            onShowBatchOnMap={handleShowJobIdsOnMap}
          />
        )}
        {activeTab === 'dashboard' && <Dashboard user={user} />}
        {activeTab === 'map' && <MapView user={user} jobIds={selectedJobIds} />}
      </Layout>
    </APIProvider>
  );
}

function getPublicPageFromLocation(): 'landing' | 'auth' {
  if (typeof window === 'undefined') {
    return 'landing';
  }

  return window.location.pathname === '/auth' ? 'auth' : 'landing';
}

function navigatePublicPage(page: 'landing' | 'auth', setPublicPage: (page: 'landing' | 'auth') => void) {
  const nextPath = page === 'auth' ? '/auth' : '/';

  if (typeof window !== 'undefined' && window.location.pathname !== nextPath) {
    window.history.pushState({}, '', nextPath);
  }

  setPublicPage(page);
}

function LandingPage(props: {
  onGoToAuth: (mode: 'sign_in' | 'sign_up') => void;
}) {
  const { onGoToAuth } = props;

  const featureCards = [
    {
      icon: Search,
      title: 'Research Runs',
      description: 'Search by city, radius, business type, and keywords without juggling spreadsheets or manual lookups.',
    },
    {
      icon: MapPinned,
      title: 'Deep Research',
      description: 'Drop one pin and expand intelligently into nearby postal areas to widen market coverage.',
    },
    {
      icon: Map,
      title: 'Clean Map View',
      description: 'Review returned businesses on a focused map built for operational decision-making, not map clutter.',
    },
    {
      icon: Briefcase,
      title: 'Lead Workspace',
      description: 'Keep past runs, saved businesses, and mapped results in one place for repeatable prospecting.',
    },
  ] as const;

  const audienceCards = [
    {
      icon: User,
      title: 'Personal Use',
      description: 'For solo operators, freelancers, and independent prospectors who need a focused local research workflow.',
    },
    {
      icon: Building2,
      title: 'Small Business',
      description: 'For agencies and local teams running prospecting every week across multiple service areas.',
    },
    {
      icon: Sparkles,
      title: 'Enterprise',
      description: 'For larger organizations that need custom research volume, rollout support, and tailored operating limits.',
    },
  ] as const;

  const plans = [
    {
      name: 'Personal',
      audience: 'For solo operators',
      price: '$19',
      period: '/month',
      cta: 'Start free',
      featured: false,
      items: ['1 user workspace', '40 research runs / month', 'Map view and dashboard history', 'Email support'],
    },
    {
      name: 'Small Business',
      audience: 'For growing local teams',
      price: '$79',
      period: '/month',
      cta: 'Choose Small Business',
      featured: true,
      items: ['Everything in Personal', '250 research runs / month', 'Deep research workflows', 'Extended lead history', 'Priority support'],
    },
    {
      name: 'Enterprise',
      audience: 'For custom rollouts',
      price: 'Contact',
      period: 'sales',
      cta: 'Talk to sales',
      featured: false,
      items: ['Custom research volume', 'Custom onboarding plan', 'Tailored support model', 'Deployment and process guidance'],
    },
  ] as const;

  return (
    <div className="min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(16,185,129,0.12),_transparent_28%),linear-gradient(180deg,#fafaf9_0%,#f5f5f4_100%)] text-stone-900">
      <div className="mx-auto max-w-7xl px-4 pb-16 pt-4 sm:px-6 lg:px-8 lg:pb-24">
        <header className="sticky top-4 z-10 rounded-3xl border border-white/70 bg-white/80 px-5 py-4 shadow-sm backdrop-blur md:px-6">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div className="flex items-center gap-3">
              <div className="rounded-2xl bg-emerald-600 p-2.5 text-white shadow-sm">
                <Briefcase className="h-5 w-5" />
              </div>
              <div>
                <p className="text-lg font-bold tracking-tight">Leads4less</p>
                <p className="text-sm text-stone-500">Local market research for modern teams</p>
              </div>
            </div>

            <nav className="flex flex-wrap items-center gap-3 text-sm font-medium text-stone-600">
              <a href="#product" className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900">
                Product
              </a>
              <a href="#workflow" className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900">
                Workflow
              </a>
              <a href="#pricing" className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900">
                Pricing
              </a>
              <button
                type="button"
                onClick={() => onGoToAuth('sign_in')}
                className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900"
              >
                Sign In
              </button>
              <button
                type="button"
                onClick={() => onGoToAuth('sign_up')}
                className="inline-flex items-center gap-2 rounded-full bg-emerald-600 px-4 py-2 text-white shadow-sm transition hover:bg-emerald-700"
              >
                Sign Up
                <ArrowRight className="h-4 w-4" />
              </button>
            </nav>
          </div>
        </header>

        <section className="py-12 lg:py-16">
          <div className="space-y-8">
            <div className="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm font-medium text-emerald-700">
              <Sparkles className="h-4 w-4" />
              Built for local lead generation workflows
            </div>

            <div className="space-y-5">
              <h1 className="max-w-4xl text-5xl font-bold tracking-tight text-stone-950 sm:text-6xl">
                Research local markets, map opportunities, and build better lead lists faster.
              </h1>
              <p className="max-w-3xl text-lg leading-8 text-stone-600 sm:text-xl">
                Run targeted searches, expand coverage from a single pin, and review every result in one focused workspace designed for real prospecting operations.
              </p>
            </div>

            <div className="flex flex-col gap-3 sm:flex-row">
              <button
                type="button"
                onClick={() => onGoToAuth('sign_up')}
                className="inline-flex items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-6 py-4 text-sm font-semibold text-white shadow-sm transition hover:bg-emerald-700"
              >
                Sign Up
                <ArrowRight className="h-4 w-4" />
              </button>
              <a
                href="#pricing"
                className="inline-flex items-center justify-center rounded-2xl border border-stone-200 bg-white px-6 py-4 text-sm font-semibold text-stone-700 shadow-sm transition hover:border-stone-300 hover:bg-stone-50"
              >
                See pricing
              </a>
            </div>
          </div>
        </section>

        <section id="product" className="rounded-[2rem] border border-stone-200 bg-white px-6 py-10 shadow-sm sm:px-8 lg:px-10">
          <div className="max-w-3xl">
            <p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Product</p>
            <h2 className="mt-3 text-3xl font-bold tracking-tight text-stone-900 sm:text-4xl">One workspace for local lead generation</h2>
            <p className="mt-4 text-base leading-8 text-stone-600">
              Leads4less keeps market research, deep area expansion, map review, and saved business history in a single operating flow so your team can move faster without losing context.
            </p>
          </div>

          <div className="mt-8 grid gap-4 lg:grid-cols-3">
            <div className="rounded-3xl bg-stone-950 p-6 text-white lg:col-span-2">
              <p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-300">Operational Workflow</p>
              <p className="mt-4 text-2xl font-bold tracking-tight">Search a market, expand intelligently, and review results visually.</p>
              <p className="mt-4 max-w-2xl text-sm leading-7 text-stone-300">
                Instead of stitching together Google tabs, spreadsheets, and hand-written notes, run the full prospecting loop from one product surface built for repeatable research. Launch deeper market coverage from a single map interaction while keeping research, deep research, dashboard, and map review connected in one workspace.
              </p>
            </div>
            <div className="rounded-3xl border border-stone-200 bg-stone-50 p-6">
              <p className="text-sm font-semibold uppercase tracking-[0.18em] text-stone-500">Best Fit</p>
              <p className="mt-4 text-2xl font-bold tracking-tight text-stone-900">Local teams who need speed and structure</p>
              <p className="mt-4 text-sm leading-7 text-stone-600">Built for recurring lead generation, territory research, and targeted market expansion.</p>
            </div>
          </div>
        </section>

        <section id="workflow" className="py-16">
          <div className="max-w-3xl">
            <p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Workflow</p>
            <h2 className="mt-3 text-3xl font-bold tracking-tight text-stone-900 sm:text-4xl">A clear research process from first search to mapped review</h2>
          </div>

          <div className="mt-8 grid gap-4 lg:grid-cols-4">
            {[
              ['01', 'Search', 'Start with location, radius, business type, and optional keywords.'],
              ['02', 'Expand', 'Use deep research to fan out from a pin into nearby postal areas.'],
              ['03', 'Review', 'Inspect returned businesses on a clean map and in the dashboard.'],
              ['04', 'Act', 'Keep high-value results organized for follow-up and repeated market work.'],
            ].map(([step, title, description]) => (
              <div key={step} className="rounded-3xl border border-stone-200 bg-white p-6 shadow-sm">
                <p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">{step}</p>
                <h3 className="mt-4 text-xl font-bold tracking-tight text-stone-900">{title}</h3>
                <p className="mt-3 text-sm leading-7 text-stone-600">{description}</p>
              </div>
            ))}
          </div>
        </section>

        <section className="rounded-[2rem] border border-stone-200 bg-white px-6 py-10 shadow-sm sm:px-8 lg:px-10">
          <div className="max-w-3xl">
            <p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Who It's For</p>
            <h2 className="mt-3 text-3xl font-bold tracking-tight text-stone-900 sm:text-4xl">Designed for personal use, small business teams, and enterprise rollouts</h2>
          </div>

          <div className="mt-8 grid gap-4 lg:grid-cols-3">
            {audienceCards.map((audience) => (
              <div key={audience.title} className="rounded-3xl border border-stone-200 bg-stone-50 p-6">
                <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-white text-emerald-600 shadow-sm">
                  <audience.icon className="h-5 w-5" />
                </div>
                <h3 className="mt-5 text-xl font-bold tracking-tight text-stone-900">{audience.title}</h3>
                <p className="mt-3 text-sm leading-7 text-stone-600">{audience.description}</p>
              </div>
            ))}
          </div>
        </section>

        <section id="pricing" className="py-16">
          <div className="max-w-3xl">
            <p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Pricing</p>
            <h2 className="mt-3 text-3xl font-bold tracking-tight text-stone-900 sm:text-4xl">Choose the plan that matches your research volume</h2>
            <p className="mt-4 text-base leading-8 text-stone-600">
              Start small, run local research consistently, and upgrade when your market coverage or team needs expand.
            </p>
          </div>

          <div className="mt-8 grid gap-5 xl:grid-cols-3">
            {plans.map((plan) => (
              <div
                key={plan.name}
                className={`rounded-[2rem] border p-7 shadow-sm ${
                  plan.featured ? 'border-emerald-300 bg-emerald-50/60 shadow-emerald-100' : 'border-stone-200 bg-white'
                }`}
              >
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <p className="text-xl font-bold tracking-tight text-stone-900">{plan.name}</p>
                    <p className="mt-2 text-sm text-stone-600">{plan.audience}</p>
                  </div>
                  {plan.featured && (
                    <span className="rounded-full bg-emerald-600 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-white">
                      Most Popular
                    </span>
                  )}
                </div>

                <div className="mt-8 flex items-end gap-1">
                  <span className="text-4xl font-bold tracking-tight text-stone-950">{plan.price}</span>
                  <span className="pb-1 text-sm text-stone-500">{plan.period}</span>
                </div>

                <button
                  type="button"
                  onClick={() => onGoToAuth(plan.name === 'Enterprise' ? 'sign_in' : 'sign_up')}
                  className={`mt-8 inline-flex w-full items-center justify-center rounded-2xl px-4 py-3 text-sm font-semibold transition ${
                    plan.featured
                      ? 'bg-emerald-600 text-white hover:bg-emerald-700'
                      : 'border border-stone-200 bg-white text-stone-800 hover:bg-stone-50'
                  }`}
                >
                  {plan.cta}
                </button>

                <div className="mt-8 space-y-3">
                  {plan.items.map((item) => (
                    <div key={item} className="flex items-start gap-3 text-sm text-stone-700">
                      <div className="mt-0.5 flex h-5 w-5 items-center justify-center rounded-full bg-emerald-100 text-emerald-700">
                        <Check className="h-3.5 w-3.5" />
                      </div>
                      <span>{item}</span>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </section>

        <section className="rounded-[2rem] bg-stone-950 px-6 py-12 text-white shadow-sm sm:px-8 lg:px-10">
          <div className="flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
            <div className="max-w-3xl">
              <p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-300">Start Now</p>
              <h2 className="mt-3 text-3xl font-bold tracking-tight sm:text-4xl">Turn local market research into a repeatable system.</h2>
              <p className="mt-4 text-base leading-8 text-stone-300">
                Create an account, run your first research job, and build a cleaner lead workflow from day one.
              </p>
            </div>
            <div className="flex flex-col gap-3 sm:flex-row">
              <button
                type="button"
                onClick={() => onGoToAuth('sign_up')}
                className="inline-flex items-center justify-center gap-2 rounded-2xl bg-emerald-500 px-6 py-4 text-sm font-semibold text-white transition hover:bg-emerald-400"
              >
                Choose a plan
                <ArrowRight className="h-4 w-4" />
              </button>
              <a
                href="#pricing"
                className="inline-flex items-center justify-center rounded-2xl border border-white/20 px-6 py-4 text-sm font-semibold text-white transition hover:bg-white/10"
              >
                Compare plans
              </a>
            </div>
          </div>
        </section>
      </div>
    </div>
  );
}

function AuthPage(props: {
  authMode: 'sign_in' | 'sign_up';
  authError: string | null;
  authNotice: string | null;
  displayName: string;
  email: string;
  isAuthenticating: boolean;
  password: string;
  onDisplayNameChange: (value: string) => void;
  onEmailChange: (value: string) => void;
  onPasswordChange: (value: string) => void;
  onGoHome: () => void;
  onSetAuthMode: (mode: 'sign_in' | 'sign_up') => void;
  onSubmit: () => void;
}) {
  const {
    authMode,
    authError,
    authNotice,
    displayName,
    email,
    isAuthenticating,
    password,
    onDisplayNameChange,
    onEmailChange,
    onPasswordChange,
    onGoHome,
    onSetAuthMode,
    onSubmit,
  } = props;

  return (
    <div className="min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(16,185,129,0.12),_transparent_30%),linear-gradient(180deg,#fafaf9_0%,#f5f5f4_100%)] text-stone-900">
      <div className="mx-auto max-w-7xl px-4 py-4 sm:px-6 lg:px-8">
        <header className="rounded-3xl border border-white/70 bg-white/80 px-5 py-4 shadow-sm backdrop-blur md:px-6">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <button type="button" onClick={onGoHome} className="flex items-center gap-3 text-left">
              <div className="rounded-2xl bg-emerald-600 p-2.5 text-white shadow-sm">
                <Briefcase className="h-5 w-5" />
              </div>
              <div>
                <p className="text-lg font-bold tracking-tight">Leads4less</p>
                <p className="text-sm text-stone-500">Local market research for modern teams</p>
              </div>
            </button>

            <div className="flex items-center gap-3 text-sm font-medium text-stone-600">
              <button type="button" onClick={onGoHome} className="rounded-full px-3 py-2 transition hover:bg-stone-100 hover:text-stone-900">
                Back to home
              </button>
            </div>
          </div>
        </header>

        <section className="grid gap-10 py-12 lg:grid-cols-[minmax(0,1fr)_440px] lg:items-center lg:py-16">
          <div className="space-y-8">
            <div className="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm font-medium text-emerald-700">
              <Sparkles className="h-4 w-4" />
              Secure access to your lead workspace
            </div>

            <div className="space-y-5">
              <h1 className="max-w-3xl text-5xl font-bold tracking-tight text-stone-950 sm:text-6xl">
                {authMode === 'sign_up' ? 'Create your workspace and start researching local markets.' : 'Sign in and continue your lead research workflow.'}
              </h1>
              <p className="max-w-2xl text-lg leading-8 text-stone-600 sm:text-xl">
                Access research runs, deep research coverage, clean map review, and saved business history from one focused operating surface.
              </p>
            </div>

            <div className="grid gap-4 sm:grid-cols-3">
              {[
                ['Targeted search', 'Run location-based business research with clear inputs and repeatable jobs.'],
                ['Map review', 'Inspect returned businesses on a cleaner map built for operational use.'],
                ['Persistent history', 'Keep lead runs and saved businesses available whenever you come back.'],
              ].map(([title, description]) => (
                <div key={title} className="rounded-3xl border border-stone-200 bg-white p-5 shadow-sm">
                  <p className="text-base font-bold tracking-tight text-stone-900">{title}</p>
                  <p className="mt-2 text-sm leading-7 text-stone-600">{description}</p>
                </div>
              ))}
            </div>
          </div>

          <div className="rounded-[2rem] border border-stone-200 bg-white p-6 shadow-xl shadow-stone-200/70 sm:p-8">
            <div className="mb-6 flex items-center justify-between">
              <div>
                <p className="text-sm font-semibold uppercase tracking-[0.18em] text-emerald-600">Account Access</p>
                <h2 className="mt-2 text-2xl font-bold tracking-tight text-stone-900">
                  {authMode === 'sign_up' ? 'Create account' : 'Sign in'}
                </h2>
                <p className="mt-2 text-sm text-stone-600">
                  {authMode === 'sign_up' ? 'Set up your account to start using Leads4less.' : 'Use your account to continue where you left off.'}
                </p>
              </div>
              <div className="rounded-2xl bg-emerald-50 p-3 text-emerald-600">
                {authMode === 'sign_up' ? <UserPlus className="h-6 w-6" /> : <LogIn className="h-6 w-6" />}
              </div>
            </div>

            <div className="grid grid-cols-2 gap-2 rounded-2xl bg-stone-100 p-1">
              <button
                type="button"
                onClick={() => onSetAuthMode('sign_in')}
                className={`rounded-xl px-3 py-2.5 text-sm font-semibold transition-all ${
                  authMode === 'sign_in' ? 'bg-white text-stone-900 shadow-sm' : 'text-stone-500 hover:text-stone-900'
                }`}
              >
                Sign In
              </button>
              <button
                type="button"
                onClick={() => onSetAuthMode('sign_up')}
                className={`rounded-xl px-3 py-2.5 text-sm font-semibold transition-all ${
                  authMode === 'sign_up' ? 'bg-white text-stone-900 shadow-sm' : 'text-stone-500 hover:text-stone-900'
                }`}
              >
                Sign Up
              </button>
            </div>

            {authError && (
              <div className="mt-5 flex items-start gap-3 rounded-2xl border border-red-100 bg-red-50 p-4 text-sm text-red-700">
                <AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0" />
                <div>
                  <p className="font-semibold">Authentication Error</p>
                  <p className="mt-1 opacity-90">{authError}</p>
                </div>
              </div>
            )}

            {authNotice && <div className="mt-5 rounded-2xl border border-emerald-100 bg-emerald-50 p-4 text-sm text-emerald-700">{authNotice}</div>}

            <form
              className="mt-5 space-y-4"
              onSubmit={(event) => {
                event.preventDefault();
                onSubmit();
              }}
            >
              {authMode === 'sign_up' && (
                <div>
                  <label className="mb-2 block text-sm font-semibold text-stone-700">Name</label>
                  <input
                    type="text"
                    value={displayName}
                    onChange={(event) => onDisplayNameChange(event.target.value)}
                    placeholder="Your name"
                    className="w-full rounded-2xl border border-stone-200 bg-stone-50 px-4 py-3 text-sm outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
                  />
                </div>
              )}

              <div>
                <label className="mb-2 block text-sm font-semibold text-stone-700">Email</label>
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(event) => onEmailChange(event.target.value)}
                  placeholder="you@example.com"
                  className="w-full rounded-2xl border border-stone-200 bg-stone-50 px-4 py-3 text-sm outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
                />
              </div>

              <div>
                <label className="mb-2 block text-sm font-semibold text-stone-700">Password</label>
                <input
                  type="password"
                  required
                  minLength={6}
                  value={password}
                  onChange={(event) => onPasswordChange(event.target.value)}
                  placeholder="At least 6 characters"
                  className="w-full rounded-2xl border border-stone-200 bg-stone-50 px-4 py-3 text-sm outline-none transition-all focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500"
                />
              </div>

              <button
                type="submit"
                disabled={isAuthenticating}
                className="flex w-full items-center justify-center gap-3 rounded-2xl bg-emerald-600 px-4 py-3.5 text-sm font-semibold text-white shadow-sm transition-all hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
              >
                {isAuthenticating ? (
                  <div className="h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"></div>
                ) : authMode === 'sign_up' ? (
                  <UserPlus className="h-5 w-5" />
                ) : (
                  <LogIn className="h-5 w-5" />
                )}
                {isAuthenticating
                  ? authMode === 'sign_up'
                    ? 'Creating account...'
                    : 'Signing in...'
                  : authMode === 'sign_up'
                    ? 'Create Account'
                    : 'Sign In'}
              </button>
            </form>
          </div>
        </section>
      </div>
    </div>
  );
}

function ConfigScreen(props: {
  icon: ReactElement;
  title: string;
  description: string;
  steps: string[];
  footer: string;
}) {
  const { icon, title, description, steps, footer } = props;

  return (
    <div className="flex h-screen items-center justify-center bg-stone-50 p-6 font-sans">
      <div className="w-full max-w-lg rounded-2xl bg-white p-8 text-center shadow-xl">
        <div className="mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-red-100 text-red-600">
          {icon}
        </div>
        <h2 className="mb-4 text-2xl font-bold text-stone-900">{title}</h2>
        <p className="mb-6 text-left text-stone-600">{description}</p>
        <div className="mb-6 space-y-4 rounded-xl border border-stone-200 bg-stone-50 p-6 text-left">
          <p className="text-sm font-medium text-stone-900">Follow these steps:</p>
          <ol className="list-inside list-decimal space-y-2 text-sm text-stone-600">
            {steps.map((step) => (
              <li key={step}>{step}</li>
            ))}
          </ol>
        </div>
        <p className="text-xs text-stone-400">{footer}</p>
      </div>
    </div>
  );
}

function MapIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <polygon points="3 6 9 3 15 6 21 3 21 18 15 21 9 18 3 21" />
      <line x1="9" y1="3" x2="9" y2="18" />
      <line x1="15" y1="6" x2="15" y2="21" />
    </svg>
  );
}
