"use client";

import Link from "next/link";
import { ReactNode } from "react";
import {
  TYPE_COLORS,
  TYPE_LABELS,
  getArticleBySlug,
  getRelatedArticles,
} from "@/data/resources-articles";
import { localizedPath } from "@/lib/localized-path";

type Props = {
  slug: string;
  lang: "en" | "ar";
};

const TYPE_ICONS: Record<string, ReactNode> = {
  guide: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  playbook: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2" strokeLinecap="round" strokeLinejoin="round" />
      <rect x="9" y="3" width="6" height="4" rx="1" />
      <path d="M9 12h6M9 16h4" strokeLinecap="round" />
    </svg>
  ),
  comparison: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M16 3h5v5M4 20L21 3M21 16v5h-5M15 15l6 6M4 4l5 5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  template: (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M14 2v6h6M16 13H8M16 17H8M10 9H8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
};

const UI = {
  en: {
    back: "All resources",
    tldr: "TL;DR",
    related: "Related articles",
    readMore: "Read article",
    ctaTitle: "Want help implementing this?",
    ctaSubtitle:
      "Tell us about your channels, team size, and goals. We will map the right SkyLight setup for your business.",
    ctaButton: "Talk to Sales",
    discuss: "Discuss this solution with us",
    byline: "By the SkyLight Chat product team",
    updated: "Last updated July 19, 2026",
    comparisonNote:
      "Editorial note: this comparison is general guidance based on publicly available product information and may change. Verify current features, limits, and pricing with each vendor before deciding.",
  },
  ar: {
    back: "كل الموارد",
    tldr: "الخلاصة السريعة",
    related: "مقالات ذات صلة",
    readMore: "اقرأ المقال",
    ctaTitle: "تحتاج مساعدة في تطبيق هذا؟",
    ctaSubtitle:
      "أخبرنا عن قنواتك وحجم فريقك وأهدافك. سنرسم لك إعداد سكاي لايت المناسب لعملك.",
    ctaButton: "تحدث مع المبيعات",
    discuss: "ناقش هذا الحل معنا",
    byline: "إعداد فريق المنتج في سكاي لايت شات",
    updated: "آخر تحديث: 19 يوليو 2026",
    comparisonNote:
      "ملاحظة تحريرية: هذه المقارنة إرشاد عام مبني على معلومات المنتجات المتاحة علناً وقد تتغير. تحقق من المزايا والقيود والأسعار الحالية مع كل مزود قبل اتخاذ القرار.",
  },
};

function parseTextWithLinks(text: string, langLink: (path: string) => string) {
  const parts: (string | React.ReactNode)[] = [];
  const regex = /\[([^\]]+)\]\(([^)]+)\)/g;
  let lastIndex = 0;
  let match;

  while ((match = regex.exec(text)) !== null) {
    const plainText = text.substring(lastIndex, match.index);
    if (plainText) {
      parts.push(plainText);
    }
    const label = match[1];
    const url = match[2];
    parts.push(
      <Link key={match.index} href={langLink(url)} style={{ color: "#a78bfa", textDecoration: "underline", textUnderlineOffset: "3px" }}>
        {label}
      </Link>
    );
    lastIndex = regex.lastIndex;
  }

  const remainingText = text.substring(lastIndex);
  if (remainingText) {
    parts.push(remainingText);
  }

  return parts.length > 0 ? parts : text;
}

export default function ResourceArticleArea({ slug, lang }: Props) {
  const ui = UI[lang];
  const isRtl = lang === "ar";
  const langLink = (path: string) => localizedPath(path, lang);
  const article = getArticleBySlug(slug, lang);
  const related = getRelatedArticles(slug, lang);

  if (!article) return null;

  const typeColor = TYPE_COLORS[article.type];
  const backChevron = isRtl ? (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="16" height="16" aria-hidden>
      <path d="M5 12h14M12 5l7 7-7 7" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ) : (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="16" height="16" aria-hidden>
      <path d="M19 12H5M12 19l-7-7 7-7" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );

  return (
    <article className={`resource-article-page ${isRtl ? "resource-article-rtl" : ""}`}>
      <div className="container article-container">
        <nav className="article-top-nav" aria-label={ui.back}>
          <Link href={langLink("/resources")} className="back-link">
            {isRtl ? (
              <>
                <span>{ui.back}</span>
                {backChevron}
              </>
            ) : (
              <>
                {backChevron}
                <span>{ui.back}</span>
              </>
            )}
          </Link>
        </nav>

        <header className="article-header" data-aos="fade-up">
          <div className="article-meta">
            <div className="meta-type">
              <span className="meta-type-icon" style={{ background: typeColor }}>
                {TYPE_ICONS[article.type]}
              </span>
              <span className="meta-type-label">{TYPE_LABELS[lang][article.type]}</span>
            </div>
            <span className="meta-separator" aria-hidden>
              ·
            </span>
            <span className="article-read-time">{article.readTime}</span>
          </div>
          <p className="article-byline">
            <span>{ui.byline}</span>
            <span aria-hidden> · </span>
            <time dateTime="2026-07-19">{ui.updated}</time>
          </p>
          <h1>{article.title}</h1>
          <p className="article-lead">{parseTextWithLinks(article.description, langLink)}</p>
        </header>

        <div className="article-content-panel" data-aos="fade-up" data-aos-delay="100">
          <div className="article-body">
            {article.type === "comparison" && (
              <aside className="comparison-note">{ui.comparisonNote}</aside>
            )}
            <section className="article-section article-tldr">
              <h2>{ui.tldr}</h2>
              <p>{parseTextWithLinks(article.tldr ?? article.description, langLink)}</p>
            </section>
            {article.sections.map((section, idx) => (
              <section className="article-section" key={idx}>
                {section.heading && <h2>{section.heading}</h2>}
                {section.text && <p>{parseTextWithLinks(section.text, langLink)}</p>}
                {section.list && (
                  <ul>
                    {section.list.map((item, lIdx) => (
                      <li key={lIdx}>{parseTextWithLinks(item, langLink)}</li>
                    ))}
                  </ul>
                )}
              </section>
            ))}
          </div>

          <div className="article-inline-cta">
            <Link className="azzle-default-btn btn2" href={langLink("/contact-us")} data-text={ui.discuss}>
              <span className="button-wraper">{ui.discuss}</span>
            </Link>
          </div>
        </div>

        {related.length > 0 && (
          <section className="related-section" data-aos="fade-up">
            <h2>{ui.related}</h2>
            <div className="related-grid">
              {related.map((item) => (
                <article className="related-card" key={item.id}>
                  <Link href={langLink(`/resources/${item.id}`)} className="related-card-link">
                    <div className="related-card-meta">
                      <span className="related-type-icon" style={{ background: TYPE_COLORS[item.type] }}>
                        {TYPE_ICONS[item.type]}
                      </span>
                      <span className="related-type">{TYPE_LABELS[lang][item.type]}</span>
                    </div>
                    <h3>{item.title}</h3>
                    <p>{item.description}</p>
                    <span className="related-read">
                      {ui.readMore}
                      <span className="related-arrow" aria-hidden>
                        {isRtl ? "←" : "→"}
                      </span>
                    </span>
                  </Link>
                </article>
              ))}
            </div>
          </section>
        )}

        <section className="article-cta" data-aos="fade-up">
          <h2>{ui.ctaTitle}</h2>
          <p>{ui.ctaSubtitle}</p>
          <Link className="azzle-default-btn btn2" href={langLink("/contact-us")} data-text={ui.ctaButton}>
            <span className="button-wraper">{ui.ctaButton}</span>
          </Link>
        </section>
      </div>

      <style jsx>{`
        .resource-article-page {
          padding: 120px 0 100px;
          background: #000000;
          min-height: 100vh;
          color: #fff;
        }

        .article-container {
          width: 100%;
        }

        .resource-article-rtl {
          direction: rtl;
        }

        .resource-article-rtl .related-read {
          flex-direction: row-reverse;
        }

        .article-top-nav {
          margin-bottom: 28px;
        }

        .back-link {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          color: #94a3b8 !important;
          text-decoration: none;
          font-size: 14px;
          font-weight: 500;
          transition: color 0.2s ease;
        }

        .back-link:hover,
        .back-link:focus-visible {
          color: #e2e8f0 !important;
        }

        .back-link span {
          color: inherit;
        }

        .back-link :global(svg) {
          stroke: currentColor;
          flex-shrink: 0;
        }

        .article-header {
          width: 100%;
          margin-bottom: 40px;
          padding-bottom: 40px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.08);
        }

        .article-meta {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 24px;
          flex-wrap: wrap;
        }

        .meta-type {
          display: inline-flex;
          align-items: center;
          gap: 10px;
          padding: 6px 14px 6px 8px;
          background: rgba(255, 255, 255, 0.04);
          border: 1px solid rgba(255, 255, 255, 0.08);
          border-radius: 999px;
        }

        .meta-type-icon {
          width: 28px;
          height: 28px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 8px;
          color: #fff;
          flex-shrink: 0;
        }

        .meta-type-icon :global(svg) {
          width: 15px;
          height: 15px;
        }

        .meta-type-label {
          font-size: 12px;
          font-weight: 600;
          letter-spacing: 0.4px;
          text-transform: uppercase;
          color: #cbd5e1;
        }

        .meta-separator {
          color: rgba(255, 255, 255, 0.2);
          font-size: 14px;
          line-height: 1;
        }

        .article-read-time {
          font-size: 14px;
          color: #64748b;
        }

        .article-byline {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
          color: #94a3b8;
          font-size: 14px;
          margin: -10px 0 18px;
        }

        .article-header h1 {
          font-size: clamp(28px, 4vw, 44px);
          font-weight: 700;
          color: #fff;
          letter-spacing: -0.5px;
          line-height: 1.25;
          margin: 0 0 20px;
          width: 100%;
        }

        .article-lead {
          font-size: 18px;
          color: #94a3b8;
          line-height: 1.75;
          margin: 0;
          width: 100%;
        }

        .article-content-panel {
          width: 100%;
          background: rgba(255, 255, 255, 0.03);
          border: 1px solid rgba(255, 255, 255, 0.06);
          border-radius: 16px;
          padding: 48px 56px;
          margin-bottom: 72px;
        }

        .article-body {
          width: 100%;
        }

        .comparison-note {
          margin: 0 0 32px;
          padding: 16px 18px;
          color: #cbd5e1;
          background: rgba(245, 158, 11, 0.08);
          border: 1px solid rgba(245, 158, 11, 0.24);
          border-radius: 12px;
          font-size: 14px;
          line-height: 1.7;
        }

        .article-section {
          margin-bottom: 40px;
          padding-bottom: 40px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.06);
        }

        .article-section:last-child {
          margin-bottom: 0;
          padding-bottom: 0;
          border-bottom: none;
        }

        .article-section h2 {
          font-size: 24px;
          font-weight: 600;
          color: #fff;
          margin: 0 0 16px;
          line-height: 1.4;
          width: 100%;
        }

        .article-section p {
          font-size: 17px;
          color: #cbd5e1;
          line-height: 1.8;
          margin: 0 0 16px;
          width: 100%;
        }

        .article-section ul {
          margin: 0;
          padding: 0;
          list-style: none;
          width: 100%;
        }

        .article-section li {
          position: relative;
          font-size: 17px;
          color: #cbd5e1;
          line-height: 1.75;
          margin-bottom: 12px;
          padding-inline-start: 28px;
        }

        .article-section li::before {
          content: "";
          position: absolute;
          top: 0.65em;
          inset-inline-start: 0;
          width: 6px;
          height: 6px;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.35);
        }

        .article-inline-cta {
          width: 100%;
          margin-top: 48px;
          padding-top: 40px;
          border-top: 1px solid rgba(255, 255, 255, 0.08);
        }

        .related-section {
          width: 100%;
          margin-bottom: 80px;
        }

        .related-section h2 {
          font-size: 28px;
          font-weight: 700;
          color: #fff;
          margin-bottom: 28px;
        }

        .related-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
          gap: 24px;
        }

        .related-card {
          padding: 32px;
          background: rgba(255, 255, 255, 0.03);
          border: 1px solid rgba(255, 255, 255, 0.06);
          border-radius: 16px;
          transition: border-color 0.2s ease, background 0.2s ease;
          overflow: hidden;
        }

        .related-card:hover {
          border-color: rgba(255, 255, 255, 0.12);
          background: rgba(255, 255, 255, 0.04);
        }

        .related-card-link {
          display: flex;
          flex-direction: column;
          height: 100%;
          color: inherit;
          text-decoration: none;
        }

        .related-card-link:hover,
        .related-card-link:focus-visible {
          color: inherit;
        }

        .related-card-meta {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 14px;
        }

        .related-type-icon {
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 8px;
          color: #fff;
          flex-shrink: 0;
        }

        .related-type-icon :global(svg) {
          width: 16px;
          height: 16px;
        }

        .related-type {
          font-size: 12px;
          font-weight: 600;
          text-transform: uppercase;
          letter-spacing: 0.5px;
          color: #94a3b8;
        }

        .related-card h3 {
          font-size: 18px;
          font-weight: 600;
          color: #fff;
          margin: 0 0 12px;
          line-height: 1.45;
          text-align: start;
          word-break: break-word;
        }

        .related-card p {
          font-size: 14px;
          color: #94a3b8;
          line-height: 1.7;
          margin: 0 0 20px;
          flex-grow: 1;
          text-align: start;
          word-break: break-word;
        }

        .related-read {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          font-size: 14px;
          font-weight: 600;
          color: #e2e8f0;
          margin-top: auto;
          padding-top: 4px;
        }

        .related-arrow {
          color: #94a3b8;
          transition: transform 0.2s ease;
        }

        .related-card:hover .related-read {
          color: #fff;
        }

        .related-card:hover .related-arrow {
          color: #fff;
          transform: translateX(2px);
        }

        .resource-article-rtl .related-card:hover .related-arrow {
          transform: translateX(-2px);
        }

        .article-cta {
          width: 100%;
          text-align: center;
          padding: 64px 48px;
          background: rgba(255, 255, 255, 0.03);
          border: 1px solid rgba(255, 255, 255, 0.06);
          border-radius: 16px;
        }

        .article-cta h2 {
          font-size: 32px;
          font-weight: 700;
          color: #fff;
          margin-bottom: 16px;
        }

        .article-cta p {
          font-size: 16px;
          color: #94a3b8;
          max-width: 640px;
          margin: 0 auto 28px;
          line-height: 1.7;
        }

        @media (max-width: 991px) {
          .article-content-panel {
            padding: 36px 32px;
          }
        }

        @media (max-width: 768px) {
          .resource-article-page {
            padding: 100px 0 80px;
          }

          .article-content-panel {
            padding: 28px 20px;
          }

          .article-section h2 {
            font-size: 20px;
          }

          .article-section p,
          .article-section li {
            font-size: 16px;
          }

          .article-cta {
            padding: 48px 24px;
          }

          .article-cta h2 {
            font-size: 26px;
          }

          .related-card {
            padding: 24px 20px;
          }
        }
      `}</style>
    </article>
  );
}
