"use client";

import { useState, useEffect, useRef, type ReactNode } from "react";
import { ChevronDown, Loader2, Scale } from "lucide-react";
import AnimatedSection from "@/components/AnimatedSection";
import Link from "next/link";
import PageHeader from "@/components/ui/PageHeader";
import { getStoredLanguage } from "@/lib/language";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useLanguage } from "@/src/hooks/LanguageContext";
import { getLegalPages } from "@/lib/api/apis";

interface LegalPage {
  id: string;
  slug: string;
  title: string;
  title_english: string;
  title_hindi: string;
  content: string;
  content_english: string;
  content_hindi: string;
  position: string;
  created_at: string;
}

// Detects whether the API content is already HTML markup
const HTML_TAG_REGEX = /<\/?[a-z][\s\S]*?>/i;

// Detects HTML-encoded entities like &lt;h1&gt;
const ENCODED_HTML_REGEX = /&lt;\/?[a-z][\s\S]*?&gt;/i;

// Decodes HTML entities (e.g. &lt; → <, &gt; → >, &amp; → &, &quot; → ")
function decodeHtmlEntities(html: string): string {
  if (typeof document === "undefined") {
    // Server-side fallback: manual replacement of common entities
    return html
      .replace(/&lt;/g, "<")
      .replace(/&gt;/g, ">")
      .replace(/&amp;/g, "&")
      .replace(/&quot;/g, '"')
      .replace(/&#039;/g, "'")
      .replace(/&nbsp;/g, " ");
  }
  const textarea = document.createElement("textarea");
  textarea.innerHTML = html;
  return textarea.value;
}

// Lowercase words that are allowed to stay inside a section heading
const HEADING_CONNECTORS = new Set([
  "by",
  "the",
  "of",
  "and",
  "to",
  "for",
  "in",
  "or",
  "with",
  "on",
  "at",
]);

// Renders inline text: linkifies URLs/emails and bolds contact labels
function renderInlineText(text: string, keyPrefix: string): ReactNode[] {
  const pattern =
    /(https?:\/\/[^\s]+|[\w.+-]+@[\w-]+\.[\w.-]+|(?:Email|Website|Phone|Contact|Address):)/g;

  return text
    .split(pattern)
    .map((part, i) => {
      if (!part) return null;
      const key = `${keyPrefix}-${i}`;

      if (/^https?:\/\//.test(part)) {
        const href = part.replace(/[.,);]+$/, "");
        return (
          <a
            key={key}
            href={href}
            target="_blank"
            rel="noopener noreferrer"
            className="text-[#FAA631] hover:underline break-words"
          >
            {href}
          </a>
        );
      }

      if (/^[\w.+-]+@[\w-]+\.[\w.-]+$/.test(part)) {
        return (
          <a
            key={key}
            href={`mailto:${part}`}
            className="text-[#FAA631] hover:underline break-words"
          >
            {part}
          </a>
        );
      }

      if (/^(?:Email|Website|Phone|Contact|Address):$/.test(part)) {
        return (
          <strong key={key} className="font-semibold text-gray-900">
            {part}{" "}
          </strong>
        );
      }

      return <span key={key}>{part}</span>;
    })
    .filter(Boolean) as ReactNode[];
}

// Formats plain-text legal content into bold headings + spaced paragraphs
function formatLegalContent(raw: string): ReactNode[] {
  const text = raw.replace(/\s+/g, " ").trim();

  // Break the text right before each numbered section marker e.g. " 1. Title"
  const segments = text
    .split(/(?=\s\d{1,2}\.\s+[A-Z])/)
    .map((s) => s.trim())
    .filter(Boolean);

  return segments.map((seg, idx) => {
    const match = seg.match(/^(\d{1,2})\.\s+([\s\S]*)$/);

    if (!match) {
      // Intro / non-numbered paragraph
      return (
        <p
          key={`intro-${idx}`}
          className="my-4 leading-relaxed text-justify text-gray-700"
        >
          {renderInlineText(seg, `intro-${idx}`)}
        </p>
      );
    }

    const num = match[1];
    const words = match[2].split(/\s+/);

    // Find where the body begins: first Title-Case word followed by a
    // lowercase word that is not a connector marks the start of a sentence.
    let bodyStart = words.length;
    for (let j = 0; j < words.length - 1; j++) {
      const current = words[j];
      const next = words[j + 1];
      if (
        /^[A-Z]/.test(current) &&
        /^[a-z]/.test(next) &&
        !HEADING_CONNECTORS.has(next.toLowerCase())
      ) {
        bodyStart = j;
        break;
      }
    }

    // Cap heading length so a duplicated word in the body can't bloat it
    const headingCount =
      bodyStart < words.length ? Math.min(bodyStart, 4) : words.length;
    const heading = words.slice(0, headingCount).join(" ");
    const body = words.slice(headingCount).join(" ");

    return (
      <p
        key={`sec-${idx}`}
        className="my-4 leading-relaxed text-justify text-gray-700"
      >
        <strong className="font-bold text-gray-900">
          {num}.{heading ? ` ${heading}` : ""}
        </strong>
        {body ? <> {renderInlineText(body, `sec-${idx}`)}</> : null}
      </p>
    );
  });
}

export default function LegalPage() {
  const lang = getStoredLanguage();
  const t = getTranslation(lang);
  const tl = t.legalPage as any;
  const { language } = useLanguage();

  const [pages, setPages] = useState<LegalPage[]>([]);
  const [loading, setLoading] = useState(true);
  const [activePage, setActivePage] = useState<string | null>(null);
  // Whether to select the last page (set when arriving from a T&C link)
  const selectLastRef = useRef(false);

  // Capture the "select last" flag once on mount (before data loads)
  useEffect(() => {
    if (
      typeof window !== "undefined" &&
      localStorage.getItem("legal_select_last") === "1"
    ) {
      selectLastRef.current = true;
      localStorage.removeItem("legal_select_last");
    }
  }, []);

  useEffect(() => {
    const loadLegalPages = async () => {
      try {
        const langCode = language === "hindi" ? "hi" : "en";
        const response = await getLegalPages(langCode);

        if (response.status && response.data?.pages) {
          const loadedPages = response.data.pages;
          setPages(loadedPages);

          if (loadedPages.length > 0) {
            setActivePage((prev) => {
              // Preserve the current selection across language reloads
              if (prev && loadedPages.some((p: LegalPage) => p.slug === prev)) {
                return prev;
              }
              // If navigated from a "Terms & Conditions" link, select the last page
              if (selectLastRef.current) {
                return loadedPages[loadedPages.length - 1].slug;
              }
              return loadedPages[0].slug;
            });
          }
        } else {
          console.error("Failed to load legal pages:", response.message);
        }
      } catch (error) {
        console.error("Error loading legal pages:", error);
      } finally {
        setLoading(false);
      }
    };

    loadLegalPages();
  }, [language]);

  const getCurrentPage = () => {
    return pages.find((page) => page.slug === activePage);
  };

  const getPageTitle = (page: LegalPage) => {
    return language === "hindi" ? page.title_hindi : page.title_english;
  };

  const getPageContent = (page: LegalPage) => {
    return language === "hindi" ? page.content_hindi : page.content_english;
  };

  return (
    <div>
      <PageHeader title={tl.pageTitle} breadcrumb={tl.breadcrumb} />

      <section className="bg-white pt-10 md:pt-16 pb-16 md:pb-24 border-b border-gray-100">
        <div className="container mx-auto px-4">
          {/* Header Section */}
          <div className="mb-12 lg:mb-16">
            <AnimatedSection>
              <div className="flex items-center gap-3 mb-4">
                <Scale className="w-8 h-8 text-[#FAA631]" />
                <span className="inline-block px-4 py-1.5 bg-[#FFF4E4] text-[#FAA631] rounded-full text-xs md:text-sm font-semibold">
                  {tl.badge}
                </span>
              </div>

              <h1 className="text-3xl md:text-4xl font-bold text-gray-900 leading-tight mb-4">
                {tl.heading}{" "}
                <span className="text-[#FAA631]">{tl.headingHighlight}</span>
              </h1>

              <p className="text-base md:text-lg text-gray-600 mb-4 max-w-2xl">
                {tl.description}
              </p>
            </AnimatedSection>
          </div>

          {loading ? (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="w-8 h-8 text-[#FAA631] animate-spin" />
            </div>
          ) : pages.length === 0 ? (
            <p className="text-gray-500 text-center py-12">
              {tl.noDocuments}
            </p>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
              {/* Sidebar - Navigation */}
              <div className="lg:col-span-1">
                <div className="sticky top-24 space-y-2 bg-gray-50 rounded-xl p-4 md:p-6">
                  {pages.map((page) => {
                    const title = getPageTitle(page);
                    const isActive = activePage === page.slug;

                    return (
                      <button
                        key={page.slug}
                        onClick={() => setActivePage(page.slug)}
                        className={`
                          w-full text-left px-4 py-3 rounded-lg font-medium text-sm transition-all duration-300
                          ${
                            isActive
                              ? "bg-[#FAA631] text-white shadow-md"
                              : "text-gray-700 hover:bg-gray-200"
                          }
                        `}
                      >
                        {title}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Main Content */}
              <div className="lg:col-span-3">
                {getCurrentPage() ? (
                  <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-sm">
                    {/* Content Header */}
                    <div className="bg-gradient-to-r from-[#FAA631]/10 to-orange-50 border-b border-gray-200 px-6 md:px-8 py-6">
                      <h2 className="text-2xl md:text-3xl font-bold text-gray-900 mb-2">
                        {getPageTitle(getCurrentPage()!)}
                      </h2>
                      <p className="text-sm text-gray-600">
                        {tl.lastUpdated} {new Date(getCurrentPage()!.created_at).toLocaleDateString(
                          language === "hindi" ? "hi-IN" : "en-US",
                          { year: "numeric", month: "long", day: "numeric" }
                        )}
                      </p>
                    </div>

                    {/* Content Body */}
                    <div className="px-6 md:px-8 py-8">
                      {(() => {
                        const rawContent = getPageContent(getCurrentPage()!) || "";

                        // Decode HTML entities if the API sent encoded HTML
                        const content = ENCODED_HTML_REGEX.test(rawContent)
                          ? decodeHtmlEntities(rawContent)
                          : rawContent;

                        // If the content is HTML, render it as markup
                        if (HTML_TAG_REGEX.test(content)) {
                          return (
                            <div
                              className="prose prose-sm md:prose-base max-w-none text-gray-700 leading-relaxed
                                prose-headings:font-bold prose-headings:text-gray-900
                                prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg
                                prose-h2:mt-6 prose-h2:mb-3
                                prose-h3:mt-5 prose-h3:mb-2
                                prose-p:my-3 prose-p:text-justify
                                prose-strong:font-bold prose-strong:text-gray-900
                                prose-ol:my-4 prose-ol:ml-6
                                prose-li:my-1 prose-li:text-gray-700
                                prose-a:text-[#FAA631] prose-a:hover:underline
                                prose-em:italic prose-em:text-gray-600"
                              dangerouslySetInnerHTML={{ __html: content }}
                            />
                          );
                        }

                        // Otherwise format plain text with bold headings + spacing
                        return (
                          <div className="text-base text-gray-700">
                            {formatLegalContent(content)}
                          </div>
                        );
                      })()}
                    </div>
                  </div>
                ) : (
                  <div className="flex items-center justify-center py-20 text-gray-500">
                    {tl.selectDocument}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}
