"use client";

import Image from "next/image";
import Link from "next/link";
import { memo, useEffect, useState } from "react";
import { ContactForm, DonationForm, CrowdfundingDonationForm } from "@/components/Forms";
import { PageBand, SectionHeader, SiteShell, PageHero } from "@/components/SiteShell";
import { API, fallbackSettings, resolveImageUrl, type SiteSettings } from "@/lib/api";

export type Article = {
  id: number;
  title: string;
  slug: string;
  category: string;
  thumbnail_url?: string;
  excerpt?: string;
  content?: string;
  author?: string;
  published_at?: string;
};

export type Project = {
  id: number;
  title: string;
  description: string;
  status: string;
  location: string;
  target_beneficiaries: string;
  fund_utilized: number;
  cover_image_url?: string;
};

export type Event = {
  id: number;
  title: string;
  event_date: string;
  venue: string;
  category: string;
  description: string;
  short_description?: string;
  cover_image_url?: string;
  price: number;
  capacity: number;
  event_status: string;
  registration_deadline?: string;
  highlights?: string;
  registered_count?: number;
  created_at?: string;
};

type Banner = {
  id: number;
  image_url?: string | null;
};

export type Area = {
  id: number;
  area_name: string;
  members_count: number;
  beneficiaries_count: number;
  impact_summary: string;
};

export type Campaign = {
  id: number; title: string; slug?: string; category: string;
  short_description: string; raised_amount: number; goal_amount: number;
  cover_image_url?: string;
};

export type HomeData = {
  settings: SiteSettings;
  impact: { members: number; beneficiaries: number; events: number; areas: number };
  articles: Article[];
  projects: Project[];
  featuredEvent: Event | null;
  campaigns: Campaign[];
};

const imageFallback = "https://images.unsplash.com/photo-1488521787991-ed7bbaae773c?auto=format&fit=crop&w=1200&q=80";
const heroImage = "/banner.jpg";
const kidsImage = "https://images.unsplash.com/photo-1542810634-71277d95dcbb?auto=format&fit=crop&w=900&q=80";
const communityImg = "https://images.unsplash.com/photo-1609220136736-443140cffec6?auto=format&fit=crop&w=900&q=80";
const educationImg = "https://images.unsplash.com/photo-1503676260728-1c00da094a0b?auto=format&fit=crop&w=900&q=80";
const volunteerImg = "https://images.unsplash.com/photo-1559027615-cd4628902d4a?auto=format&fit=crop&w=900&q=80";
const healthcareImg = "https://images.unsplash.com/photo-1576091160399-112ba8d25d1d?auto=format&fit=crop&w=900&q=80";

function formatDate(dateStr: string) {
  if (!dateStr) return "";
  return new Date(dateStr).toLocaleDateString("en-IN", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
}

/* ════════════════════════════════════════════════════════════════
   HOME
   ════════════════════════════════════════════════════════════════ */

const HeroBanner = memo(function HeroBanner() {
  return (
    <section className="relative overflow-hidden bg-gradient-to-br from-emerald-950 via-emerald-900 to-teal-900">
      <div className="absolute inset-0 opacity-20 bg-[radial-gradient(circle_at_30%_20%,rgba(255,255,255,0.1)_0%,transparent_60%)]" />
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute -top-40 -right-40 w-80 h-80 rounded-full border border-white/10" />
        <div className="absolute -bottom-20 -left-20 w-60 h-60 rounded-full border border-white/5" />
      </div>
      <Image
        src={heroImage}
        alt="Shanti Kritnischay Seva Foundation - Banner"
        width={1600}
        height={600}
        sizes="100vw"
        className="w-full h-auto relative z-10"
        priority
        style={{ display: "block" }}
      />
    </section>
  );
});

const StatsGrid = memo(function StatsGrid({ stats }: { stats: { label: string; value: number; suffix: string }[] }) {
  return (
    <section className="border-y border-[var(--color-hairline-cool)] bg-[var(--color-canvas-soft)]">
      <div className="mx-auto max-w-[1280px] px-4 lg:px-6">
        <div className="grid divide-y divide-[var(--color-hairline-cool)] sm:grid-cols-2 sm:divide-y-0 lg:grid-cols-4 lg:divide-x">
          {stats.map((stat) => (
            <div key={stat.label} className="px-2 py-8 md:px-8">
              <p className="text-4xl leading-none tracking-[-0.02em] text-[var(--color-ink)] md:text-5xl" style={{ fontWeight: 500 }}>
                {Number(stat.value).toLocaleString("en-IN")}
                {stat.suffix}
              </p>
              <p className="mt-2 text-xs font-medium uppercase tracking-widest text-[var(--color-ink-mute)]">
                {stat.label}
              </p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
});

function HomeIndexRedesign({
  data,
  stats,
}: {
  data: HomeData;
  stats: { label: string; value: number; suffix: string }[];
}) {
  return (
    <>
      {/* Foundation overview */}
      <section className="overflow-hidden bg-white py-16 md:py-24">
        <div className="mx-auto max-w-[1280px] px-4 lg:px-6">
          <div className="grid gap-12 lg:grid-cols-2 lg:items-center">
            <div className="relative z-10 space-y-7">
              <span className="eyebrow">
                <span className="eyebrow-dot" />
                Foundation Overview
              </span>
              <h2
                className="max-w-lg text-4xl leading-[1.1] tracking-[-0.02em] text-[var(--color-ink)] md:text-5xl"
                style={{ fontWeight: 500 }}
              >
                A sharper, kinder way to serve local families.
              </h2>
              <p className="max-w-lg text-lg leading-7 text-[var(--color-ink-mute)]">
                We combine field teams, volunteer energy, and simple digital records so every program stays practical, transparent, and close to the people it serves.
              </p>
              <div className="grid grid-cols-2 gap-8 border-t border-[var(--color-hairline-cool)] pt-8">
                <div>
                  <h3 className="mb-2 text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Local First</h3>
                  <p className="text-sm leading-6 text-[var(--color-ink-mute)]">Programs are shaped around village-level needs and field feedback.</p>
                </div>
                <div>
                  <h3 className="mb-2 text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Transparent</h3>
                  <p className="text-sm leading-6 text-[var(--color-ink-mute)]">Receipts, reports, and impact records managed digitally.</p>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-4 pt-10">
                <div className="relative h-64 w-full overflow-hidden rounded-[12px] border border-[var(--color-hairline)] group">
                  <Image src={kidsImage} alt="Children learning" fill className="object-cover transition-transform duration-700 group-hover:scale-105" sizes="(max-width: 768px) 100vw, 50vw" loading="lazy" />
                </div>
                <div className="relative h-48 w-full overflow-hidden rounded-[12px] border border-[var(--color-hairline)] group">
                  <Image src={communityImg} alt="Community program" fill className="object-cover transition-transform duration-700 group-hover:scale-105" sizes="(max-width: 768px) 100vw, 50vw" loading="lazy" />
                </div>
              </div>
              <div className="space-y-4 pb-10">
                <div className="relative h-48 w-full overflow-hidden rounded-[12px] border border-[var(--color-hairline)] group">
                  <Image src={volunteerImg} alt="Volunteer Network" fill className="object-cover transition-transform duration-700 group-hover:scale-105" sizes="(max-width: 768px) 100vw, 50vw" loading="lazy" />
                </div>
                <div className="relative flex h-64 w-full items-center justify-center rounded-[12px] bg-[var(--color-canvas-night)] p-6 text-center">
                  <div>
                    <h3 className="text-xl text-[var(--color-on-dark)]" style={{ fontWeight: 500 }}>Growing Impact</h3>
                    <p className="mt-2 text-xs text-[var(--color-on-dark)]/60">Together we are building a sustainable future.</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <StatsGrid stats={stats} />

      {/* Core programs */}
      <section className="bg-white">
        <div className="mx-auto max-w-[1280px] px-4 py-16 md:py-24 lg:px-6">
          <div className="mb-14 text-center">
            <span className="eyebrow">
              <span className="eyebrow-dot" />
              Core Programs
            </span>
            <h2
              className="mx-auto mt-5 max-w-2xl text-4xl leading-[1.1] tracking-[-0.02em] text-[var(--color-ink)] md:text-5xl"
              style={{ fontWeight: 500 }}
            >
              Focused work, clean execution.
            </h2>
          </div>

          <div className="grid gap-6 lg:grid-cols-3">
            {([
              ["Education", "Learning Support", "Books, tuition help, mentoring, and scholarship discovery.", educationImg, "/projects"],
              ["Healthcare", "Health & Nutrition", "Village camps, preventive screenings, nutrition awareness, and referrals.", healthcareImg, "/events"],
              ["Community", "Volunteer Network", "Members and volunteers coordinating surveys, events, and follow-up.", volunteerImg, "/membership/volunteer"],
            ] as const).map(([tag, title, text, img, href]) => (
              <Link key={title} href={href} className="group overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white transition-all duration-300 hover:-translate-y-1 hover:shadow-[var(--shadow-l2)]">
                <div className="relative h-56 overflow-hidden">
                  <Image src={img} alt={title} fill className="object-cover transition-transform duration-700 group-hover:scale-105" sizes="(max-width: 1024px) 100vw, 33vw" loading="lazy" />
                </div>
                <div className="p-8">
                  <span className="badge badge-soft">{tag}</span>
                  <h3 className="mt-4 text-2xl text-[var(--color-ink)] transition-colors group-hover:text-[var(--color-primary-deep)]" style={{ fontWeight: 500 }}>{title}</h3>
                  <p className="mt-3 text-sm leading-6 text-[var(--color-ink-mute)]">{text}</p>
                  <div className="mt-6 flex items-center gap-2 text-sm font-medium text-[var(--color-primary-deep)]">
                    Explore Program
                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                    </svg>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </div>
      </section>

      {data.campaigns.length > 0 && (
        <section className="border-t border-[var(--color-hairline-cool)] bg-[var(--color-canvas-soft)] py-16 md:py-24">
          <div className="mx-auto max-w-[1280px] px-4 lg:px-6">
            <div className="mb-14 text-center">
              <span className="eyebrow">
                <span className="eyebrow-dot" />
                Featured Causes
              </span>
              <h2
                className="mx-auto mt-5 max-w-2xl text-4xl leading-[1.1] tracking-[-0.02em] text-[var(--color-ink)] md:text-5xl"
                style={{ fontWeight: 500 }}
              >
                Campaigns designed for everyday giving.
              </h2>
            </div>

            <div className="grid gap-6 md:grid-cols-3">
              {data.campaigns.map((c) => {
                const pct = Math.min(100, Math.round((c.raised_amount || 0) / (c.goal_amount || 1) * 100));
                const coverSrc = resolveImageUrl(c.cover_image_url);
                return (
                  <article key={c.id} className="group flex flex-col overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white transition-all duration-300 hover:-translate-y-1 hover:shadow-[var(--shadow-l2)]">
                    <div className="relative h-52 w-full overflow-hidden">
                      {coverSrc ? (
                        <Image src={coverSrc} alt={c.title} fill className="object-cover transition-transform duration-700 group-hover:scale-105" sizes="(max-width: 768px) 100vw, 33vw" loading="lazy" />
                      ) : (
                        <div className="absolute inset-0 flex items-center justify-center bg-[var(--color-canvas-soft)]">
                          <span className="text-6xl text-[var(--color-ink-faint)]" style={{ fontWeight: 500 }}>{c.title?.charAt(0) ?? "C"}</span>
                        </div>
                      )}
                      <div className="absolute right-4 top-4">
                        <span className="badge badge-soft bg-white/90">{c.category}</span>
                      </div>
                    </div>

                    <div className="flex flex-1 flex-col p-7">
                      <h3 className="text-xl text-[var(--color-ink)] transition-colors group-hover:text-[var(--color-primary-deep)]" style={{ fontWeight: 500 }}>{c.title}</h3>
                      <p className="mt-3 flex-1 text-sm leading-6 text-[var(--color-ink-mute)] line-clamp-3">{c.short_description}</p>

                      <div className="mt-6">
                        <div className="mb-2 flex justify-between text-sm text-[var(--color-ink)]">
                          <span className="font-medium text-[var(--color-ink)]">
                            ₹{Number(c.raised_amount || 0).toLocaleString("en-IN")} <span className="text-xs font-normal text-[var(--color-ink-mute)]">raised</span>
                          </span>
                          <span className="text-[var(--color-ink-mute)]">₹{Number(c.goal_amount || 0).toLocaleString("en-IN")}</span>
                        </div>
                        <div className="progress-bar mb-6">
                          <div className="progress-fill" style={{ width: `${pct}%` }} />
                        </div>

                        <Link href={`/crowdfunding/detail?slug=${c.slug || c.id}`} className="btn w-full">
                          Donate Now
                        </Link>
                      </div>
                    </div>
                  </article>
                );
              })}
            </div>
          </div>
        </section>
      )}

      {/* Delivery model */}
      <section className="bg-white">
        <div className="mx-auto max-w-[1280px] px-4 py-16 md:py-24 lg:px-6">
          <div className="grid gap-14 lg:grid-cols-[0.85fr_1.15fr] lg:items-center">
            <SectionHeader
              eyebrow="Delivery Model"
              title="A simple workflow that keeps impact accountable."
              text="The foundation work moves from local discovery to measured reporting, keeping programs useful and easy to audit."
            />
            <div className="grid gap-5 sm:grid-cols-2">
              {([
                ["01", "Identify", "Field coordinators document real needs from families, schools, and villages."],
                ["02", "Plan", "Resources, budget, timeline, and volunteers are aligned before execution."],
                ["03", "Deliver", "Teams run camps, distribute materials, and record beneficiaries on-site."],
                ["04", "Report", "Receipts, updates, and outcomes are reviewed through admin records."],
              ] as const).map(([step, title, text]) => (
                <article key={title} className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-7 transition-all duration-300 hover:-translate-y-1 hover:shadow-[var(--shadow-l2)]">
                  <div className="flex h-11 w-11 items-center justify-center rounded-md bg-[var(--color-canvas-soft)] text-sm text-[var(--color-primary-deep)]" style={{ fontWeight: 500 }}>
                    {step}
                  </div>
                  <h3 className="mt-5 text-lg text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{title}</h3>
                  <p className="mt-3 text-sm leading-6 text-[var(--color-ink-mute)]">{text}</p>
                </article>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Why support us */}
      <section className="border-t border-[var(--color-hairline-cool)] bg-[var(--color-canvas-soft)] py-16 md:py-24">
        <div className="mx-auto max-w-[1280px] px-4 lg:px-6">
          <SectionHeader eyebrow="Why Support Us" title="Designed for trust, not noise." center />
          <div className="grid gap-6 md:grid-cols-3">
            {([
              ["Grassroots Impact", "Programs are built with local coordinators, so support reaches families with fewer layers."],
              ["Transparent Records", "Receipts, donor records, event updates, and project data are handled through the admin system."],
              ["Community First", "Members, volunteers, and beneficiaries shape the work through practical field feedback."],
            ] as const).map(([title, text], index) => (
              <article key={title} className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-8 transition-all duration-300 hover:-translate-y-1 hover:shadow-[var(--shadow-l2)]">
                <div className="flex h-11 w-11 items-center justify-center rounded-md bg-[var(--color-canvas-soft)] text-sm text-[var(--color-ink)]" style={{ fontWeight: 500 }}>
                  {String(index + 1).padStart(2, "0")}
                </div>
                <h3 className="mt-5 text-xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{title}</h3>
                <p className="mt-4 text-sm leading-7 text-[var(--color-ink-mute)]">{text}</p>
              </article>
            ))}
          </div>
        </div>
      </section>

      {data.featuredEvent && (
        <FeaturedEventSection event={data.featuredEvent} />
      )}

      {data.projects.length > 0 && (
        <section className="bg-white">
          <div className="mx-auto max-w-[1280px] px-4 py-16 md:py-24 lg:px-6">
            <div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
              <SectionHeader eyebrow="Projects" title="Where support is being used." text="Live project records from the foundation database." />
            </div>
            <ProjectGrid projects={data.projects.slice(0, 3)} />
            <div className="mt-10 flex justify-center">
              <Link href="/projects" className="btn-outline">
                View all projects
                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                </svg>
              </Link>
            </div>
          </div>
        </section>
      )}

      {data.articles.length > 0 && (
        <section className="border-t border-[var(--color-hairline-cool)] bg-[var(--color-canvas-soft)] py-16 md:py-24">
          <div className="mx-auto max-w-[1280px] px-4 lg:px-6">
            <div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
              <SectionHeader eyebrow="Latest Updates" title="News from the field." text="Announcements, success stories, and recent program coverage." />
            </div>
            <ArticleGrid articles={data.articles.slice(0, 4)} />
            <div className="mt-10 flex justify-center">
              <Link href="/news" className="btn-outline">
                All Articles
                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                </svg>
              </Link>
            </div>
          </div>
        </section>
      )}

      <CTABanner />
    </>
  );
}

const FeaturedEventSection = memo(function FeaturedEventSection({ event }: { event: Event }) {
  return (
    <section className="bg-white py-16 md:py-24">
      <div className="mx-auto max-w-[1280px] px-4 lg:px-6">
        <div className="relative overflow-hidden rounded-[12px] bg-[var(--color-canvas-night)] shadow-[var(--shadow-l2)]">
          <div className="grid lg:grid-cols-[1.1fr_0.9fr]">
            <div className="flex flex-col justify-center p-10 md:p-16">
              <span className="eyebrow eyebrow-green w-fit">
                <span className="inline-block h-1.5 w-1.5 rounded-full bg-[var(--color-on-primary)]" />
                Featured Event
              </span>
              <h2 className="mt-6 max-w-xl text-4xl leading-[1.1] tracking-[-0.02em] text-[var(--color-on-dark)] md:text-5xl" style={{ fontWeight: 500 }}>
                {event.title}
              </h2>
              <p className="mt-5 text-lg leading-7 text-[var(--color-on-dark)]/60">
                {event.description}
              </p>
              <div className="mt-8 flex flex-wrap items-center gap-8">
                <div>
                  <p className="text-[11px] font-medium uppercase tracking-widest text-[var(--color-on-dark)]/50">Date</p>
                  <p className="mt-1 font-medium text-[var(--color-on-dark)]">{formatDate(event.event_date)}</p>
                </div>
                {event.venue && (
                  <div>
                    <p className="text-[11px] font-medium uppercase tracking-widest text-[var(--color-on-dark)]/50">Venue</p>
                    <p className="mt-1 font-medium text-[var(--color-on-dark)]">{event.venue}</p>
                  </div>
                )}
              </div>
              <Link href="/events" className="btn mt-9 w-fit">
                Register Now
                <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                </svg>
              </Link>
            </div>
            <div className="relative min-h-[300px] w-full lg:min-h-full">
              <Image src={resolveImageUrl(event.cover_image_url, communityImg)} alt={event.title} fill className="object-cover" sizes="(max-width: 1024px) 100vw, 50vw" loading="lazy" />
              <div className="absolute inset-0 bg-gradient-to-t from-[var(--color-canvas-night)] via-transparent to-transparent lg:bg-gradient-to-r lg:from-[var(--color-canvas-night)] lg:via-transparent lg:to-transparent" />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
});

const CTABanner = memo(function CTABanner() {
  return (
    <section className="bg-white py-16 md:py-24">
      <div className="mx-auto max-w-[1280px] px-4 lg:px-6">
        <div className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-10 shadow-[var(--shadow-l1)] md:p-16">
          <div className="flex flex-col items-start justify-between gap-8 md:flex-row md:items-center">
            <div className="max-w-2xl">
              <h2 className="text-3xl leading-[1.1] tracking-[-0.02em] text-[var(--color-ink)] md:text-5xl" style={{ fontWeight: 500 }}>
                Join the movement.
              </h2>
              <p className="mt-4 text-lg leading-7 text-[var(--color-ink-mute)]">
                Every contribution supports education kits, health camps, nutrition drives, and community programs.
              </p>
            </div>
            <div className="flex flex-col gap-3 sm:flex-row">
              <Link href="/donate" className="btn">
                Make a Donation
              </Link>
              <Link href="/contact" className="btn-outline">
                Talk to Our Team
              </Link>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
});

export function HomeClient({ serverData }: { serverData: HomeData }) {
  const stats = [
    { label: "Members", value: serverData.impact.members, suffix: "+" },
    { label: "Beneficiaries", value: serverData.impact.beneficiaries, suffix: "+" },
    { label: "Events Held", value: serverData.impact.events, suffix: "" },
    { label: "Areas Served", value: serverData.impact.areas, suffix: "" },
  ];

  return (
    <SiteShell>
      <HeroBanner />
      <HomeIndexRedesign
        data={serverData}
        stats={stats}
      />
    </SiteShell>
  );
}

/* ════════════════════════════════════════════════════════════════
   PROJECTS
   ════════════════════════════════════════════════════════════════ */

type FilterStatus = "all" | "ongoing" | "completed" | "planning";

function getStatusLabel(status: string): FilterStatus {
  const s = status?.toLowerCase();
  if (s === "ongoing" || s === "active") return "ongoing";
  if (s === "completed") return "completed";
  if (s === "planning") return "planning";
  return "ongoing";
}

function StatusBadge({ status }: { status: string }) {
  const s = getStatusLabel(status);
  const styles: Record<FilterStatus, string> = {
    ongoing: "bg-[var(--color-primary)]/10 text-[var(--color-primary-deep)]",
    completed: "bg-[var(--color-canvas-soft)] text-[var(--color-ink-mute)]",
    planning: "bg-[var(--color-canvas-soft)] text-[var(--color-ink-mute)]",
    all: "",
  };
  const labels: Record<FilterStatus, string> = {
    ongoing: "\u25CF Ongoing",
    completed: "Completed",
    planning: "Planning",
    all: "",
  };
  return (
    <span className={`inline-block rounded-full px-3 py-1 text-[11px] font-medium ${styles[s]}`}>
      {labels[s]}
    </span>
  );
}

function ProgressBar({ value, status }: { value?: number; status: string }) {
  const pct = value ?? 0;
  return (
    <div className="flex-1 mx-3">
      <div className="mb-1 flex justify-between text-[10px] text-[var(--color-ink-mute)]">
        <span>{pct === 100 ? "Completed" : "Progress"}</span>
        <span>{pct}%</span>
      </div>
      <div className="progress-bar">
        <div className="progress-fill" style={{ width: `${pct}%` }} />
      </div>
    </div>
  );
}

function ProjectCard({ project, featured = false }: { project: Project; featured?: boolean }) {
  const status = getStatusLabel((project as any).status ?? "ongoing");
  const name = (project as any).name ?? project.title;
  const rawImageUrl = (project as any).imageUrl ?? project.cover_image_url;
  const resolvedImageUrl = resolveImageUrl(rawImageUrl, imageFallback);

  return (
    <article
      className={`group flex flex-col ${featured ? "md:flex-row md:col-span-2" : ""} overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white transition-all duration-300 hover:-translate-y-1 hover:shadow-[var(--shadow-l2)]`}
    >
      <div
        className={`relative flex items-center justify-center overflow-hidden bg-[var(--color-canvas-soft)] ${featured ? "h-52 md:h-auto md:w-5/12 md:shrink-0" : "h-40 w-full"}`}
      >
        {resolvedImageUrl ? (
          <Image
            src={resolvedImageUrl}
            alt={name}
            fill
            className="absolute inset-0 h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
            sizes={featured ? "(max-width: 768px) 100vw, 500px" : "(max-width: 768px) 100vw, 380px"}
            loading="lazy"
          />
        ) : (
          <div className="relative select-none text-6xl text-[var(--color-ink-faint)]" style={{ fontWeight: 500 }}>
            {name?.charAt(0) ?? "P"}
          </div>
        )}
      </div>
      <div className="flex flex-1 flex-col p-6">
        <div className="mb-3 flex items-center justify-between">
          <StatusBadge status={(project as any).status ?? "ongoing"} />
          {(project as any).year && (
            <span className="text-xs text-[var(--color-ink-mute)]">{(project as any).year}</span>
          )}
        </div>
        <h3 className="mb-2 text-xl leading-tight text-[var(--color-ink)]" style={{ fontWeight: 500 }}>
          {name}
        </h3>
        <p className="mb-4 flex-1 text-sm leading-6 text-[var(--color-ink-mute)] line-clamp-3">
          {(project as any).description ?? "No description available."}
        </p>
        <div className="flex items-center border-t border-[var(--color-hairline-cool)] pt-4">
          {(project as any).team?.length > 0 && (
            <div className="flex">
              {((project as any).team as string[]).slice(0, 3).map(
                (initials: string, i: number) => (
                  <div
                    key={i}
                    className="flex h-7 w-7 items-center justify-center rounded-full border-2 border-white bg-[var(--color-canvas-soft)] text-[10px] font-medium text-[var(--color-ink-mute)]"
                    style={{ marginLeft: i === 0 ? 0 : -8 }}
                  >
                    {initials}
                  </div>
                )
              )}
            </div>
          )}
          <ProgressBar value={(project as any).progress ?? 0} status={(project as any).status ?? "ongoing"} />
          <Link
            href={`/projects/${project.id}`}
            className="flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-[6px] border border-[var(--color-hairline-strong)] px-4 py-2 text-xs font-medium text-[var(--color-ink)] transition-colors hover:border-[var(--color-ink)]"
          >
            View
            <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" />
            </svg>
          </Link>
        </div>
      </div>
    </article>
  );
}

function FilterPill({ label, active, onClick }: { label: string; active: boolean; onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className={`rounded-full px-4 py-1.5 text-[13px] font-medium transition-colors ${
        active
          ? "bg-[var(--color-ink)] text-[var(--color-on-dark)]"
          : "border border-[var(--color-hairline-strong)] bg-white text-[var(--color-ink-mute)] hover:border-[var(--color-ink)] hover:text-[var(--color-ink)]"
      }`}
    >
      {label}
    </button>
  );
}

export function ProjectsLive({ serverData }: { serverData: Project[] }) {
  return (
    <SiteShell>
      
      <ProjectsContent initialData={serverData} />
    </SiteShell>
  );
}

function ProjectsContent({ initialData: data }: { initialData: Project[] }) {
  const [filter, setFilter] = useState<FilterStatus>("all");
  const filtered = filter === "all" ? data : data.filter(
    (p) => getStatusLabel((p as any).status ?? "ongoing") === filter
  );

  const filters: { key: FilterStatus; label: string }[] = [
    { key: "all", label: "All projects" },
    { key: "ongoing", label: "Ongoing" },
    { key: "completed", label: "Completed" },
    { key: "planning", label: "Planning" },
  ];

  return (
    <PageBand>
      <div className="mb-8 flex flex-wrap gap-2">
        {filters.map(({ key, label }) => (
          <FilterPill key={key} label={label} active={filter === key} onClick={() => setFilter(key)} />
        ))}
      </div>
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        {filtered.length === 0 ? (
          <div className="col-span-full flex flex-col items-center justify-center rounded-[12px] border-2 border-dashed border-[var(--color-hairline-strong)] py-20 text-center">
            <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-md bg-[var(--color-canvas-soft)]">
              <svg className="h-8 w-8 text-[var(--color-ink-faint)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5m8.25 3v6.75m0 0l-3-3m3 3l3-3M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" />
              </svg>
            </div>
            <p className="text-[var(--color-ink-mute)]">No projects found</p>
          </div>
        ) : (
          filtered.map((project) => <ProjectCard key={project.id} project={project} />)
        )}
      </div>
    </PageBand>
  );
}

/* ════════════════════════════════════════════════════════════════
   DONATE
   ════════════════════════════════════════════════════════════════ */

export function DonateLive() {
  return (
    <SiteShell>
      
      <DonateContent />
    </SiteShell>
  );
}

function DonateContent() {
  return (
    <PageBand>
      <div className="grid gap-10 lg:grid-cols-[1fr_420px]">
        <div className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-8">
          <h2 className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Donation Details</h2>
          <p className="mt-1 text-sm text-[var(--color-ink-mute)]">Complete the form below to proceed with your donation.</p>
          <div className="mt-6">
            <DonationForm />
          </div>
        </div>
        <div className="space-y-6">
          <div className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-8">
            <h3 className="text-lg text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Your Impact</h3>
            <ul className="mt-5 space-y-4 text-sm text-[var(--color-ink-mute)]">
              <li className="flex items-start gap-3">
                <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[var(--color-primary)]/15 text-xs text-[var(--color-primary-deep)]">✓</span>
                Education kits for underprivileged children
              </li>
              <li className="flex items-start gap-3">
                <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[var(--color-primary)]/15 text-xs text-[var(--color-primary-deep)]">✓</span>
                Free health check-up camps in remote villages
              </li>
              <li className="flex items-start gap-3">
                <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[var(--color-primary)]/15 text-xs text-[var(--color-primary-deep)]">✓</span>
                Nutrition drives for women and children
              </li>
              <li className="flex items-start gap-3">
                <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[var(--color-primary)]/15 text-xs text-[var(--color-primary-deep)]">✓</span>
                Digital literacy programs for rural youth
              </li>
            </ul>
          </div>
          <div className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-8">
            <h3 className="text-lg text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Tax Benefits</h3>
            <p className="mt-3 text-sm leading-6 text-[var(--color-ink-mute)]">
              Donations to our foundation are eligible for tax exemption under Section 80G of the Income Tax Act. You will receive a receipt for your donation.
            </p>
          </div>
        </div>
      </div>
    </PageBand>
  );
}

/* ════════════════════════════════════════════════════════════════
   NEWS / ARTICLES
   ════════════════════════════════════════════════════════════════ */

export function ArticleGrid({ articles }: { articles: Article[] }) {
  return (
    <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
      {articles.map((article) => {
        const imgSrc = resolveImageUrl(article.thumbnail_url);
        return (
          <Link key={article.id} href={`/news/${article.slug}`} className="group flex flex-col overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white transition-all duration-300 hover:-translate-y-1 hover:shadow-[var(--shadow-l2)]">
            <div className="relative flex h-40 w-full items-center justify-center overflow-hidden bg-[var(--color-canvas-soft)]">
              {imgSrc ? (
                <Image
                  src={imgSrc}
                  alt={article.title}
                  fill
                  className="absolute inset-0 h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
                  sizes="(max-width: 768px) 100vw, 25vw"
                  loading="lazy"
                />
              ) : (
                <div className="relative select-none text-6xl text-[var(--color-ink-faint)]" style={{ fontWeight: 500 }}>
                  {article.title?.charAt(0) ?? "N"}
                </div>
              )}
            </div>
            <div className="flex flex-1 flex-col p-6">
              <div className="mb-3">
                <span className="badge badge-soft">{article.category}</span>
              </div>
              <h3 className="mb-2 text-xl leading-tight text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{article.title}</h3>
              {article.excerpt && <p className="mb-4 flex-1 text-sm leading-6 text-[var(--color-ink-mute)] line-clamp-3">{article.excerpt}</p>}
              <div className="mt-auto border-t border-[var(--color-hairline-cool)] pt-4">
                <span className="inline-flex items-center gap-2 text-xs font-medium text-[var(--color-primary-deep)] transition-all group-hover:gap-3">
                  Read More
                  <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                  </svg>
                </span>
              </div>
            </div>
          </Link>
        );
      })}
    </div>
  );
}

export function ProjectGrid({ projects }: { projects: Project[] }) {
  return (
    <div className="grid gap-6 md:grid-cols-2">
      {projects.length === 0 ? (
        <div className="col-span-full flex flex-col items-center justify-center rounded-[12px] border-2 border-dashed border-[var(--color-hairline-strong)] py-20 text-center">
          <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-md bg-[var(--color-canvas-soft)]">
            <svg className="h-8 w-8 text-[var(--color-ink-faint)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5m8.25 3v6.75m0 0l-3-3m3 3l3-3M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" />
            </svg>
          </div>
          <p className="text-[var(--color-ink-mute)]">No projects yet</p>
        </div>
      ) : (
        projects.map((project, i) => <ProjectCard key={project.id} project={project} featured={i === 0} />)
      )}
    </div>
  );
}

export function NewsLive({ serverData }: { serverData: Article[] }) {
  return (
    <SiteShell>
      
      <PageBand>
        {serverData.length > 0 ? <ArticleGrid articles={serverData} /> : (
          <div className="flex flex-col items-center justify-center py-20 text-center">
            <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-md bg-[var(--color-canvas-soft)]">
              <svg className="h-8 w-8 text-[var(--color-ink-faint)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 7.5h1.5m-1.5 3h1.5m-7.5 3h7.5m-7.5 3h7.5m3-9h3.375c.621 0 1.125.504 1.125 1.125V18a2.25 2.25 0 01-2.25 2.25M16.5 7.5V18a2.25 2.25 0 002.25 2.25M16.5 7.5V4.875c0-.621-.504-1.125-1.125-1.125H4.125C3.504 3.75 3 4.254 3 4.875V18a2.25 2.25 0 002.25 2.25h13.5M6 7.5h3v3H6v-3z" />
              </svg>
            </div>
            <p className="text-[var(--color-ink-mute)]">No articles found.</p>
          </div>
        )}
      </PageBand>
    </SiteShell>
  );
}

/* ════════════════════════════════════════════════════════════════
   EVENTS
   ════════════════════════════════════════════════════════════════ */

export function EventsLive({ serverData }: { serverData: Event[] }) {
  return (
    <SiteShell>
      
      <PageBand>
        {serverData.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-center">
            <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-md bg-[var(--color-canvas-soft)]">
              <svg className="h-8 w-8 text-[var(--color-ink-faint)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <rect x="3" y="4" width="18" height="18" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" />
              </svg>
            </div>
            <p className="text-[var(--color-ink-mute)]">No events found.</p>
          </div>
        ) : (
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {serverData.map((event) => (
              <Link key={event.id} href={`/events/${event.id}`} className="group flex flex-col overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white transition-all duration-300 hover:-translate-y-1 hover:shadow-[var(--shadow-l2)]">
                <div className="relative flex h-40 w-full items-center justify-center overflow-hidden bg-[var(--color-canvas-soft)]">
                  {event.cover_image_url ? (
                    <Image src={resolveImageUrl(event.cover_image_url, imageFallback)} alt={event.title} fill className="absolute inset-0 h-full w-full object-cover transition-transform duration-500 group-hover:scale-105" sizes="(max-width: 768px) 100vw, 33vw" loading="lazy" />
                  ) : (
                    <div className="relative select-none text-6xl text-[var(--color-ink-faint)]" style={{ fontWeight: 500 }}>
                      {event.title?.charAt(0) ?? "E"}
                    </div>
                  )}
                </div>
                <div className="flex flex-1 flex-col p-6">
                  <div className="mb-3">
                    <span className="badge badge-soft">{event.category.replace("_", " ")}</span>
                  </div>
                  <h3 className="mb-2 text-xl leading-tight text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{event.title}</h3>
                  <p className="mb-4 flex-1 text-sm leading-6 text-[var(--color-ink-mute)] line-clamp-3">{event.short_description || event.description?.slice(0, 100)}</p>
                  <div className="flex flex-wrap items-center gap-3 border-t border-[var(--color-hairline-cool)] pt-4">
                    <div className="flex items-center gap-1.5 text-xs text-[var(--color-ink-mute)]">
                      <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}><rect x="3" y="4" width="18" height="18" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" /></svg>
                      {formatDate(event.event_date)}
                    </div>
                    {event.venue && (
                      <div className="flex items-center gap-1.5 text-xs text-[var(--color-ink-mute)]">
                        <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" /></svg>
                        {event.venue}
                      </div>
                    )}
                    <span className="ml-auto inline-flex items-center gap-1.5 rounded-[6px] border border-[var(--color-hairline-strong)] px-3 py-1.5 text-xs font-medium text-[var(--color-ink)] transition-colors group-hover:border-[var(--color-ink)]">
                      Details
                      <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" /></svg>
                    </span>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        )}
      </PageBand>
    </SiteShell>
  );
}

/* ════════════════════════════════════════════════════════════════
   CONTACT
   ════════════════════════════════════════════════════════════════ */

export function ContactLive() {
  return (
    <SiteShell>
      
      <PageBand>
        <div className="grid gap-10 lg:grid-cols-[1fr_420px]">
          <div className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-8">
            <h2 className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Send a Message</h2>
            <p className="mt-1 text-sm text-[var(--color-ink-mute)]">We typically respond within 24 hours.</p>
            <div className="mt-6"><ContactForm /></div>
          </div>
          <div className="space-y-5">
            {([
              ["Address", fallbackSettings.address, "M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0zM15 11a3 3 0 11-6 0 3 3 0 016 0z"],
              ["Phone", fallbackSettings.phone, "M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 014.69 12 19.79 19.79 0 011.65 3.18 2 2 0 013.62 1h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L7.91 8.59a16 16 0 006 6l.94-.94a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"],
              ["Email", fallbackSettings.email, "M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2zM22 6l-10 7L2 6"],
            ] as const).map(([title, value, path]) => (
              <div key={title} className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-6 transition-all duration-200 hover:shadow-[var(--shadow-l1)]">
                <div className="flex items-center gap-4">
                  <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-[var(--color-canvas-soft)]">
                    <svg width="20" height="20" fill="none" stroke="var(--color-primary-deep)" strokeWidth="2" viewBox="0 0 24 24"><path d={path} strokeLinecap="round" strokeLinejoin="round" /></svg>
                  </span>
                  <div>
                    <p className="text-xs font-medium uppercase tracking-wider text-[var(--color-ink-mute-2)]">{title}</p>
                    <p className="text-sm font-medium text-[var(--color-ink)]">{value}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </PageBand>
    </SiteShell>
  );
}

/* ════════════════════════════════════════════════════════════════
   CROWDFUNDING
   ════════════════════════════════════════════════════════════════ */

export function CrowdfundingLive({ serverData }: { serverData: Campaign[] }) {
  return (
    <SiteShell>
      
      <PageBand>
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
          {serverData.map((c) => {
            const pct = Math.min(100, Math.round((c.raised_amount || 0) / (c.goal_amount || 1) * 100));
            return (
              <article key={c.id} className="group flex flex-col overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white transition-all duration-300 hover:-translate-y-1 hover:shadow-[var(--shadow-l2)]">
                <div className="relative flex h-40 w-full items-center justify-center overflow-hidden bg-[var(--color-canvas-soft)]">
                  {resolveImageUrl(c.cover_image_url) ? (
                    <Image src={resolveImageUrl(c.cover_image_url)} alt={c.title} fill className="object-cover transition-transform duration-500 group-hover:scale-105" sizes="(max-width: 768px) 100vw, 33vw" loading="lazy" />
                  ) : (
                    <div className="relative select-none text-6xl text-[var(--color-ink-faint)]" style={{ fontWeight: 500 }}>
                      {c.title?.charAt(0) ?? "C"}
                    </div>
                  )}
                </div>
                <div className="flex flex-1 flex-col p-6">
                  <div className="mb-3">
                    <span className="badge badge-soft">{c.category}</span>
                  </div>
                  <h3 className="mb-2 text-xl leading-tight text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{c.title}</h3>
                  <p className="mb-4 flex-1 text-sm leading-6 text-[var(--color-ink-mute)] line-clamp-3">{c.short_description}</p>
                  <div className="mt-auto">
                    <div className="mb-1.5 flex justify-between text-xs text-[var(--color-ink-mute)]">
                      <span className="text-[var(--color-ink)]">₹{Number(c.raised_amount || 0).toLocaleString("en-IN")} raised</span>
                      <span>₹{Number(c.goal_amount || 0).toLocaleString("en-IN")} goal</span>
                    </div>
                    <div className="progress-bar mb-4">
                      <div className="progress-fill" style={{ width: `${pct}%` }} />
                    </div>
                    <Link href={`/crowdfunding/detail?slug=${c.slug || c.id}`} className="btn w-full">
                      Donate Now
                    </Link>
                  </div>
                </div>
              </article>
            );
          })}
        </div>
      </PageBand>
    </SiteShell>
  );
}

export function CrowdfundingStatusClient({ orderId }: { orderId: string }) {
  const [paymentStatus, setPaymentStatus] = useState<"checking" | "paid" | "pending" | "error">("checking");
  useEffect(() => {
    if (!orderId) { setPaymentStatus("error"); return; }
    const check = async () => {
      try {
        const res = await fetch(`${API}/donations/payment-status/${orderId}`);
        if (!res.ok) { setPaymentStatus("pending"); return; }
        const data = await res.json();
        setPaymentStatus(data.status === "paid" ? "paid" : "pending");
      } catch { setPaymentStatus("error"); }
    };
    const timer = setTimeout(check, 2000);
    return () => clearTimeout(timer);
  }, [orderId]);
  return (
    <div className="w-full max-w-md rounded-[12px] border border-[var(--color-hairline)] bg-white p-10 text-center shadow-[var(--shadow-l2)]">
      {paymentStatus === "checking" && (
        <>
          <div className="mx-auto mb-6 h-14 w-14 animate-spin rounded-full border-[3px] border-[var(--color-hairline-cool)] border-t-primary" />
          <h2 className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Verifying Payment</h2>
          <p className="mt-2 text-sm text-[var(--color-ink-mute)]">Please wait while we confirm your payment...</p>
        </>
      )}
      {paymentStatus === "paid" && (
        <>
          <div className="mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-[var(--color-primary)]/15 text-3xl">{'\u2705'}</div>
          <h2 className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Payment Successful!</h2>
          <p className="mt-2 text-sm text-[var(--color-ink-mute)]">Thank you for your contribution.</p>
        </>
      )}
      {paymentStatus === "pending" && (
        <>
          <div className="mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-[var(--color-canvas-soft)] text-3xl">{'\u23F3'}</div>
          <h2 className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Payment Pending</h2>
          <p className="mt-2 text-sm text-[var(--color-ink-mute)]">Your payment is being processed.</p>
        </>
      )}
      {paymentStatus === "error" && (
        <>
          <div className="mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-[var(--color-canvas-soft)] text-3xl">{'\u274C'}</div>
          <h2 className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Something went wrong</h2>
          <p className="mt-2 text-sm text-[var(--color-ink-mute)]">Could not verify payment status. Contact support if amount was deducted.</p>
        </>
      )}
    </div>
  );
}

export function CrowdfundingDetailPage({ slug }: { slug: string }) {
  const [campaign, setCampaign] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    if (!slug) { setLoading(false); return; }
    fetch(`${API}/crowdfunding/${slug}`)
      .then(r => r.json())
      .then(data => { setCampaign(data); setLoading(false); })
      .catch(() => setLoading(false));
  }, [slug]);
  if (loading) return <SiteShell><PageBand><p className="text-center text-[var(--color-ink-mute)]">Loading campaign...</p></PageBand></SiteShell>;
  if (!campaign) return <SiteShell><PageBand><p className="text-center text-[var(--color-ink-mute)]">Campaign not found.</p></PageBand></SiteShell>;

  const pct = Math.min(100, Math.round((campaign.raised_amount || 0) / (campaign.goal_amount || 1) * 100));
  const coverSrc = resolveImageUrl(campaign.cover_image_url, imageFallback);

  return (
    <SiteShell>
      
      <PageBand>
        <div className="grid gap-10 lg:grid-cols-[1fr_420px]">
          <div className="space-y-8">
            <div className="relative flex h-72 items-center justify-center overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white">
              <Image src={coverSrc} alt={campaign.title} fill className="absolute inset-0 h-full w-full object-cover transition duration-700 group-hover:scale-105" sizes="(max-width: 1024px) 100vw, 600px" priority />
            </div>

            {campaign.short_description && (
              <p className="text-lg leading-7 text-[var(--color-ink-mute)]">
                {campaign.short_description}
              </p>
            )}

            <div className="prose-ink prose prose-lg max-w-none" dangerouslySetInnerHTML={{ __html: campaign.description || "" }} />

            {campaign.recent_donors?.length > 0 && (
              <div className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-8">
                <h3 className="mb-5 flex items-center gap-2 text-lg text-[var(--color-ink)]" style={{ fontWeight: 500 }}>
                  <svg className="h-5 w-5 text-[var(--color-primary-deep)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                  </svg>
                  Recent Donors
                </h3>
                <div className="divide-y divide-[var(--color-hairline-cool)]">
                  {campaign.recent_donors.map((d: any, i: number) => (
                    <div key={i} className="flex items-center justify-between py-3 first:pt-0 last:pb-0">
                      <div className="flex items-center gap-3">
                        <div className="flex h-9 w-9 items-center justify-center rounded-full bg-[var(--color-canvas-soft)] text-xs font-medium text-[var(--color-ink)]">
                          {d.donor_name?.charAt(0)?.toUpperCase() ?? "A"}
                        </div>
                        <span className="text-sm font-medium text-[var(--color-ink)]">{d.donor_name}</span>
                      </div>
                      <span className="text-sm font-medium text-[var(--color-primary-deep)]">
                        +₹{Number(d.amount || 0).toLocaleString("en-IN")}
                      </span>
                    </div>
                  ))}
                </div>
                {campaign.donor_count > campaign.recent_donors.length && (
                  <p className="mt-4 text-center text-xs text-[var(--color-ink-mute-2)]">
                    +{campaign.donor_count - campaign.recent_donors.length} more donors
                  </p>
                )}
              </div>
            )}
          </div>

          <div className="space-y-6 lg:sticky lg:top-24 lg:self-start">
            <div className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-8">
              <h3 className="mb-5 text-xs font-medium uppercase tracking-widest text-[var(--color-ink-mute-2)]">Campaign Progress</h3>
              <div className="mb-1 flex items-end justify-between">
                <span className="text-3xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>
                  ₹{Number(campaign.raised_amount || 0).toLocaleString("en-IN")}
                </span>
                <span className="text-lg text-[var(--color-ink-mute)]">{pct}%</span>
              </div>
              <p className="mb-4 text-xs text-[var(--color-ink-mute-2)]">
                raised of ₹{Number(campaign.goal_amount || 0).toLocaleString("en-IN")} goal
              </p>
              <div className="progress-bar mb-6">
                <div className="progress-fill" style={{ width: `${pct}%` }} />
              </div>
              <CrowdfundingDonationForm campaignId={campaign.id} campaignTitle={campaign.title} />
            </div>

            <div className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-8">
              <h3 className="mb-5 text-xs font-medium uppercase tracking-widest text-[var(--color-ink-mute-2)]">Campaign Info</h3>
              <div className="space-y-4 text-sm">
                {campaign.location && (
                  <div className="flex items-start gap-3">
                    <svg className="mt-0.5 h-4 w-4 shrink-0 text-[var(--color-ink-mute-2)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" />
                    </svg>
                    <span className="text-[var(--color-ink-mute)]">{campaign.location}</span>
                  </div>
                )}
                {campaign.beneficiaries_count > 0 && (
                  <div className="flex items-start gap-3">
                    <svg className="mt-0.5 h-4 w-4 shrink-0 text-[var(--color-ink-mute-2)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    <span className="text-[var(--color-ink-mute)]">{campaign.beneficiaries_count.toLocaleString("en-IN")} beneficiaries</span>
                  </div>
                )}
                {campaign.start_date && (
                  <div className="flex items-start gap-3">
                    <svg className="mt-0.5 h-4 w-4 shrink-0 text-[var(--color-ink-mute-2)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <rect x="3" y="4" width="18" height="18" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" />
                    </svg>
                    <span className="text-[var(--color-ink-mute)]">
                      {formatDate(campaign.start_date)}{campaign.end_date ? ` - ${formatDate(campaign.end_date)}` : ""}
                    </span>
                  </div>
                )}
                <div className="flex items-start gap-3">
                  <svg className="mt-0.5 h-4 w-4 shrink-0 text-[var(--color-ink-mute-2)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                  </svg>
                  <span className="text-[var(--color-ink-mute)]">{campaign.donor_count ?? 0} donors</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </PageBand>
    </SiteShell>
  );
}

/* ════════════════════════════════════════════════════════════════
   AREAS / LOCATIONS
   ════════════════════════════════════════════════════════════════ */

export function AreasLive({ serverData }: { serverData: Area[] }) {
  return (
    <SiteShell>
      
      <PageBand>
        {serverData.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-center">
            <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-md bg-[var(--color-canvas-soft)]">
              <svg className="h-8 w-8 text-[var(--color-ink-faint)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" />
              </svg>
            </div>
            <p className="text-[var(--color-ink-mute)]">No areas found.</p>
          </div>
        ) : (
          <div className="grid gap-0 md:grid-cols-2">
            {serverData.map((area, i) => (
              <div key={area.id} className={`py-8 md:py-10 ${i % 2 === 1 ? "md:pl-10" : "md:pr-10"} ${i >= 2 ? "md:pt-0" : ""} ${i < serverData.length - 2 ? "border-b border-[var(--color-hairline-cool)] md:border-b-0" : ""} ${i < serverData.length - 2 && i % 2 === 0 ? "md:border-b md:border-[var(--color-hairline-cool)]" : ""}`}>
                <div className="group flex items-start gap-5 rounded-[12px] p-5 transition-all duration-200 hover:bg-[var(--color-canvas-soft)]">
                  <div className="mt-1 flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-[var(--color-canvas-soft)] text-lg text-[var(--color-primary-deep)]" style={{ fontWeight: 500 }}>
                    {area.area_name.charAt(0)}
                  </div>
                  <div className="min-w-0 flex-1">
                    <h3 className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{area.area_name}</h3>
                    <div className="mt-3 flex items-center gap-6">
                      <div className="flex items-center gap-2">
                        <span className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{area.members_count}</span>
                        <span className="text-xs font-medium uppercase tracking-wider text-[var(--color-ink-mute-2)]">Members</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{area.beneficiaries_count}</span>
                        <span className="text-xs font-medium uppercase tracking-wider text-[var(--color-ink-mute-2)]">Beneficiaries</span>
                      </div>
                    </div>
                    {area.impact_summary && (
                      <p className="mt-3 text-sm leading-6 text-[var(--color-ink-mute)]">{area.impact_summary}</p>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </PageBand>
    </SiteShell>
  );
}
