import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { ShoppingCart, CheckCircle, Menu } from "lucide-react";
import { products, formatPrice } from "@shared/products";
import {
  platformComparisonRows,
  platformFaqs,
  platformProductVideo,
} from "@shared/platformContent";
import { useLocation } from "wouter";

export default function Shop() {
  const [, navigate] = useLocation();
  const [showMobileMenu, setShowMobileMenu] = useState(false);

  const handleAddToCart = (productId: string) => {
    // Store cart in both localStorage (persistent) and sessionStorage (immediate)
    let cartItems = [];
    
    // Try localStorage first (persistent across sessions)
    const storedCart = localStorage.getItem("cart");
    if (storedCart) {
      try {
        cartItems = JSON.parse(storedCart);
      } catch (e) {
        console.error('Failed to parse localStorage cart:', e);
      }
    }
    
    const existing = cartItems.find((item: any) => item.productId === productId);
    
    if (existing) {
      existing.quantity += 1;
    } else {
      cartItems.push({ productId, quantity: 1 });
    }
    
    // Save to both storages for redundancy
    localStorage.setItem("cart", JSON.stringify(cartItems));
    sessionStorage.setItem("pendingCartItems", JSON.stringify(cartItems));
    
    // Navigate to checkout
    navigate("/checkout");
  };

  return (
    <div className="min-h-screen flex flex-col bg-background">
      {/* Header */}
      <header className="sticky top-0 z-50 bg-background border-b border-border">
        <div className="container flex items-center justify-between py-4">
          <div className="flex items-center gap-8">
            <a href="/" className="flex items-center gap-2 hover:opacity-80 transition-opacity">
              <img
                src="https://d2xsxph8kpxj0f.cloudfront.net/310519663183885862/MATkf3xTWf8GjeFQgJipRW/1775460623330_863f878b.jpg"
                alt="Modemanagement Logo"
                className="h-12 w-auto"
              />
            </a>
          </div>
          <nav className="hidden md:flex items-center gap-6">
            <a href="/#kpi-dashboard" className="text-foreground hover:text-primary font-semibold transition-colors">KPI Calculator</a>
            <a href="/#wat-zeggen-mijn-klanten" className="text-foreground hover:text-primary font-semibold transition-colors">Testimonials</a>
            <a href="/#inkoopplanning" className="text-foreground hover:text-primary font-semibold transition-colors">Inkoopplanning</a>
            <a href="/#korting-calculator" className="text-foreground hover:text-primary font-semibold transition-colors">Korting Calculator</a>
            <a href="/#gratis-cursus" className="text-foreground hover:text-primary font-semibold transition-colors">Gratis Cursus</a>
            <a href="/shop" className="text-primary font-semibold">Webshop</a>
            <a href="/#gratis-kpi-analyse" className="text-foreground hover:text-primary font-semibold transition-colors">Gratis Analyse</a>
          </nav>
          <div className="flex items-center gap-4">
            <button
              onClick={() => setShowMobileMenu(!showMobileMenu)}
              className="md:hidden flex items-center justify-center w-10 h-10 rounded-lg hover:bg-secondary transition-colors"
              aria-label="Menu"
            >
              <Menu className="w-6 h-6" />
            </button>
            <a href="https://koalendar.com/e/cor-van-laar" target="_blank" rel="noopener noreferrer" className="hidden md:inline-block">
              <Button className="bg-primary text-primary-foreground hover:bg-primary/90">
                📞 Gratis belafspraak
              </Button>
            </a>
          </div>
        </div>
        {showMobileMenu && (
          <div className="md:hidden border-t border-border bg-background/95 backdrop-blur">
            <div className="container py-4 space-y-3">
              <a href="/#kpi-dashboard" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                KPI Calculator
              </a>
              <a href="/#wat-zeggen-mijn-klanten" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Testimonials
              </a>
              <a href="/#inkoopplanning" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Inkoopplanning
              </a>
              <a href="/#korting-calculator" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Korting Calculator
              </a>
              <a href="/#gratis-cursus" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Gratis Cursus
              </a>
              <a href="/shop" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Webshop
              </a>
              <a href="/#gratis-kpi-analyse" onClick={() => setShowMobileMenu(false)} className="block px-4 py-2 text-foreground hover:text-primary font-semibold transition-colors rounded-lg hover:bg-secondary">
                Gratis Analyse
              </a>
              <Button className="luxury-button w-full" onClick={() => { window.open('https://koalendar.com/e/cor-van-laar', '_blank'); setShowMobileMenu(false); }}>
                📞 Gratis belafspraak
              </Button>
            </div>
          </div>
        )}
      </header>

      <div className="flex flex-1 flex-col lg:flex-row">
        {/* Products Grid */}
        <div className="flex-1 container py-12 lg:border-r lg:border-border">
          <div className="space-y-8">
            <div className="text-center space-y-4">
              <h1 className="text-3xl sm:text-4xl lg:text-5xl leading-tight font-bold font-serif text-foreground">
                Modemanagement Webshop
              </h1>
              <p className="text-xl text-muted-foreground">
                Kies het perfecte pakket voor jouw bedrijf
              </p>
            </div>

            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
              {products.map((product) => (
                <Card
                  key={product.id}
                  className={`flex flex-col p-6 transition-all hover:shadow-lg ${
                    product.highlighted ? "border-primary border-2" : ""
                  }`}
                >
                  {product.highlighted && (
                    <div className={`mb-4 inline-block px-3 py-1 rounded-full text-sm font-semibold ${
                      product.highlightedTone === "amber"
                        ? "bg-amber-300 text-amber-950 border border-amber-400"
                        : "bg-primary text-primary-foreground"
                    }`}>
                      {product.highlightedLabel ?? "Populair"}
                    </div>
                  )}

                  <h3 className={`${product.titleLines ? "text-lg lg:text-xl" : "text-xl lg:text-2xl"} leading-tight font-bold font-serif text-foreground mb-2`}>
                    {product.titleLines
                      ? product.titleLines.map(line => <span key={line} className="block">{line}</span>)
                      : product.name}
                  </h3>

                  {product.subtitle && (
                    <p className="text-sm font-semibold text-primary mb-4">
                      {product.subtitle}
                    </p>
                  )}

                  <div className="mb-4">
                    <div className="flex items-baseline gap-2">
                      <span className="text-4xl font-bold text-primary">
                        €{(product.price / 100).toFixed(2)}
                      </span>
                      {product.priceNote && (
                        <span className="text-sm text-muted-foreground">{product.priceNote}</span>
                      )}
                      {product.duration && !product.priceNote && (
                        <span className="text-sm text-muted-foreground">{product.duration}</span>
                      )}
                    </div>
                  </div>

                  <p className="text-foreground/70 mb-6">{product.description}</p>

                  <div className="space-y-3 mb-6 flex-1">
                    {product.features.map((feature, idx) => (
                      <div key={idx} className="flex gap-2">
                        <CheckCircle className="w-5 h-5 text-primary flex-shrink-0 mt-0.5" />
                        <span className="text-sm text-foreground">{feature}</span>
                      </div>
                    ))}
                  </div>

                  <div className="flex gap-2">
                    {product.externalLink ? (
                      <a
                        href={product.externalLink}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex-1"
                      >
                        <Button className="w-full bg-primary text-primary-foreground hover:bg-primary/90">
                          {product.externalButtonLabel ?? "Klik hier"}
                        </Button>
                      </a>
                    ) : (
                      <Button
                        onClick={() => handleAddToCart(product.id)}
                        className="flex-1 bg-primary text-primary-foreground hover:bg-primary/90"
                      >
                        <ShoppingCart className="w-4 h-4 mr-2" />
                        In winkelwagen
                      </Button>
                    )}
                  </div>
                </Card>
              ))}
            </div>

            <section className="mt-16 grid gap-8 lg:grid-cols-2 lg:items-center" aria-labelledby="platform-video-heading">
              <div className="rounded-2xl bg-secondary/50 p-6 sm:p-8">
                <p className="mb-3 text-sm font-bold tracking-[0.16em] text-primary">PRODUCTVIDEO</p>
                <h2 id="platform-video-heading" className="font-serif text-3xl font-bold leading-tight text-foreground sm:text-4xl">
                  {platformProductVideo.title}
                </h2>
                <p className="mt-4 max-w-xl text-base leading-relaxed text-foreground/70">
                  {platformProductVideo.description}
                </p>
                <a
                  href="https://modemanagement.zite.so/"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="mt-6 inline-block"
                >
                  <Button className="bg-primary text-primary-foreground hover:bg-primary/90">
                    Bekijk het platform
                  </Button>
                </a>
              </div>
              <div className="overflow-hidden rounded-2xl border border-primary/20 bg-black shadow-lg">
                <video
                  className="aspect-video h-full w-full object-cover"
                  autoPlay
                  muted
                  loop
                  playsInline
                  controls
                  preload="metadata"
                  aria-label="Korte productvideo over het Inkoopplan en Maandanalyse Platform"
                >
                  <source src={platformProductVideo.src} type="video/mp4" />
                  Je browser ondersteunt deze video niet.
                </video>
              </div>
            </section>

            <section className="mt-16" aria-labelledby="platform-comparison-heading">
              <div className="max-w-2xl">
                <p className="text-sm font-bold tracking-[0.16em] text-primary">WELK PAKKET PAST BIJ JOU?</p>
                <h2 id="platform-comparison-heading" className="mt-3 font-serif text-3xl font-bold text-foreground sm:text-4xl">
                  Vergelijk je mogelijkheden
                </h2>
                <p className="mt-4 text-foreground/70">
                  Kies het pakket dat past bij de manier waarop je nu wilt werken: zelf aan de slag, maandelijks sturen of persoonlijk sparren.
                </p>
              </div>
              <div className="mt-8 overflow-x-auto rounded-2xl border border-border bg-card">
                <p className="px-4 pt-3 text-xs font-medium text-muted-foreground md:hidden">
                  Veeg horizontaal om alle pakketten te vergelijken.
                </p>
                <table className="min-w-[720px] w-full border-collapse text-left text-sm">
                  <thead className="bg-secondary/70 text-foreground">
                    <tr>
                      <th className="p-4 font-semibold">Onderdeel</th>
                      <th className="p-4 font-semibold">AI voor Modewinkels</th>
                      <th className="bg-amber-50 p-4 font-semibold text-amber-950">Inkoopplan/Maandanalyse</th>
                      <th className="p-4 font-semibold">Consult</th>
                    </tr>
                  </thead>
                  <tbody>
                    {platformComparisonRows.map((row) => (
                      <tr key={row.label} className="border-t border-border">
                        <th scope="row" className="p-4 font-semibold text-foreground">{row.label}</th>
                        <td className="p-4 text-foreground/70">{row.ai}</td>
                        <td className="bg-amber-50/60 p-4 font-medium text-foreground">{row.platform}</td>
                        <td className="p-4 text-foreground/70">{row.consult}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>

            <section className="mt-16" aria-labelledby="platform-faq-heading">
              <div className="max-w-2xl">
                <p className="text-sm font-bold tracking-[0.16em] text-primary">VEELGESTELDE VRAGEN</p>
                <h2 id="platform-faq-heading" className="mt-3 font-serif text-3xl font-bold text-foreground sm:text-4xl">
                  Over het Inkoopplan/Maandanalyse Platform
                </h2>
              </div>
              <div className="mt-8 grid gap-3">
                {platformFaqs.map((faq) => (
                  <details key={faq.question} className="rounded-xl border border-border bg-card px-5 py-4 group">
                    <summary className="cursor-pointer list-none pr-8 font-semibold text-foreground marker:hidden">
                      {faq.question}
                    </summary>
                    <p className="mt-3 leading-relaxed text-foreground/70">{faq.answer}</p>
                  </details>
                ))}
              </div>
            </section>
          </div>
        </div>
      </div>
    </div>
  );
}
