"use client";

import Link from "next/link";
import { useState } from "react";
import { usePublicCopy } from "@/lib/cms/use-public-copy";
import { normalizeVolunteerPageCopy } from "@/content/volunteer-page";
import {
  DEFAULT_VOLUNTEER_LANDING,
  type VolunteerLandingData,
} from "@/lib/volunteer-landing";
import type { VolunteerDivision } from "@/lib/volunteer-applications";
import VolunteerApplicationForm from "./VolunteerApplicationForm";
import VolunteerCrisisSupport from "./VolunteerCrisisSupport";
import { InlineText } from "@/components/cms/LandingInlineEditor";
import LandingSectionCanvas from "@/components/cms/LandingSectionCanvas";
import type { LandingPageSection } from "@/lib/cms/landing-section-schema";

const roadmap = [
  {
    month: "Bulan 1–2",
    mode: "Online",
    title: "Interview Volunteer",
    detail: "Ngobrol untuk saling mengenal potensi, minat, dan hal yang ingin kamu pelajari.",
  },
  {
    month: "Bulan 1–3",
    mode: "Online",
    title: "Upgrading Volunteer",
    detail: "Mengenal konsep dakwah, komunikasi, dan pengelolaan event yang relevan.",
  },
  {
    month: "Bulan 1–3",
    mode: "Offline BSD",
    title: "Hangout Volunteer",
    detail: "Kumpul santai di BSD untuk membangun kedekatan dan rasa nyaman sebagai tim.",
  },
  {
    month: "Bulan 4",
    mode: "Offline BSD",
    title: "Welcome Party",
    detail: "Penyambutan resmi dan penempatan divisi berdasarkan minat serta proses bersama.",
  },
  {
    month: "Bulan 4–6",
    mode: "Offline BSD",
    title: "Big Event & Follow Up",
    detail: "Menyiapkan event bersama dan menjaga koneksi melalui pendampingan setelahnya.",
  },
] as const;

const pillars = [
  {
    title: "Interview",
    mode: "Online",
    detail: "Saling mengenal volunteer dan menemukan potensi yang ingin dikembangkan.",
  },
  {
    title: "Upgrading",
    mode: "Online",
    detail: "Belajar konsep, standar event, dan gerak dakwah YukNgaji.",
  },
  {
    title: "Hangout",
    mode: "Offline BSD",
    detail: "Nongkrong dan membangun bonding di ruang publik BSD.",
  },
  {
    title: "Welcome Party",
    mode: "Offline BSD",
    detail: "Penyambutan tim regional dan penempatan divisi.",
  },
  {
    title: "Big Event",
    mode: "Offline BSD",
    detail: "Kolaborasi volunteer untuk mengelola event regional.",
  },
  {
    title: "Follow Up",
    mode: "Offline BSD",
    detail: "Pendampingan empat sesi Kelas KEY, agenda MainYuk, dan olahraga bersama.",
  },
] as const;

const divisions: {
  value: VolunteerDivision;
  eyebrow: string;
  description: string;
  activities: string[];
  fit: string;
}[] = [
  {
    value: "EVENT",
    eyebrow: "Operasional & pengalaman acara",
    description: "Membantu menghadirkan perjumpaan tatap muka yang terasa nyaman di BSD.",
    activities: [
      "Mengatur alur acara dan koordinasi panggung",
      "Mengelola venue serta logistik regional BSD",
      "Menyambut peserta dengan hospitality yang hangat",
    ],
    fit: "Kamu suka bergerak, koordinasi langsung, dan menyambut orang baru.",
  },
  {
    value: "MEDIA",
    eyebrow: "Cerita & visual",
    description: "Mengolah cerita kegiatan menjadi konten yang terasa dekat dan mudah dibagikan.",
    activities: [
      "Videografi cinematic dan reels kreatif",
      "Desain visual untuk kebutuhan kegiatan",
      "Copywriting media sosial",
    ],
    fit: "Kamu tertarik pada visual, video, desain, atau merangkai kata.",
  },
  {
    value: "FOLLOW_UP",
    eyebrow: "Pendampingan & kebersamaan",
    description: "Menjaga koneksi setelah kegiatan lewat belajar dan agenda bersama.",
    activities: [
      "Mendampingi empat sesi Kelas KEY",
      "Menyiapkan agenda MainYuk dan olahraga bareng",
      "Menjadi teman ngobrol yang hadir dengan empati",
    ],
    fit: "Kamu senang mendengar, menemani, dan merawat lingkar pertemanan.",
  },
];

export default function VolunteerLandingView({
  page,
  landingSections = [],
  preview = false,
}: {
  page: VolunteerLandingData;
  landingSections?: LandingPageSection[];
  preview?: boolean;
}) {
  const publicCopy = usePublicCopy();
  const copy = normalizeVolunteerPageCopy(publicCopy.volunteerPageCopyJson);
  const volunteerJoinUrl = publicCopy.volunteerHeroPrimaryHref.startsWith("https://")
    ? publicCopy.volunteerHeroPrimaryHref
    : new URL(publicCopy.volunteerHeroPrimaryHref, "https://yukngajibsd.com/gabung-volunteer").toString();
  const structuredData = {
    "@context": "https://schema.org",
    "@type": "Organization",
    "@id": "https://yukngajibsd.com/#yukngaji-bsd",
    name: "YukNgaji BSD",
    url: "https://yukngajibsd.com",
    description: "Komunitas regional YukNgaji di BSD City, Tangerang Selatan.",
    location: {
      "@type": "Place",
      name: "BSD City, Tangerang Selatan",
      address: {
        "@type": "PostalAddress",
        addressLocality: "Tangerang Selatan",
        addressRegion: "Banten",
        addressCountry: "ID",
      },
    },
    potentialAction: {
      "@type": "JoinAction",
      name: "Masuk antrean Volunteer Regional YukNgaji BSD Batch 2",
      target: {
        "@type": "EntryPoint",
        urlTemplate: volunteerJoinUrl,
        inLanguage: "id",
      },
      object: {
        "@type": "Organization",
        name: "Volunteer Regional YukNgaji BSD",
      },
    },
  };
  const [selectedDivision, setSelectedDivision] = useState<VolunteerDivision | null>(null);
  const [notice, setNotice] = useState("");
  const paragraphs = page.content.split(/\n\s*\n/).filter(Boolean);

  function updateDivision(division: VolunteerDivision | null) {
    setSelectedDivision(division);
    setNotice(
      division
        ? `${copy.divisions.items.find(item => item.value === division)?.title || division} terpilih. Pilihan ini akan ikut tercatat di antreanmu.`
        : "",
    );
  }

  function chooseDivision(division: VolunteerDivision) {
    updateDivision(division);
    document.getElementById("volunteer-division")?.focus();
  }

  return (
    <main className={"vol-landing"}>
      {!preview && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData).replace(/</g, "\\u003c") }}
        />
      )}
      <a className={`${"vol-wrap"} ${"vol-skipLink"}`} href="#main-content"><InlineText path="volunteerCopy.skipLink" value={copy.skipLink} /></a>

      {preview && (
        <p className={"vol-previewNotice"} role="status">
          <InlineText path="volunteerCopy.previewNotice" value={copy.previewNotice} />
        </p>
      )}

      <aside className={"vol-announcement"} aria-label={copy.announcementLabel}>
        <div className={`${"vol-wrap"} ${"vol-announcementInner"}`}>
          <span className={`${"vol-statusPill"} ${"vol-statusPillClosed"}`}><InlineText path="volunteerCopy.announcement.closed" value={copy.announcement.closed} /></span>
          <span className={`${"vol-statusPill"} ${"vol-statusPillOpen"}`}><InlineText path="volunteerCopy.announcement.open" value={copy.announcement.open} /></span>
          <span><InlineText path="volunteerCopy.announcement.note" value={copy.announcement.note} /></span>
        </div>
      </aside>

      <header className={"vol-nav"}>
        <div className={`${"vol-wrap"} ${"vol-navInner"}`}>
          <Link className={"vol-brand"} href="/" aria-label={copy.navigation.brandLabel}>
            <span className={"vol-brandMark"} aria-hidden="true">YN</span>
            <span className={"vol-brandText"}>
              <InlineText path="publicCopy.siteTitle" value={publicCopy.siteTitle} />
              <small><InlineText path="volunteerCopy.navigation.subtitle" value={copy.navigation.subtitle} /></small>
            </span>
          </Link>
          <nav className={"vol-navLinks"} aria-label={copy.navigation.ariaLabel}>
            <a href="#roadmap"><InlineText path="volunteerCopy.navigation.labels.0" value={copy.navigation.labels[0]} /></a>
            <a href="#pilar"><InlineText path="volunteerCopy.navigation.labels.1" value={copy.navigation.labels[1]} /></a>
            <a href="#divisi"><InlineText path="volunteerCopy.navigation.labels.2" value={copy.navigation.labels[2]} /></a>
            <a href="#faq"><InlineText path="volunteerCopy.navigation.labels.3" value={copy.navigation.labels[3]} /></a>
            <Link href="/kegiatan"><InlineText path="volunteerCopy.navigation.labels.4" value={copy.navigation.labels[4]} /></Link>
          </nav>
          <a className={`${"vol-button"} ${"vol-navCta"}`} href={publicCopy.volunteerNavCtaHref}>
            <InlineText path="volunteerCopy.navigation.cta" value={copy.navigation.cta} />
          </a>
        </div>
      </header>

      <div className={"vol-wrap"}>
        <section className={"vol-hero"} id="main-content" aria-labelledby="volunteer-title">
          <div>
            <p className={"vol-eyebrow"}><InlineText path="volunteerCopy.hero.eyebrow" value={copy.hero.eyebrow} /></p>
            <h1 id="volunteer-title">
              <InlineText path="volunteerCopy.hero.title" value={copy.hero.title} />
              <span className={"vol-heroAccent"}> <InlineText path="volunteerCopy.hero.accent" value={copy.hero.accent} /></span>
            </h1>
            <p className={"vol-heroDescription"}>
              <InlineText path="volunteerCopy.hero.description" value={copy.hero.description} />
              {page.description && page.description !== DEFAULT_VOLUNTEER_LANDING.description && <> <InlineText path="volunteerLanding.description" value={page.description} /></>}
            </p>
            <div className={"vol-heroActions"}>
              <a className={"vol-button"} href={publicCopy.volunteerHeroPrimaryHref}><InlineText path="volunteerCopy.hero.primaryCta" value={copy.hero.primaryCta} /> <span aria-hidden="true">→</span></a>
              <a className={`${"vol-button"} ${"vol-buttonSecondary"}`} href={publicCopy.volunteerHeroSecondaryHref}><InlineText path="volunteerCopy.hero.secondaryCta" value={copy.hero.secondaryCta} /></a>
            </div>
            <div className={"vol-heroMeta"} aria-label="Informasi program">
              {copy.hero.meta.map((item, index) => <span className={"vol-tag"} key={index}><InlineText path={`volunteerCopy.hero.meta.${index}`} value={item} /></span>)}
            </div>
          </div>
          <div className={"vol-heroArt"} aria-label="Program volunteer YukNgaji BSD, Juli sampai Desember 2026">
            <div className={"vol-artTop"}>
              <span><InlineText path="volunteerCopy.hero.artLabel" value={copy.hero.artLabel} /></span>
              <span className={"vol-artNumber"}><InlineText path="volunteerCopy.hero.artNumber" value={copy.hero.artNumber} /></span>
            </div>
            <p className={"vol-artMessage"}><InlineText path="volunteerCopy.hero.artMessage" value={copy.hero.artMessage} /></p>
            <div className={"vol-artBottom"}>
              <InlineText path="volunteerLanding.title" value={page.title} />
              <strong><InlineText path="volunteerCopy.hero.artFooter" value={copy.hero.artFooter} /></strong>
            </div>
            {page.image && (
              // CMS images can use external URLs that are not listed in next.config.
              // eslint-disable-next-line @next/next/no-img-element
              <img className={"vol-heroImage"} src={page.image} alt={copy.hero.artAlt} />
            )}
          </div>
        </section>

        <section className={"vol-section"} aria-labelledby="safe-space-heading">
          <div className={"vol-sectionHeader"}>
            <p className={"vol-sectionEyebrow"}><InlineText path="volunteerCopy.safety.eyebrow" value={copy.safety.eyebrow} /></p>
            <h2 id="safe-space-heading"><InlineText path="volunteerCopy.safety.title" value={copy.safety.title} /></h2>
            <p className={"vol-sectionIntro"}><InlineText path="volunteerCopy.safety.intro" value={copy.safety.intro} /></p>
          </div>
          <div className={"vol-safetyGrid"}>
            {copy.safety.cards.map((card, index) => (
              <article className={"vol-safetyItem"} key={card.title}>
                <strong><InlineText path={`volunteerCopy.safety.cards.${index}.title`} value={card.title} /></strong>
                <p><InlineText path={`volunteerCopy.safety.cards.${index}.description`} value={card.description} /></p>
              </article>
            ))}
          </div>
        </section>

        {paragraphs.length > 0 && (
          <section className={`${"vol-section"} ${"vol-contentSection"}`} aria-labelledby="about-heading">
            <div>
              <p className={"vol-sectionEyebrow"}><InlineText path="volunteerCopy.aboutEyebrow" value={copy.aboutEyebrow} /></p>
              <InlineText as="h2" path="volunteerLanding.title" value={page.title} />
            </div>
            <div className={"vol-contentCopy"}>
              {paragraphs.map((paragraph, index) => <p key={index}>{paragraph}</p>)}
            </div>
          </section>
        )}

        <section className={"vol-section"} aria-labelledby="why-heading">
          <div className={"vol-sectionHeader"}>
            <p className={"vol-sectionEyebrow"}><InlineText path="volunteerCopy.why.eyebrow" value={copy.why.eyebrow} /></p>
            <h2 id="why-heading"><InlineText path="volunteerCopy.why.title" value={copy.why.title} /></h2>
          </div>
          <div className={"vol-problemGrid"}>
            {copy.why.cards.map((card, index) => (
              <article className={"vol-problem"} key={card.title}>
                <div>
                  <span className={"vol-problemMarker"} aria-hidden="true">{String(index + 1).padStart(2, "0")}</span>
                  <h3><InlineText path={`volunteerCopy.why.cards.${index}.title`} value={card.title} /></h3>
                  <p><InlineText path={`volunteerCopy.why.cards.${index}.description`} value={card.description} /></p>
                </div>
                <p className={"vol-promise"}><InlineText path={`volunteerCopy.why.cards.${index}.promise`} value={card.promise} /></p>
              </article>
            ))}
          </div>
        </section>

        <section className={"vol-section"} id="roadmap" aria-labelledby="roadmap-heading">
          <div className={"vol-sectionHeader"}>
            <p className={"vol-sectionEyebrow"}><InlineText path="volunteerCopy.roadmap.eyebrow" value={copy.roadmap.eyebrow} /></p>
            <h2 id="roadmap-heading"><InlineText path="volunteerCopy.roadmap.title" value={copy.roadmap.title} /></h2>
            <p className={"vol-sectionIntro"}><InlineText path="volunteerCopy.roadmap.intro" value={copy.roadmap.intro} /></p>
          </div>
          <ol className={"vol-roadmap"}>
            {copy.roadmap.steps.map((step, index) => (
              <li className={"vol-roadmapItem"} key={step.title}>
                <div className={"vol-roadmapMeta"}>
                  <span className={"vol-roadmapStep"}>STEP 0{index + 1}</span>
                  <span><InlineText path={`volunteerCopy.roadmap.steps.${index}.mode`} value={step.mode} /></span>
                </div>
                <span className={"vol-roadmapMonth"}><InlineText path={`volunteerCopy.roadmap.steps.${index}.month`} value={step.month} /></span>
                <h3><InlineText path={`volunteerCopy.roadmap.steps.${index}.title`} value={step.title} /></h3>
                <p><InlineText path={`volunteerCopy.roadmap.steps.${index}.detail`} value={step.detail} /></p>
              </li>
            ))}
          </ol>
        </section>

        <section className={"vol-section"} id="pilar" aria-labelledby="pillars-heading">
          <div className={"vol-sectionHeader"}>
            <p className={"vol-sectionEyebrow"}><InlineText path="volunteerCopy.pillars.eyebrow" value={copy.pillars.eyebrow} /></p>
            <h2 id="pillars-heading"><InlineText path="volunteerCopy.pillars.title" value={copy.pillars.title} /></h2>
            <p className={"vol-sectionIntro"}><InlineText path="volunteerCopy.pillars.intro" value={copy.pillars.intro} /></p>
          </div>
          <div className={"vol-pillarsGrid"}>
            {copy.pillars.items.map((pillar, index) => (
              <article className={"vol-pillar"} key={pillar.title}>
                <div className={"vol-pillarTop"}>
                  <span className={"vol-pillarIcon"} aria-hidden="true">0{index + 1}</span>
                  <span className={`${"vol-tag"} ${pillar.mode === "Online" ? "vol-pillTagOnline" : "vol-pillTagOffline"}`}>
                    <InlineText path={`volunteerCopy.pillars.items.${index}.mode`} value={pillar.mode} />
                  </span>
                </div>
                <h3><InlineText path={`volunteerCopy.pillars.items.${index}.title`} value={pillar.title} /></h3>
                <p><InlineText path={`volunteerCopy.pillars.items.${index}.detail`} value={pillar.detail} /></p>
              </article>
            ))}
          </div>
          <p className={"vol-programNote"}>
            <InlineText path="volunteerCopy.pillars.note" value={copy.pillars.note} />
          </p>
        </section>

        <section className={"vol-section"} id="divisi" aria-labelledby="divisions-heading">
          <div className={"vol-sectionHeader"}>
            <p className={"vol-sectionEyebrow"}><InlineText path="volunteerCopy.divisions.eyebrow" value={copy.divisions.eyebrow} /></p>
            <h2 id="divisions-heading"><InlineText path="volunteerCopy.divisions.title" value={copy.divisions.title} /></h2>
            <p className={"vol-sectionIntro"}><InlineText path="volunteerCopy.divisions.intro" value={copy.divisions.intro} /></p>
          </div>
          <div className={"vol-divisionsGrid"}>
            {copy.divisions.items.map((division, index) => (
              <article className={"vol-division"} key={division.value}>
                <span className={"vol-divisionLabel"}><InlineText path={`volunteerCopy.divisions.items.${index}.eyebrow`} value={division.eyebrow} /></span>
                <h3><InlineText path={`volunteerCopy.divisions.items.${index}.title`} value={division.title} /></h3>
                <p><InlineText path={`volunteerCopy.divisions.items.${index}.description`} value={division.description} /></p>
                <ul>
                  {division.activities.map((activity, activityIndex) => <li key={activityIndex}><InlineText path={`volunteerCopy.divisions.items.${index}.activities.${activityIndex}`} value={activity} /></li>)}
                </ul>
                <p className={"vol-divisionFit"}>
                  <strong>Mungkin cocok kalau:</strong>
                  <InlineText path={`volunteerCopy.divisions.items.${index}.fit`} value={division.fit} />
                </p>
                {!preview && (
                  <button
                    className={`${"vol-button"} ${"vol-buttonSecondary"} ${"vol-divisionAction"}`}
                    type="button"
                    aria-pressed={selectedDivision === division.value}
                    onClick={() => chooseDivision(division.value as VolunteerDivision)}
                  >
                    <InlineText path={`volunteerCopy.divisions.items.${index}.cta`} value={division.cta} />
                  </button>
                )}
              </article>
            ))}
          </div>
          {notice && (
            <div className={`${"vol-toast"} ${"vol-divisionToast"}`} role="status" aria-live="polite">
              <p>{notice}</p>
              <button
                className={"vol-toastClose"}
                type="button"
                aria-label="Tutup notifikasi pilihan divisi"
                onClick={() => setNotice("")}
              >
                ×
              </button>
            </div>
          )}
        </section>

        <section className={`${"vol-section"} ${"vol-formSection"}`} id="volunteer-form" aria-labelledby="form-heading">
          <div className={`${"vol-formPanel"} ${"vol-wrap"}`}>
            <div className={"vol-formHeading"}>
              <span className={`${"vol-statusPill"} ${"vol-statusPillOpen"}`}><InlineText path="volunteerCopy.form.status" value={copy.form.status} /></span>
              <h2 id="form-heading"><InlineText path="volunteerCopy.form.title" value={copy.form.title} /></h2>
              <p>
                <InlineText path="volunteerCopy.form.description" value={copy.form.description} />
              </p>
            </div>
            {preview ? (
              <p className={"vol-previewNotice"}><InlineText path="volunteerCopy.form.preview" value={copy.form.preview} /></p>
            ) : (
              <VolunteerApplicationForm
                initialDivision={selectedDivision}
                onDivisionChange={updateDivision}
              />
            )}
          </div>
        </section>

        <section className={"vol-section"} id="faq" aria-labelledby="faq-heading">
          <div className={"vol-sectionHeader"}>
            <p className={"vol-sectionEyebrow"}><InlineText path="volunteerCopy.faq.eyebrow" value={copy.faq.eyebrow} /></p>
            <h2 id="faq-heading"><InlineText path="volunteerCopy.faq.title" value={copy.faq.title} /></h2>
            <p className={"vol-sectionIntro"}><InlineText path="volunteerCopy.faq.intro" value={copy.faq.intro} /></p>
          </div>
          <div className={"vol-faqList"}>
            {copy.faq.items.map((item, index) => (
              <details className={"vol-faqItem"} key={index}>
                <summary><InlineText path={`volunteerCopy.faq.items.${index}.question`} value={item.question} /></summary>
                <p className={"vol-faqAnswer"}><InlineText path={`volunteerCopy.faq.items.${index}.answer`} value={item.answer} /></p>
              </details>
            ))}
          </div>
        </section>

        <section className={"vol-section"} aria-label="Informasi dukungan krisis">
          <VolunteerCrisisSupport copy={copy.support} />
        </section>
        <LandingSectionCanvas
          pageType="volunteer"
          pageKey="volunteer"
          initialSections={landingSections}
        />
      </div>

      <footer className={"vol-footer"}>
        <div className={`${"vol-wrap"} ${"vol-footerInner"}`}>
          <div className={"vol-footerBrand"}>
            <Link className={"vol-brand"} href="/">
              <span className={"vol-brandMark"} aria-hidden="true">YN</span>
              <span className={"vol-brandText"}><InlineText path="publicCopy.siteTitle" value={publicCopy.siteTitle} /><small><InlineText path="volunteerCopy.footer.subtitle" value={copy.footer.subtitle} /></small></span>
            </Link>
            <p><InlineText path="volunteerCopy.footer.tagline" value={copy.footer.tagline} /></p>
          </div>
          <nav className={"vol-footerLinks"} aria-label="Navigasi footer volunteer">
            <a href="#roadmap"><InlineText path="volunteerCopy.footer.links.0" value={copy.footer.links[0]} /></a>
            <a href="#divisi"><InlineText path="volunteerCopy.footer.links.1" value={copy.footer.links[1]} /></a>
            <a href="#faq"><InlineText path="volunteerCopy.footer.links.2" value={copy.footer.links[2]} /></a>
            <a href={publicCopy.volunteerFooterEventsHref}><InlineText path="volunteerCopy.footer.links.3" value={copy.footer.links[3]} /></a>
            <a href={publicCopy.volunteerFooterJoinHref}><InlineText path="volunteerCopy.footer.links.4" value={copy.footer.links[4]} /></a>
          </nav>
        </div>
        <div className={`${"vol-wrap"} ${"vol-copyright"}`}>
          <InlineText path="volunteerCopy.footer.copyright" value={copy.footer.copyright} />
        </div>
      </footer>
    </main>
  );
}
