"use client";

import React, { useState } from "react";
import { Bell, Smartphone } from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { apiFetch } from "@/lib/csrf/client";

export function AppSection() {
  const { language } = useI18n();
  const isDe = language === "de";
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!email.trim()) return;

    setIsLoading(true);
    try {
      await apiFetch("/api/waitlist", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: email.trim(),
          name: name.trim() || undefined,
          source: "landing_app_section",
        }),
      });
      setSubmitted(true);
    } catch {
      // Still show success — the endpoint is designed to be resilient
      setSubmitted(true);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <section id="app" className="w-full bg-[#F8FAFC] font-sans py-20 sm:py-24 relative">
      <div className="max-w-[1440px] mx-auto px-4 sm:px-8 border-x border-[#E2E8F0] relative">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-24 items-start">
          <div className="lg:col-span-7 lg:pt-4">
            <div className="flex items-center gap-2 mb-4">
              <span className="w-2.5 h-2.5 bg-emerald-500" />
              <span className="font-mono text-xs uppercase tracking-caps font-semibold text-[#475569]">
                {isDe ? "DIE RECEIPT SCANNER APP · IN KÜRZE" : "THE RECEIPT SCANNER APP · COMING SOON"}
              </span>
            </div>
            <h2 className="font-display text-3xl sm:text-4xl lg:text-5xl font-bold tracking-tightest text-black max-w-2xl">
              {isDe ? "Mit dem Smartphone scannen. In Excel finalisieren." : "Scan on your phone. Finish in Excel."}
            </h2>
            <p className="mt-5 text-base sm:text-lg text-[#444749] leading-relaxed max-w-2xl">
              {isDe
                ? "Die mobile App ist der schnellste Weg, Belege direkt unterwegs zu erfassen. Nutzen Sie denselben Account auf Web und Mobile, behalten Sie Ihren Belegverlauf synchron und exportieren Sie von jedem Gerät."
                : "The mobile app is the fastest way to capture receipts wherever work happens. Use the same account on web and mobile, keep your receipt history connected, and export from whichever screen is in front of you."}
            </p>

            <div className="mt-8 flex flex-wrap gap-x-8 gap-y-3 border-t border-[#E2E8F0] pt-5 font-mono text-[11px] uppercase tracking-caps text-[#475569]">
              <span className="flex items-center gap-2"><Smartphone className="w-4 h-4 text-black" /> {isDe ? "Unterwegs erfassen" : "Capture anywhere"}</span>
              <span>{isDe ? "Ein Account für Web + Mobile" : "Same account on web + mobile"}</span>
              <span>{isDe ? "Flexibler Export" : "Export from either"}</span>
            </div>
          </div>

          <div className="lg:col-span-5 bg-black text-white border-2 border-black p-6 sm:p-8">
            <div className="flex items-center justify-between border-b border-white/20 pb-4 mb-6">
              <div className="flex items-center gap-2">
                <Bell className="w-4 h-4" />
                <span className="font-mono text-xs uppercase tracking-caps font-semibold">{isDe ? "App-Warteliste" : "App waitlist"}</span>
              </div>
              <span className="font-mono text-[10px] uppercase tracking-wider text-emerald-300">iOS · Android</span>
            </div>
            <h3 className="font-display text-2xl sm:text-3xl font-bold tracking-tight">
              {isDe ? "Seien Sie als Erste dabei." : "Be first in line."}
            </h3>
            <p className="mt-3 text-sm text-white/70 leading-relaxed">
              {isDe
                ? "Melden Sie sich für Vorabzugang und App-Updates an. Ihr bestehender Web-Account funktioniert auch in der App."
                : "Join the launch list for early access and app updates. Your web account will work in the app, too."}
            </p>

            {submitted ? (
              <div className="mt-6 border border-emerald-400/60 bg-emerald-400/10 p-4 text-sm text-emerald-200">
                {isDe ? "Vielen Dank — Ihre Wartelisten-Anmeldung wurde erfasst." : "Thanks — your waitlist request is captured for this device."}
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="mt-6 space-y-3">
                <label htmlFor="app-waitlist-name" className="sr-only">{isDe ? "Name" : "Name"}</label>
                <input
                  id="app-waitlist-name"
                  type="text"
                  value={name}
                  onChange={(event) => setName(event.target.value)}
                  placeholder={isDe ? "Ihr Name (optional)" : "Your name (optional)"}
                  className="w-full min-h-12 bg-white text-black border border-white px-4 font-sans text-sm placeholder:text-[#64748B] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"
                />
                <label htmlFor="app-waitlist-email" className="sr-only">{isDe ? "E-Mail-Adresse" : "Email address"}</label>
                <input
                  id="app-waitlist-email"
                  type="email"
                  value={email}
                  onChange={(event) => setEmail(event.target.value)}
                  placeholder="you@company.com"
                  required
                  className="w-full min-h-12 bg-white text-black border border-white px-4 font-sans text-sm placeholder:text-[#64748B] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"
                />
                <button
                  type="submit"
                  disabled={isLoading}
                  className="w-full min-h-12 bg-emerald-400 text-black px-4 font-mono text-xs uppercase tracking-caps font-bold hover:bg-emerald-300 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white disabled:opacity-60 disabled:cursor-not-allowed"
                >
                  {isLoading
                    ? (isDe ? "Wird eingetragen…" : "Signing up…")
                    : (isDe ? "Zur Warteliste anmelden" : "Join the app waitlist")}
                </button>
              </form>
            )}
            <p className="mt-4 font-mono text-[10px] uppercase tracking-wider text-white/45">
              {isDe ? "Kein Spam · Nur Early Access" : "No spam · Early access only"}
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}
