"use client";

import { useState } from "react";
import Link from "next/link";
import {
  ScanLine,
  Mail,
  Upload,
  Users,
  BarChart3,
  Shield,
  Zap,
  ArrowRight,
  Check,
  ChevronDown,
  ChevronUp,
  Church,
  Globe,
  Workflow,
  Clock,
  Heart,
  Building2,
  CalendarDays,
  FileText,
  Webhook,
} from "lucide-react";
import { MarketingNav } from "@/components/marketing/nav";
import { MarketingFooter } from "@/components/marketing/footer";

function Hero() {
  return (
    <section className="relative pt-32 pb-20 sm:pt-40 sm:pb-28 overflow-hidden">
      <div className="absolute inset-0 gradient-mesh pointer-events-none" />
      <div className="relative mx-auto max-w-4xl px-6 text-center">
        <div className="inline-flex items-center gap-2 rounded-full border border-border/60 bg-card/60 px-4 py-1.5 text-xs font-medium text-muted-foreground mb-8 glass">
          <Church className="h-3.5 w-3.5" />
          Built for churches &amp; ministries
        </div>
        <h1 className="text-4xl sm:text-5xl lg:text-6xl font-bold tracking-tight leading-[1.1] mb-6">
          Stop hand-typing
          <br />
          <span className="bg-gradient-to-r from-primary via-foreground to-primary bg-clip-text text-transparent">
            visitor cards.
          </span>
        </h1>
        <p className="text-lg sm:text-xl text-muted-foreground max-w-2xl mx-auto mb-10 leading-relaxed">
          Echo uses AI-powered OCR to scan your guest cards, prayer requests, and
          response forms &mdash; then sends the data straight into Planning Center,
          your CRM, or wherever your team needs it. In seconds, not hours.
        </p>
        <div className="flex flex-col sm:flex-row items-center justify-center gap-4">
          <Link
            href="/signup"
            className="inline-flex items-center gap-2 rounded-xl bg-primary px-8 py-3.5 text-base font-semibold text-primary-foreground shadow-lg hover:opacity-90 transition-opacity"
          >
            Start Free &mdash; 50 Cards/Month
            <ArrowRight className="h-4 w-4" />
          </Link>
          <a
            href="#how-it-works"
            className="inline-flex items-center gap-2 rounded-xl border border-border/60 bg-card/60 px-8 py-3.5 text-base font-medium text-foreground hover:bg-accent/40 transition-colors glass"
          >
            See How It Works
          </a>
        </div>
        <p className="mt-6 text-xs text-muted-foreground">
          No credit card required &middot; Set up in under 5 minutes
        </p>
      </div>
    </section>
  );
}

function ProblemStatement() {
  return (
    <section className="py-16 sm:py-20">
      <div className="mx-auto max-w-5xl px-6">
        <div className="glass-card rounded-2xl p-8 sm:p-12">
          <div className="grid md:grid-cols-3 gap-8 text-center">
            <div>
              <div className="text-4xl font-bold text-destructive mb-2">3+</div>
              <div className="text-sm text-muted-foreground">
                Hours per week spent manually entering guest card data
              </div>
            </div>
            <div>
              <div className="text-4xl font-bold text-destructive mb-2">40%</div>
              <div className="text-sm text-muted-foreground">
                Of visitor follow-ups delayed by slow data processing
              </div>
            </div>
            <div>
              <div className="text-4xl font-bold text-destructive mb-2">1 in 5</div>
              <div className="text-sm text-muted-foreground">
                Guest records contain transcription errors from handwriting
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function HowItWorks() {
  const steps = [
    {
      number: "01",
      icon: ScanLine,
      title: "Scan or Upload",
      description:
        "Drop a stack of cards into your office scanner and send them via email or FTP. Or upload photos directly from your phone.",
    },
    {
      number: "02",
      icon: Zap,
      title: "AI Reads Every Field",
      description:
        "Our vision AI extracts names, phone numbers, emails, addresses, prayer requests, decisions &mdash; even messy handwriting.",
    },
    {
      number: "03",
      icon: Workflow,
      title: "Review & Integrate",
      description:
        "Your team reviews the results in a clean dashboard, then syncs directly to Planning Center, Google Sheets, or your CRM with one click.",
    },
  ];

  return (
    <section id="how-it-works" className="py-16 sm:py-24">
      <div className="mx-auto max-w-5xl px-6">
        <div className="text-center mb-16">
          <h2 className="text-3xl sm:text-4xl font-bold tracking-tight mb-4">
            From paper to people in three steps
          </h2>
          <p className="text-muted-foreground text-lg max-w-2xl mx-auto">
            No more squinting at handwriting on Monday morning. Echo handles the
            tedious work so your team can focus on follow-up.
          </p>
        </div>
        <div className="grid md:grid-cols-3 gap-6">
          {steps.map((step) => (
            <div
              key={step.number}
              className="glass-card rounded-2xl p-8 text-center group hover:scale-[1.02] transition-transform"
            >
              <div className="text-xs font-bold text-muted-foreground/50 tracking-widest mb-4">
                STEP {step.number}
              </div>
              <div className="mx-auto mb-5 h-14 w-14 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
                <step.icon className="h-7 w-7 text-primary" />
              </div>
              <h3 className="text-lg font-semibold mb-3">{step.title}</h3>
              <p
                className="text-sm text-muted-foreground leading-relaxed"
                dangerouslySetInnerHTML={{ __html: step.description }}
              />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const features = [
  {
    icon: ScanLine,
    title: "AI-Powered OCR",
    href: "/features/ai-ocr",
    description:
      "Advanced vision AI reads handwriting, checkboxes, and printed text. Extracts 20+ fields per card including names, contact info, prayer requests, and spiritual decisions.",
  },
  {
    icon: Mail,
    title: "Email & FTP Scanning",
    href: "/features/scanner-integration",
    description:
      "Configure your office scanner to email or FTP batches directly. Echo automatically picks them up and starts processing &mdash; no manual upload needed.",
  },
  {
    icon: Upload,
    title: "Drag & Drop Upload",
    href: "/features/scanner-integration",
    description:
      "Upload photos or PDFs from your phone, tablet, or computer. Supports multi-page duplex-scanned PDFs with automatic front/back pairing.",
  },
  {
    icon: CalendarDays,
    title: "Collection Days & Events",
    href: "/features/collection-days",
    description:
      "Define recurring services and events. Echo auto-assigns scanned cards to the most recent Sunday service or event, keeping everything organized.",
  },
  {
    icon: Users,
    title: "Team Collaboration",
    href: "/features/team-collaboration",
    description:
      "Invite your pastoral care team with role-based access. Assign cards for follow-up, track review status, and keep everyone on the same page.",
  },
  {
    icon: Building2,
    title: "Multi-Site Ready",
    href: "/features/multi-site",
    description:
      "Manage multiple campuses under one organization. Each location gets its own collection days, scanner setup, and team assignments.",
  },
  {
    icon: BarChart3,
    title: "Dashboard & Analytics",
    href: "/features/analytics",
    description:
      "See first-time guests, salvations, prayer requests, and follow-up status at a glance. Filter, sort, and export your data anytime.",
  },
  {
    icon: Shield,
    title: "Secure by Default",
    href: "/features/security",
    description:
      "Role-based permissions, encrypted storage, email verification, and invitation-only team access protect your congregation&rsquo;s personal data.",
  },
  {
    icon: Clock,
    title: "Instant Follow-Up",
    href: "/features/ai-ocr",
    description:
      "Stop waiting until Tuesday to start reaching out. Cards scanned Sunday afternoon are in your system by Sunday evening.",
  },
];

function Features() {
  return (
    <section id="features" className="py-16 sm:py-24 relative">
      <div className="absolute inset-0 gradient-mesh pointer-events-none opacity-50" />
      <div className="relative mx-auto max-w-6xl px-6">
        <div className="text-center mb-16">
          <h2 className="text-3xl sm:text-4xl font-bold tracking-tight mb-4">
            Everything your guest services team needs
          </h2>
          <p className="text-muted-foreground text-lg max-w-2xl mx-auto">
            Purpose-built for the way churches actually work &mdash; from the
            welcome center to the pastor&rsquo;s desk.
          </p>
        </div>
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {features.map((feature) => (
            <Link
              key={feature.title}
              href={feature.href}
              className="glass-card rounded-xl p-6 hover:scale-[1.01] transition-transform group"
            >
              <div className="mb-4 h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
                <feature.icon className="h-5 w-5 text-primary" />
              </div>
              <div className="flex items-center gap-2 mb-2">
                <h3 className="font-semibold">{feature.title}</h3>
                <ArrowRight className="h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 group-hover:translate-x-0.5 transition-all" />
              </div>
              <p
                className="text-sm text-muted-foreground leading-relaxed"
                dangerouslySetInnerHTML={{ __html: feature.description }}
              />
            </Link>
          ))}
        </div>
        <div className="text-center mt-10">
          <Link
            href="/features"
            className="inline-flex items-center gap-2 text-sm font-semibold text-primary hover:underline"
          >
            Explore all features
            <ArrowRight className="h-4 w-4" />
          </Link>
        </div>
      </div>
    </section>
  );
}

const integrations = [
  {
    name: "Planning Center",
    description: "Auto-match or create people, sync contact info, and add guests to lists.",
    tag: "Most Popular",
    icon: Heart,
  },
  {
    name: "Google Sheets",
    description: "Append card data to a shared spreadsheet for custom reporting workflows.",
    icon: FileText,
  },
  {
    name: "Monday.com",
    description: "Create board items with mapped columns for project-style follow-up tracking.",
    icon: Globe,
  },
  {
    name: "Airtable",
    description: "Push records with field mapping into any Airtable base for flexible data management.",
    icon: BarChart3,
  },
  {
    name: "Webhooks",
    description: "Send signed payloads to any URL on card events. Connect to Zapier, Make, or your custom API.",
    icon: Webhook,
  },
  {
    name: "CSV Export",
    description: "Download your data anytime as CSV for import into any system.",
    icon: FileText,
  },
];

function Integrations() {
  return (
    <section id="integrations" className="py-16 sm:py-24">
      <div className="mx-auto max-w-5xl px-6">
        <div className="text-center mb-16">
          <h2 className="text-3xl sm:text-4xl font-bold tracking-tight mb-4">
            Connects to your existing tools
          </h2>
          <p className="text-muted-foreground text-lg max-w-2xl mx-auto">
            Echo doesn&rsquo;t replace your church management system &mdash; it feeds
            it. Send scanned data exactly where your team already works.
          </p>
        </div>
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {integrations.map((integration) => (
            <div
              key={integration.name}
              className="glass-card rounded-xl p-6 relative"
            >
              {integration.tag && (
                <span className="absolute top-4 right-4 text-[10px] font-bold uppercase tracking-wider bg-primary/10 text-primary px-2 py-0.5 rounded-full">
                  {integration.tag}
                </span>
              )}
              <div className="mb-4 h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                <integration.icon className="h-5 w-5 text-primary" />
              </div>
              <h3 className="font-semibold mb-2">{integration.name}</h3>
              <p className="text-sm text-muted-foreground leading-relaxed">
                {integration.description}
              </p>
            </div>
          ))}
        </div>
        <div className="text-center mt-10">
          <Link
            href="/features/integrations"
            className="inline-flex items-center gap-2 text-sm font-semibold text-primary hover:underline"
          >
            See all integrations in detail
            <ArrowRight className="h-4 w-4" />
          </Link>
        </div>
      </div>
    </section>
  );
}

const tiers = [
  {
    name: "Free",
    price: "$0",
    period: "forever",
    description: "Perfect for trying Echo with your team.",
    cards: "50 cards/month",
    features: [
      "AI-powered OCR extraction",
      "Web upload (PDF, JPEG, PNG)",
      "2 team members",
      "1 location",
      "CSV export",
      "Community support",
    ],
    cta: "Get Started Free",
    ctaHref: "/signup",
    highlighted: false,
  },
  {
    name: "Starter",
    price: "$29",
    period: "/month",
    annualPrice: "$24",
    description: "For churches ready to automate their guest workflow.",
    cards: "250 cards/month",
    features: [
      "Everything in Free, plus:",
      "Email & FTP scanner integration",
      "5 team members",
      "Collection day management",
      "Google Sheets integration",
      "Webhook support",
      "Email support",
    ],
    cta: "Start 14-Day Trial",
    ctaHref: "/signup?plan=starter",
    highlighted: false,
  },
  {
    name: "Growth",
    price: "$79",
    period: "/month",
    annualPrice: "$66",
    description: "Full integration power for growing congregations.",
    cards: "1,000 cards/month",
    features: [
      "Everything in Starter, plus:",
      "Planning Center sync",
      "Monday.com & Airtable",
      "15 team members",
      "3 locations",
      "Auto-assign to events",
      "API access",
      "Priority support",
    ],
    cta: "Start 14-Day Trial",
    ctaHref: "/signup?plan=growth",
    highlighted: true,
  },
  {
    name: "Enterprise",
    price: "Custom",
    period: "",
    description: "For multi-site churches and denominations.",
    cards: "Unlimited cards",
    features: [
      "Everything in Growth, plus:",
      "Unlimited team members",
      "Unlimited locations",
      "SSO / SAML authentication",
      "Custom integrations",
      "Dedicated account manager",
      "99.9% uptime SLA",
    ],
    cta: "Contact Sales",
    ctaHref: "mailto:support@stillwell.cloud?subject=Sales%20inquiry",
    highlighted: false,
  },
];

function Pricing() {
  const [annual, setAnnual] = useState(false);

  return (
    <section id="pricing" className="py-16 sm:py-24 relative">
      <div className="absolute inset-0 gradient-mesh pointer-events-none opacity-50" />
      <div className="relative mx-auto max-w-6xl px-6">
        <div className="text-center mb-12">
          <h2 className="text-3xl sm:text-4xl font-bold tracking-tight mb-4">
            Simple, transparent pricing
          </h2>
          <p className="text-muted-foreground text-lg max-w-2xl mx-auto mb-8">
            Start free. Upgrade when you&rsquo;re ready. Every plan saves your team
            hours of manual data entry every single week.
          </p>
          <div className="inline-flex items-center gap-3 rounded-full border border-border/60 bg-card/60 p-1 glass">
            <button
              onClick={() => setAnnual(false)}
              className={`rounded-full px-5 py-2 text-sm font-medium transition-all ${
                !annual
                  ? "bg-primary text-primary-foreground shadow-sm"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              Monthly
            </button>
            <button
              onClick={() => setAnnual(true)}
              className={`rounded-full px-5 py-2 text-sm font-medium transition-all ${
                annual
                  ? "bg-primary text-primary-foreground shadow-sm"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              Annual
              <span className="ml-1.5 text-xs opacity-80">Save 17%</span>
            </button>
          </div>
        </div>

        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
          {tiers.map((tier) => (
            <div
              key={tier.name}
              className={`rounded-2xl p-6 flex flex-col ${
                tier.highlighted
                  ? "glass-card ring-2 ring-primary/30 shadow-xl scale-[1.02]"
                  : "glass-card"
              }`}
            >
              {tier.highlighted && (
                <div className="text-[10px] font-bold uppercase tracking-wider text-primary mb-4">
                  Most Popular
                </div>
              )}
              <h3 className="text-lg font-semibold">{tier.name}</h3>
              <div className="mt-3 mb-1">
                <span className="text-3xl font-bold">
                  {annual && tier.annualPrice ? tier.annualPrice : tier.price}
                </span>
                {tier.period && (
                  <span className="text-sm text-muted-foreground ml-1">
                    {tier.period}
                  </span>
                )}
              </div>
              {annual && tier.annualPrice && (
                <div className="text-xs text-muted-foreground mb-3">
                  Billed annually ({tier.annualPrice === "$24" ? "$288" : "$792"}/year)
                </div>
              )}
              <p className="text-sm text-muted-foreground mb-4">
                {tier.description}
              </p>
              <div className="text-sm font-semibold text-foreground mb-4 pb-4 border-b border-border/40">
                {tier.cards}
              </div>
              <ul className="space-y-3 mb-8 flex-1">
                {tier.features.map((feature) => (
                  <li key={feature} className="flex items-start gap-2.5 text-sm">
                    <Check className="h-4 w-4 text-primary mt-0.5 shrink-0" />
                    <span className="text-muted-foreground">{feature}</span>
                  </li>
                ))}
              </ul>
              <Link
                href={tier.ctaHref}
                className={`block text-center rounded-lg py-2.5 text-sm font-semibold transition-all ${
                  tier.highlighted
                    ? "bg-primary text-primary-foreground shadow-sm hover:opacity-90"
                    : "border border-border/60 bg-card/60 text-foreground hover:bg-accent/40"
                }`}
              >
                {tier.cta}
              </Link>
            </div>
          ))}
        </div>
        <p className="text-center text-xs text-muted-foreground mt-8">
          All paid plans include a 14-day free trial. No credit card required to
          start. Need more cards? Overage billed at $0.08/card.
        </p>
      </div>
    </section>
  );
}

const testimonials = [
  {
    quote:
      "We used to spend all of Monday morning entering visitor cards. Now it's done before we leave on Sunday. Echo literally gave us a day back.",
    name: "Sarah Mitchell",
    role: "Guest Services Director",
    church: "Grace Community Church",
  },
  {
    quote:
      "The Planning Center integration alone was worth it. New guests show up in our system automatically &mdash; our follow-up team can start reaching out the same day.",
    name: "David Chen",
    role: "Executive Pastor",
    church: "Hillside Fellowship",
  },
  {
    quote:
      "We have three campuses and Echo keeps everything organized. Each location scans their own cards and it all flows into one dashboard.",
    name: "Maria Rodriguez",
    role: "Administrative Director",
    church: "New Life Church",
  },
];

function Testimonials() {
  return (
    <section className="py-16 sm:py-24">
      <div className="mx-auto max-w-5xl px-6">
        <div className="text-center mb-12">
          <h2 className="text-3xl sm:text-4xl font-bold tracking-tight mb-4">
            Trusted by churches like yours
          </h2>
        </div>
        <div className="grid md:grid-cols-3 gap-5">
          {testimonials.map((t) => (
            <div key={t.name} className="glass-card rounded-xl p-6">
              <p
                className="text-sm text-muted-foreground leading-relaxed mb-6 italic"
                dangerouslySetInnerHTML={{ __html: `&ldquo;${t.quote}&rdquo;` }}
              />
              <div>
                <div className="text-sm font-semibold">{t.name}</div>
                <div className="text-xs text-muted-foreground">
                  {t.role}, {t.church}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const faqs = [
  {
    q: "What types of cards can Echo scan?",
    a: "Echo works with any printed or handwritten response card, guest card, prayer request form, connection card, or decision card. If a human can read it, Echo can too. We support PDF (including multi-page duplex scans), JPEG, PNG, and WebP formats.",
  },
  {
    q: "How accurate is the AI OCR?",
    a: "Echo uses the same vision AI models that power leading enterprise document processing. For printed text, accuracy is near-perfect. For handwriting, accuracy typically ranges from 85-95% depending on legibility — which is why every card goes through a human review step before syncing.",
  },
  {
    q: "Do I need special scanning equipment?",
    a: "No. Any office scanner, multi-function printer, or even a smartphone camera works. If your scanner supports 'Scan to Email' or 'Scan to FTP' (most do), you can automate the entire process with zero manual uploading.",
  },
  {
    q: "How does the Planning Center integration work?",
    a: "Echo connects via OAuth to your Planning Center People account. When a card is processed, it matches the person by email or name. If they exist, it updates their record. If not, it creates a new person. You can also add them to specific lists automatically.",
  },
  {
    q: "Is our congregation's data secure?",
    a: "Yes. All data is encrypted in transit and at rest. We use role-based access controls, invitation-only team access, and email verification. Your data is stored on enterprise-grade infrastructure (Supabase + Vercel) with SOC 2 compliance.",
  },
  {
    q: "Can we self-host Echo?",
    a: "Enterprise plans include the option for on-premise deployment via Docker. This is ideal for denominations or large organizations with strict data residency requirements.",
  },
  {
    q: "What happens if we go over our card limit?",
    a: "We'll never cut you off mid-month. Overage is billed at $0.08 per card. If you're consistently exceeding your plan, we'll suggest upgrading to save money.",
  },
  {
    q: "Is there a contract or commitment?",
    a: "No. Monthly plans can be cancelled anytime. Annual plans are paid upfront for the discount but you can switch to monthly at renewal. The free tier is free forever.",
  },
];

function FAQ() {
  const [openIndex, setOpenIndex] = useState<number | null>(null);

  return (
    <section id="faq" className="py-16 sm:py-24">
      <div className="mx-auto max-w-3xl px-6">
        <div className="text-center mb-12">
          <h2 className="text-3xl sm:text-4xl font-bold tracking-tight mb-4">
            Frequently asked questions
          </h2>
        </div>
        <div className="space-y-3">
          {faqs.map((faq, i) => (
            <div key={i} className="glass-card rounded-xl overflow-hidden">
              <button
                onClick={() => setOpenIndex(openIndex === i ? null : i)}
                className="flex items-center justify-between w-full px-6 py-4 text-left"
              >
                <span className="text-sm font-semibold pr-4">{faq.q}</span>
                {openIndex === i ? (
                  <ChevronUp className="h-4 w-4 text-muted-foreground shrink-0" />
                ) : (
                  <ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" />
                )}
              </button>
              {openIndex === i && (
                <div className="px-6 pb-5">
                  <p className="text-sm text-muted-foreground leading-relaxed">
                    {faq.a}
                  </p>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function FinalCTA() {
  return (
    <section className="py-16 sm:py-24 relative">
      <div className="absolute inset-0 gradient-mesh pointer-events-none" />
      <div className="relative mx-auto max-w-3xl px-6 text-center">
        <div className="glass-card rounded-2xl p-10 sm:p-14">
          <h2 className="text-3xl sm:text-4xl font-bold tracking-tight mb-4">
            Ready to give your team Sunday evenings back?
          </h2>
          <p className="text-muted-foreground text-lg mb-8 max-w-xl mx-auto">
            Join churches who&rsquo;ve already processed thousands of guest cards
            with Echo. Start free &mdash; no credit card, no commitment.
          </p>
          <Link
            href="/signup"
            className="inline-flex items-center gap-2 rounded-xl bg-primary px-8 py-3.5 text-base font-semibold text-primary-foreground shadow-lg hover:opacity-90 transition-opacity"
          >
            Get Started Free
            <ArrowRight className="h-4 w-4" />
          </Link>
        </div>
      </div>
    </section>
  );
}

export default function WelcomePage() {
  return (
    <div className="min-h-screen bg-background">
      <MarketingNav />
      <Hero />
      <ProblemStatement />
      <HowItWorks />
      <Features />
      <Integrations />
      <Testimonials />
      <Pricing />
      <FAQ />
      <FinalCTA />
      <MarketingFooter />
    </div>
  );
}
