"use client";

import {
  ChangeEvent,
  FormEvent,
  useEffect,
  useState,
} from "react";
import Link from "next/link";

import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";

export default function CreateArticlePage() {
  const [title, setTitle] = useState("");
  const [slug, setSlug] = useState("");
  const [excerpt, setExcerpt] = useState("");
  const [content, setContent] = useState("");
  const [category, setCategory] = useState("");

  const [published, setPublished] = useState(false);

  const getCurrentDate = () => {
    const now = new Date();
    const offset = now.getTimezoneOffset();

    const localDate = new Date(
      now.getTime() - offset * 60 * 1000
    );

    return localDate.toISOString().split("T")[0];
  };

  const [publishedAt, setPublishedAt] =
    useState(getCurrentDate());

  const [images, setImages] = useState<File[]>([]);
  const [previews, setPreviews] = useState<string[]>([]);

const [uploading, setUploading] = useState(false);
const [saving, setSaving] = useState(false);

const [articleAccess, setArticleAccess] = useState<boolean | null>(null);
const [checkingAccess, setCheckingAccess] = useState(true);

const [showAlertModal, setShowAlertModal] = useState(false);

const [alertType, setAlertType] = useState<
  "success" | "error" | "warning" | "info"
>("info");

const [alertTitle, setAlertTitle] = useState("");
const [alertMessage, setAlertMessage] = useState("");

const showAlert = (
  type: "success" | "error" | "warning" | "info",
  title: string,
  message: string
) => {
  setAlertType(type);
  setAlertTitle(title);
  setAlertMessage(message);
  setShowAlertModal(true);
};

const closeAlert = () => {
  setShowAlertModal(false);
};

useEffect(() => {
  const checkArticleAccess = async () => {
    try {
      const response = await fetch(
  "/api/user/articles/article-access-check",
  {
    method: "GET",
    cache: "no-store",
  }
);

      const result = await response.json();

      if (!response.ok || !result.success) {
  showAlert(
    "warning",
    "Article Access",
    result.message ||
      "Unable to verify your Article access."
  );

  return;
}

      setArticleAccess(
        result.data?.articleAccess === true
      );
    } catch (error) {
      console.error(
        "CHECK ARTICLE ACCESS ERROR:",
        error
      );

      showAlert(
        "error",
        "Connection Error",
        "Unable to verify your Article access."
      );
    } finally {
      setCheckingAccess(false);
    }
  };

  checkArticleAccess();
}, []);

  const generateSlug = (value: string) => {
    return value
      .toLowerCase()
      .trim()
      .replace(/[^a-z0-9\s-]/g, "")
      .replace(/\s+/g, "-")
      .replace(/-+/g, "-");
  };

  const handleTitleChange = (value: string) => {
    setTitle(value);

    if (!slug) {
      setSlug(generateSlug(value));
    }
  };

 const handleImagesChange = (
  event: ChangeEvent<HTMLInputElement>
) => {
  if (checkingAccess || articleAccess !== true) {
    event.target.value = "";

    showAlert(
      "warning",
      "Article Access Disabled",
      "Your access to add Articles has been disabled by the Admin."
    );

    return;
  }

  const selectedFiles = Array.from(
    event.target.files || []
  );

  if (selectedFiles.length === 0) {
    return;
  }

  const imageFiles = selectedFiles.filter((file) =>
    file.type.startsWith("image/")
  );

  if (imageFiles.length === 0) {
    showAlert(
      "warning",
      "Invalid File",
      "The selected files are not images."
    );

    event.target.value = "";
    return;
  }

  setImages((previous) => [
    ...previous,
    ...imageFiles,
  ]);

  const newPreviews = imageFiles.map((file) =>
    URL.createObjectURL(file)
  );

  setPreviews((previous) => [
    ...previous,
    ...newPreviews,
  ]);

  event.target.value = "";
};
  const removeImage = (index: number) => {
  if (checkingAccess || articleAccess !== true) {
  return;
}

  const preview = previews[index];

    if (preview) {
      URL.revokeObjectURL(preview);
    }

    setImages((previous) =>
      previous.filter(
        (_, imageIndex) => imageIndex !== index
      )
    );

    setPreviews((previous) =>
      previous.filter(
        (_, imageIndex) => imageIndex !== index
      )
    );
  };

  const uploadImages = async () => {
  if (checkingAccess || articleAccess !== true) {
  throw new Error(
    "Your access to add Articles has been disabled by the Admin."
  );
}

  if (images.length === 0) {
    return [];
  }

    const formData = new FormData();

    images.forEach((file) => {
  formData.append("images", file);
});

    setUploading(true);

    try {
      const response = await fetch(
        "/api/user/articles/upload",
        {
          method: "POST",
          body: formData,
        }
      );

      const result = await response.json();

      if (!response.ok || !result.success) {
        throw new Error(
          result.message ||
            "Failed to upload images"
        );
      }

      return result.data as string[];
    } finally {
      setUploading(false);
    }
  };

  const handleSubmit = async (
    event: FormEvent<HTMLFormElement>
  ) => {
    event.preventDefault();

    if (checkingAccess) {
  return;
}

if (articleAccess !== true) {
  showAlert(
    "warning",
    "Article Access Disabled",
    "Your access to add Articles has been disabled by the Admin."
  );

  return;
}

    if (!title.trim()) {
      showAlert(
  "warning",
  "Article Title Required",
  "Please enter an article title before continuing."
);
      return;
    }

    if (!slug.trim()) {
      showAlert(
  "warning",
  "Article Slug Required",
  "Please enter an article slug before continuing."
);
      return;
    }

    if (!content.trim()) {
      showAlert(
  "warning",
  "Article Content Required",
  "Please enter the article content before continuing."
);
      return;
    }

    if (!publishedAt) {
      showAlert(
  "warning",
  "Publish Date Required",
  "Please select a publish date before continuing."
);
      return;
    }

    setSaving(true);

    try {
      const uploadedImages = await uploadImages();

      const publishDate = publishedAt
        ? new Date(
            `${publishedAt}T00:00:00`
          ).toISOString()
        : null;

      const response = await fetch(
        "/api/user/articles",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            title: title.trim(),
            slug: slug.trim(),
            excerpt:
              excerpt.trim() || null,
            content: content.trim(),
            category:
              category.trim() || null,
            published,
            publishedAt: publishDate,
            images: uploadedImages,
          }),
        }
      );

      const result = await response.json();

      if (!response.ok || !result.success) {
        throw new Error(
          result.message ||
            "Failed to save article"
        );
      }

     showAlert(
  "success",
  published
    ? "Article Published Successfully"
    : "Article Saved Successfully",
  published
    ? "Your article has been added and published successfully."
    : "Your article has been added as a draft successfully."
);
    } catch (error) {
      console.error(
        "CREATE USER ARTICLE ERROR:",
        error
      );

      showAlert(
  "error",
  "Failed to Create Article",
  error instanceof Error
    ? error.message
    : "Failed to create article."
);
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <Navbar />

      <style>{`
        .create-article-page {
          position: relative;
          min-height: 100vh;
          overflow: hidden;
          background:
            radial-gradient(
              circle at 8% 12%,
              rgba(25, 135, 84, 0.055),
              transparent 26%
            ),
            radial-gradient(
              circle at 92% 78%,
              rgba(25, 135, 84, 0.045),
              transparent 25%
            ),
            #f8faf9;
          padding: 110px 20px 70px;
        }

        .create-article-page::before,
        .create-article-page::after {
          content: "";
          position: absolute;
          pointer-events: none;
          border-radius: 50%;
          filter: blur(1px);
        }

        .create-article-page::before {
          width: 280px;
          height: 280px;
          top: 150px;
          left: -170px;
          border: 1px solid rgba(25, 135, 84, 0.08);
          animation: ambientFloatOne 8s ease-in-out infinite;
        }

        .create-article-page::after {
          width: 220px;
          height: 220px;
          right: -130px;
          bottom: 180px;
          border: 1px solid rgba(25, 135, 84, 0.07);
          animation: ambientFloatTwo 10s ease-in-out infinite;
        }

        .create-article-container {
          position: relative;
          z-index: 2;
          max-width: 1120px;
          margin: 0 auto;
        }

        .page-header {
          margin-bottom: 28px;
          animation: headerReveal 0.7s ease both;
        }

        .back-link {
          display: inline-flex;
          align-items: center;
          gap: 7px;
          color: #667085;
          text-decoration: none;
          font-size: 13px;
          font-weight: 600;
          margin-bottom: 20px;
          transition: 0.25s ease;
        }

        .back-link:hover {
          color: #198754;
          transform: translateX(-3px);
        }

        .page-eyebrow {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          color: #198754;
          font-size: 11px;
          font-weight: 800;
          letter-spacing: 1.5px;
          margin-bottom: 8px;
        }

        .page-eyebrow::before {
          content: "";
          width: 25px;
          height: 2px;
          border-radius: 99px;
          background: #198754;
          animation: eyebrowLine 2.5s ease-in-out infinite;
        }

        .page-title {
          margin: 0;
          color: #101828;
          font-size: clamp(28px, 4vw, 40px);
          line-height: 1.15;
          font-weight: 800;
          letter-spacing: -0.8px;
        }

        .page-description {
          margin: 9px 0 0;
          max-width: 720px;
          color: #667085;
          font-size: 14px;
          line-height: 1.75;
        }

        .form-card {
          position: relative;
          overflow: hidden;
          background: #ffffff;
          border: 1px solid #e4e9e6;
          border-radius: 18px;
          box-shadow:
            0 10px 30px rgba(16, 24, 40, 0.055),
            0 2px 8px rgba(25, 135, 84, 0.025);
          animation:
            cardReveal 0.8s ease 0.08s both,
            cardBreathing 6s ease-in-out 1s infinite;
        }

        /*
         * Continuous animated green line
         * across the top of the main card.
         */
        .form-card::before {
          content: "";
          position: absolute;
          top: 0;
          left: -100%;
          width: 100%;
          height: 4px;
          background:
            linear-gradient(
              90deg,
              #198754,
              #73c69a,
              #198754,
              #4aa977,
              #198754
            );
          animation: greenLineLoop 4s linear infinite;
          z-index: 10;
        }

        .form-card::after {
          content: "";
          position: absolute;
          top: 0;
          left: -30%;
          width: 30%;
          height: 4px;
          background:
            linear-gradient(
              90deg,
              transparent,
              rgba(255, 255, 255, 0.95),
              transparent
            );
          animation: greenLineHighlight 4s linear infinite;
          z-index: 11;
          pointer-events: none;
        }

        .form-card-header {
          position: relative;
          padding: 25px 28px 22px;
          border-bottom: 1px solid #eaecf0;
          background:
            linear-gradient(
              135deg,
              #ffffff 0%,
              #fbfdfc 100%
            );
        }

        .form-card-header::after {
          content: "";
          position: absolute;
          left: 28px;
          bottom: -1px;
          width: 75px;
          height: 2px;
          background: #198754;
          border-radius: 99px;
          animation: headerAccent 3s ease-in-out infinite;
        }

        .form-card-title {
          margin: 0;
          color: #101828;
          font-size: 19px;
          font-weight: 750;
        }

        .form-card-description {
          margin: 7px 0 0;
          color: #667085;
          font-size: 12px;
          line-height: 1.7;
        }

        .form-card-body {
          padding: 28px;
        }

        .form-section {
          position: relative;
          background:
            linear-gradient(
              145deg,
              #fbfcfd 0%,
              #ffffff 100%
            );
          border: 1px solid #e6ebe8;
          border-radius: 14px;
          padding: 21px;
          transition:
            border-color 0.3s ease,
            box-shadow 0.3s ease,
            transform 0.3s ease;
          animation: sectionReveal 0.7s ease both;
        }

        .form-section:hover {
          border-color: #cfe4d8;
          box-shadow:
            0 8px 22px rgba(16, 24, 40, 0.045);
        }

        .form-section-title {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 19px;
          color: #344054;
          font-size: 13px;
          font-weight: 750;
        }

        .form-section-title i {
          width: 34px;
          height: 34px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 9px;
          color: #198754;
          background: #eaf7f0;
          font-size: 15px;
          animation: iconFloat 3.5s ease-in-out infinite;
        }

        .form-label-custom {
          display: block;
          margin-bottom: 7px;
          color: #344054;
          font-size: 12px;
          font-weight: 700;
        }

        .form-control-custom {
          width: 100%;
          min-height: 44px;
          padding: 10px 13px;
          border: 1px solid #d0d5dd;
          border-radius: 9px;
          background: #ffffff;
          color: #101828;
          font-size: 13px;
          outline: none;
          transition:
            border-color 0.25s ease,
            box-shadow 0.25s ease,
            transform 0.25s ease;
        }

        .form-control-custom:hover {
          border-color: #b8c4be;
        }

        .form-control-custom:focus {
          border-color: #198754;
          box-shadow:
            0 0 0 3px rgba(25, 135, 84, 0.1),
            0 4px 12px rgba(25, 135, 84, 0.04);
        }

        textarea.form-control-custom {
          resize: vertical;
          line-height: 1.75;
        }

        .form-help {
          margin-top: 7px;
          color: #98a2b3;
          font-size: 10px;
          line-height: 1.65;
        }

        .slug-preview {
          display: flex;
          align-items: center;
          margin-top: 8px;
          padding: 8px 10px;
          border-radius: 8px;
          border: 1px solid #e4ebe7;
          background: #f5f9f7;
          color: #667085;
          font-size: 10px;
          word-break: break-all;
          animation: previewAppear 0.35s ease both;
        }

        .slug-preview i {
          color: #198754;
        }

        .upload-box {
          position: relative;
          padding: 20px;
          border: 1px dashed #bdd0c5;
          border-radius: 12px;
          background:
            linear-gradient(
              145deg,
              #ffffff,
              #f9fcfa
            );
          transition:
            border-color 0.25s ease,
            background 0.25s ease,
            box-shadow 0.25s ease;
        }

        .upload-box:hover {
          border-color: #198754;
          background: #fbfefc;
          box-shadow:
            0 6px 18px rgba(25, 135, 84, 0.055);
        }

        .upload-input {
          width: 100%;
          min-height: 44px;
          padding: 8px 10px;
          border: 1px solid #d0d5dd;
          border-radius: 9px;
          background: #ffffff;
          color: #475467;
          font-size: 12px;
          cursor: pointer;
        }

        .upload-input:focus {
          outline: none;
          border-color: #198754;
          box-shadow:
            0 0 0 3px rgba(25, 135, 84, 0.1);
        }

        .preview-grid {
          display: grid;
          grid-template-columns:
            repeat(4, minmax(0, 1fr));
          gap: 14px;
        }

        .preview-item {
          position: relative;
          overflow: hidden;
          border-radius: 12px;
          background: #f2f4f7;
          border: 1px solid #e3e8e5;
          box-shadow:
            0 5px 15px rgba(16, 24, 40, 0.045);
          animation:
            previewItemReveal 0.55s ease both,
            previewItemFloat 5s ease-in-out
              0.6s infinite;
          transition:
            transform 0.3s ease,
            box-shadow 0.3s ease;
        }

        .preview-item:hover {
          transform: translateY(-4px);
          box-shadow:
            0 12px 25px rgba(16, 24, 40, 0.09);
        }

        .preview-image {
          width: 100%;
          height: 175px;
          object-fit: cover;
          display: block;
          transition: transform 0.55s ease;
        }

        .preview-item:hover .preview-image {
          transform: scale(1.035);
        }

        .thumbnail-badge {
          position: absolute;
          top: 9px;
          left: 9px;
          padding: 5px 9px;
          border-radius: 6px;
          background: rgba(25, 135, 84, 0.94);
          color: #ffffff;
          font-size: 9px;
          font-weight: 700;
          box-shadow:
            0 4px 10px rgba(25, 135, 84, 0.2);
          animation: badgePulse 2.8s ease-in-out infinite;
        }

        .remove-image {
          position: absolute;
          top: 8px;
          right: 8px;
          width: 32px;
          height: 32px;
          border: 1px solid rgba(255, 255, 255, 0.25);
          border-radius: 50%;
          background: rgba(220, 53, 69, 0.94);
          color: #ffffff;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition:
            transform 0.25s ease,
            background 0.25s ease;
        }

        .remove-image:hover {
          background: #bb2d3b;
          transform: rotate(90deg) scale(1.06);
        }

        .publish-date-box,
        .publish-box {
          height: 100%;
          padding: 18px;
          border: 1px solid #e1e7e4;
          border-radius: 12px;
          background: #ffffff;
          transition:
            border-color 0.25s ease,
            box-shadow 0.25s ease,
            transform 0.25s ease;
        }

        .publish-date-box:hover,
        .publish-box:hover {
          border-color: #cfe4d8;
          box-shadow:
            0 7px 20px rgba(16, 24, 40, 0.045);
          transform: translateY(-2px);
        }

        .publish-date-header {
          display: flex;
          align-items: center;
          gap: 9px;
          margin-bottom: 12px;
        }

        .publish-date-header i {
          color: #198754;
          animation: iconFloat 3s ease-in-out infinite;
        }

        .publish-date-title {
          color: #344054;
          font-size: 12px;
          font-weight: 700;
        }

        .publish-date-input {
          width: 100%;
          min-height: 44px;
          padding: 9px 12px;
          border: 1px solid #d0d5dd;
          border-radius: 9px;
          background: #ffffff;
          color: #101828;
          font-size: 12px;
          outline: none;
          transition:
            border-color 0.25s ease,
            box-shadow 0.25s ease;
        }

        .publish-date-input:focus {
          border-color: #198754;
          box-shadow:
            0 0 0 3px rgba(25, 135, 84, 0.1);
        }

        .publish-info {
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .publish-icon {
          width: 42px;
          height: 42px;
          border-radius: 11px;
          background: #e9f7ef;
          color: #198754;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
          animation:
            publishIconFloat 3.2s ease-in-out infinite;
        }

        .publish-title {
          color: #344054;
          font-size: 12px;
          font-weight: 700;
          margin-bottom: 3px;
        }

        .publish-description {
          color: #98a2b3;
          font-size: 10px;
          line-height: 1.55;
        }

        .switch-custom {
          display: flex;
          justify-content: flex-end;
          flex-shrink: 0;
        }

        .switch-custom .form-check-input {
          width: 44px;
          height: 23px;
          margin: 0;
          cursor: pointer;
          box-shadow: none;
        }

        .switch-custom .form-check-input:checked {
          background-color: #198754;
          border-color: #198754;
        }

        .switch-custom .form-check-input:focus {
          box-shadow:
            0 0 0 3px rgba(25, 135, 84, 0.1);
        }

        .form-actions {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 15px;
          padding-top: 3px;
        }

        .cancel-button,
        .save-button {
          min-height: 44px;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          padding: 10px 17px;
          border-radius: 9px;
          text-decoration: none;
          font-size: 12px;
          font-weight: 650;
          transition:
            transform 0.25s ease,
            box-shadow 0.25s ease,
            background 0.25s ease;
          cursor: pointer;
        }

        .cancel-button {
          color: #667085;
          background: #ffffff;
          border: 1px solid #d0d5dd;
        }

        .cancel-button:hover {
          color: #344054;
          background: #f9fafb;
          transform: translateX(-2px);
        }

        .save-button {
          position: relative;
          overflow: hidden;
          color: #ffffff;
          background: #198754;
          border: 1px solid #198754;
          box-shadow:
            0 7px 18px rgba(25, 135, 84, 0.17);
        }

        .save-button::before {
          content: "";
          position: absolute;
          top: 0;
          left: -120%;
          width: 70%;
          height: 100%;
          background:
            linear-gradient(
              90deg,
              transparent,
              rgba(255, 255, 255, 0.22),
              transparent
            );
          transform: skewX(-18deg);
          animation: buttonShine 3.2s ease-in-out infinite;
        }

        .save-button:hover:not(:disabled) {
          background: #157347;
          border-color: #157347;
          transform: translateY(-2px);
          box-shadow:
            0 10px 24px rgba(25, 135, 84, 0.23);
        }

        .save-button:active:not(:disabled) {
          transform: translateY(0);
        }

        .save-button:disabled {
          opacity: 0.7;
          cursor: not-allowed;
        }

        .save-button i,
        .save-button span {
          position: relative;
          z-index: 2;
        }

        .spinner-border {
          position: relative;
          z-index: 2;
        }

        @keyframes greenLineLoop {
          0% {
            left: -100%;
          }

          100% {
            left: 100%;
          }
        }

        @keyframes greenLineHighlight {
          0% {
            left: -30%;
            opacity: 0;
          }

          12% {
            opacity: 1;
          }

          55% {
            opacity: 1;
          }

          100% {
            left: 100%;
            opacity: 0;
          }
        }

        @keyframes headerReveal {
          from {
            opacity: 0;
            transform: translateY(14px);
          }

          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        @keyframes cardReveal {
          from {
            opacity: 0;
            transform: translateY(20px) scale(0.99);
          }

          to {
            opacity: 1;
            transform: translateY(0) scale(1);
          }
        }

        @keyframes cardBreathing {
          0%,
          100% {
            box-shadow:
              0 10px 30px rgba(16, 24, 40, 0.055),
              0 2px 8px rgba(25, 135, 84, 0.025);
          }

          50% {
            box-shadow:
              0 13px 34px rgba(16, 24, 40, 0.075),
              0 4px 12px rgba(25, 135, 84, 0.045);
          }
        }

        @keyframes sectionReveal {
          from {
            opacity: 0;
            transform: translateY(10px);
          }

          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        @keyframes iconFloat {
          0%,
          100% {
            transform: translateY(0);
          }

          50% {
            transform: translateY(-3px);
          }
        }

        @keyframes publishIconFloat {
          0%,
          100% {
            transform: translateY(0) rotate(0deg);
          }

          50% {
            transform: translateY(-3px) rotate(2deg);
          }
        }

        @keyframes previewAppear {
          from {
            opacity: 0;
            transform: translateY(5px);
          }

          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        @keyframes previewItemReveal {
          from {
            opacity: 0;
            transform: translateY(12px) scale(0.98);
          }

          to {
            opacity: 1;
            transform: translateY(0) scale(1);
          }
        }

        @keyframes previewItemFloat {
          0%,
          100% {
            transform: translateY(0);
          }

          50% {
            transform: translateY(-3px);
          }
        }

        @keyframes badgePulse {
          0%,
          100% {
            box-shadow:
              0 4px 10px rgba(25, 135, 84, 0.18);
          }

          50% {
            box-shadow:
              0 5px 15px rgba(25, 135, 84, 0.32);
          }
        }

        @keyframes publishIconGlow {
          0%,
          100% {
            box-shadow:
              0 0 0 rgba(25, 135, 84, 0);
          }

          50% {
            box-shadow:
              0 0 0 6px rgba(25, 135, 84, 0.055);
          }
        }

        @keyframes eyebrowLine {
          0%,
          100% {
            width: 25px;
          }

          50% {
            width: 38px;
          }
        }

        @keyframes headerAccent {
          0%,
          100% {
            width: 55px;
            opacity: 0.75;
          }

          50% {
            width: 100px;
            opacity: 1;
          }
        }

        @keyframes buttonShine {
          0% {
            left: -120%;
          }

          45%,
          100% {
            left: 140%;
          }
        }

        @keyframes ambientFloatOne {
          0%,
          100% {
            transform: translateY(0) rotate(0deg);
          }

          50% {
            transform: translateY(-22px) rotate(8deg);
          }
        }

        @keyframes ambientFloatTwo {
          0%,
          100% {
            transform: translateY(0) rotate(0deg);
          }

          50% {
            transform: translateY(18px) rotate(-7deg);
          }
        }

        @media (max-width: 991.98px) {
          .create-article-page {
            padding: 100px 20px 55px;
          }

          .form-card-body {
            padding: 23px;
          }

          .preview-grid {
            grid-template-columns:
              repeat(3, minmax(0, 1fr));
          }
        }

        @media (max-width: 767.98px) {
          .create-article-page {
            padding: 92px 16px 45px;
          }

          .form-card {
            border-radius: 15px;
          }

          .form-card-header {
            padding: 21px 20px;
          }

          .form-card-body {
            padding: 18px;
          }

          .form-section {
            padding: 17px;
          }

          .preview-grid {
            grid-template-columns:
              repeat(2, minmax(0, 1fr));
          }

          .preview-image {
            height: 155px;
          }
        }

        @media (max-width: 575.98px) {
          .create-article-page {
            padding: 88px 12px 38px;
          }

          .page-header {
            margin-bottom: 22px;
          }

          .back-link {
            margin-bottom: 15px;
          }

          .page-title {
            font-size: 28px;
          }

          .page-description {
            font-size: 13px;
          }

          .form-card-header {
            padding: 19px 16px;
          }

          .form-card-body {
            padding: 13px;
          }

          .form-section {
            padding: 15px;
            border-radius: 12px;
          }

          .form-section-title {
            margin-bottom: 16px;
          }

          .form-section-title i {
            width: 31px;
            height: 31px;
            font-size: 14px;
          }

          .preview-grid {
            gap: 9px;
          }

          .preview-image {
            height: 135px;
          }

          .thumbnail-badge {
            top: 7px;
            left: 7px;
            padding: 4px 7px;
            font-size: 8px;
          }

          .remove-image {
            top: 6px;
            right: 6px;
            width: 30px;
            height: 30px;
          }

          .publish-date-box,
          .publish-box {
            padding: 15px;
          }

          .publish-info {
            gap: 10px;
          }

          .publish-icon {
            width: 39px;
            height: 39px;
          }

          .form-actions {
            flex-direction: column-reverse;
            align-items: stretch;
          }

          .cancel-button,
          .save-button {
            width: 100%;
          }

          .create-article-page::before,
          .create-article-page::after {
            display: none;
          }
        }

        @media (prefers-reduced-motion: reduce) {
          .create-article-page::before,
          .create-article-page::after,
          .page-header,
          .form-card,
          .form-card::before,
          .form-card::after,
          .page-eyebrow::before,
          .form-section,
          .form-section-title i,
          .publish-date-header i,
          .publish-icon,
          .preview-item,
          .thumbnail-badge,
          .save-button::before {
            animation: none !important;
          }

          .back-link,
          .form-section,
          .preview-item,
          .publish-date-box,
          .publish-box,
          .save-button {
            transition: none !important;
          }
        }

      .article-alert-overlay {
  position: fixed;
  inset: 0;
  z-index: 99999;

  display: flex;
  align-items: center;
  justify-content: center;

  padding: 20px;

  background: rgba(15, 23, 42, 0.52);
  backdrop-filter: blur(6px);
  -webkit-backdrop-filter: blur(6px);

  animation: articleAlertOverlayShow 0.25s ease both;
}

.article-alert-modal {
  position: relative;

  width: min(90%, 420px);

  padding: 32px 26px 27px;

  background: #ffffff;

  border: 1px solid #e7ece9;
  border-radius: 20px;

  text-align: center;

  box-shadow:
    0 25px 70px rgba(16, 24, 40, 0.18),
    0 10px 30px rgba(16, 24, 40, 0.08);

  overflow: hidden;

  animation: articleAlertModalShow 0.38s
    cubic-bezier(0.34, 1.25, 0.64, 1) both;
}

/* Garis hijau kecil di bagian atas card */
.article-alert-modal::before {
  content: "";

  position: absolute;

  top: 0;
  left: 0;

  width: 100%;
  height: 3px;

  background:
    linear-gradient(
      90deg,
      #198754,
      #73c69a,
      #4aa977,
      #198754
    );
}

/* ICON CONTAINER */
.article-alert-icon {
  width: 76px;
  height: 76px;

  margin: 2px auto 19px;

  display: flex;
  align-items: center;
  justify-content: center;

  border-radius: 50%;

  flex-shrink: 0;

  animation:
    articleAlertIconShow 0.55s
    cubic-bezier(0.34, 1.56, 0.64, 1)
    0.08s both;
}

/* SUCCESS */
.article-alert-icon.success {
  color: #198754;
  background: #eaf7f0;

  border: 1px solid #cfe9da;

  box-shadow:
    0 0 0 7px rgba(25, 135, 84, 0.045),
    0 8px 22px rgba(25, 135, 84, 0.12);
}

/* ERROR */
.article-alert-icon.error {
  color: #dc3545;
  background: #fcebec;

  border: 1px solid #f3c8cd;

  box-shadow:
    0 0 0 7px rgba(220, 53, 69, 0.045),
    0 8px 22px rgba(220, 53, 69, 0.10);
}

/* WARNING */
.article-alert-icon.warning {
  color: #856404;
  background: #fff3cd;

  border: 1px solid #ffe69c;

  box-shadow:
    0 0 0 7px rgba(255, 193, 7, 0.045),
    0 8px 22px rgba(255, 193, 7, 0.10);
}

/* INFO */
.article-alert-icon.info {
  color: #0d6efd;
  background: #e7f1ff;

  border: 1px solid #cfe2ff;

  box-shadow:
    0 0 0 7px rgba(13, 110, 253, 0.045),
    0 8px 22px rgba(13, 110, 253, 0.10);
}

/* SVG CHECKMARK */
.article-alert-check {
  width: 42px;
  height: 42px;

  display: block;

  overflow: visible;
}

.article-alert-check-circle {
  fill: none;

  stroke: currentColor;
  stroke-width: 3;

  stroke-linecap: round;
  stroke-linejoin: round;

  stroke-dasharray: 160;
  stroke-dashoffset: 160;

  animation:
    articleAlertCircleDraw 0.55s
    ease-out
    0.25s forwards;
}

.article-alert-check-mark {
  fill: none;

  stroke: currentColor;
  stroke-width: 4;

  stroke-linecap: round;
  stroke-linejoin: round;

  stroke-dasharray: 45;
  stroke-dashoffset: 45;

  animation:
    articleAlertCheckDraw 0.35s
    ease-out
    0.48s forwards;
}

/* Bootstrap icon untuk error/warning/info */
.article-alert-icon i {
  display: block;

  font-size: 2.25rem;
  line-height: 1;

  animation:
    articleAlertInnerIconShow 0.4s
    cubic-bezier(0.34, 1.56, 0.64, 1)
    0.18s both;
}

/* TITLE */
.article-alert-title {
  position: relative;

  margin: 0 0 8px;

  color: #101828;

  font-size: 19px;
  line-height: 1.35;

  font-weight: 750;
}

/* MESSAGE */
.article-alert-message {
  position: relative;

  margin: 0 auto 22px;

  max-width: 340px;

  color: #667085;

  font-size: 13px;
  line-height: 1.7;
}

/* BUTTON */
.article-alert-button {
  min-width: 105px;

  padding: 10px 21px;

  border: 1px solid #198754;
  border-radius: 9px;

  color: #ffffff;
  background: #198754;

  font-size: 13px;
  font-weight: 650;

  cursor: pointer;

  transition:
    background 0.25s ease,
    transform 0.25s ease,
    box-shadow 0.25s ease;
}

.article-alert-button:hover {
  background: #157347;
  border-color: #157347;

  transform: translateY(-2px);

  box-shadow:
    0 8px 20px rgba(25, 135, 84, 0.20);
}

.article-alert-button:active {
  transform: translateY(0);
}

/* ANIMATIONS */

@keyframes articleAlertOverlayShow {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes articleAlertModalShow {
  from {
    opacity: 0;
    transform: translateY(18px) scale(0.94);
  }

  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes articleAlertIconShow {
  from {
    opacity: 0;
    transform: scale(0.35) rotate(-12deg);
  }

  to {
    opacity: 1;
    transform: scale(1) rotate(0);
  }
}

@keyframes articleAlertInnerIconShow {
  from {
    opacity: 0;
    transform: scale(0.2);
  }

  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes articleAlertCircleDraw {
  to {
    stroke-dashoffset: 0;
  }
}

@keyframes articleAlertCheckDraw {
  to {
    stroke-dashoffset: 0;
  }
}

/* MOBILE */
@media (max-width: 575.98px) {
  .article-alert-overlay {
    padding: 16px;
  }

  .article-alert-modal {
    width: min(100%, 380px);

    padding: 29px 20px 23px;

    border-radius: 17px;
  }

  .article-alert-icon {
    width: 70px;
    height: 70px;

    margin-bottom: 17px;
  }

  .article-alert-check {
    width: 39px;
    height: 39px;
  }

  .article-alert-icon i {
    font-size: 2.05rem;
  }

  .article-alert-title {
    font-size: 17px;
  }

  .article-alert-message {
    max-width: 310px;

    font-size: 12px;
    line-height: 1.65;
  }

  .article-alert-button {
    width: 100%;
  }
}

@media (prefers-reduced-motion: reduce) {
  .article-alert-overlay,
  .article-alert-modal,
  .article-alert-icon,
  .article-alert-icon i,
  .article-alert-check-circle,
  .article-alert-check-mark {
    animation: none !important;
  }

  .article-alert-check-circle,
  .article-alert-check-mark {
    stroke-dashoffset: 0;
  }
}
      `}</style>

      <main className="create-article-page">
        <div className="create-article-container">

          <section className="page-header">

            <div className="page-eyebrow">
              ARTICLE MANAGEMENT
            </div>

            <h1 className="page-title">
              Create New Article
            </h1>

            <p className="page-description">
              Create and publish a new article to
              share knowledge, insights, tutorials,
              and experiences through GloVaTech.
            </p>
          </section>

          <section className="form-card">

            <div className="form-card-header">
              <h2 className="form-card-title">
                Article Information
              </h2>

              <p className="form-card-description">
                Complete the article details, content,
                category, images, publication date,
                and publication status.
              </p>
            </div>

            <div className="form-card-body">

              <form onSubmit={handleSubmit}>

                <div className="row g-4">

                  {/* BASIC INFORMATION */}
                  <div className="col-12">
                    <div className="form-section">

                      <div className="form-section-title">
                        <i className="bi bi-file-text"></i>
                        <span>Basic Information</span>
                      </div>

                      <div className="row g-4">

                        <div className="col-12 col-lg-8">
                          <label className="form-label-custom">
                            Article Title
                            <span className="text-danger ms-1">
                              *
                            </span>
                          </label>

                          <input
  type="text"
  className="form-control-custom"
  value={title}
  onChange={(event) =>
    handleTitleChange(
      event.target.value
    )
  }
  placeholder="Example: Introduction to Artificial Intelligence"
  required
  disabled={
    checkingAccess ||
    articleAccess !== true
  }
/>

                          <div className="form-help">
                            Use a clear, informative,
                            and easy-to-understand title.
                          </div>
                        </div>

                        <div className="col-12 col-lg-4">
                          <label className="form-label-custom">
                            Category
                          </label>

                          <input
                            type="text"
                            className="form-control-custom"
                            value={category}
                            onChange={(event) =>
                              setCategory(
                                event.target.value
                              )
                            }
                            placeholder="Technology"
                            disabled={
  checkingAccess ||
  articleAccess !== true
}
                          />
                        </div>

                        <div className="col-12">
                          <label className="form-label-custom">
                            Slug
                            <span className="text-danger ms-1">
                              *
                            </span>
                          </label>

                          <input
                            type="text"
                            className="form-control-custom"
                            value={slug}
                            onChange={(event) =>
                              setSlug(
                                event.target.value
                              )
                            }
                            placeholder="introduction-to-artificial-intelligence"
                            required
                            disabled={
  checkingAccess ||
  articleAccess !== true
}
                          />

                          {slug && (
                            <div className="slug-preview">
                              <i className="bi bi-link-45deg me-1"></i>
                              /{slug}
                            </div>
                          )}
                        </div>

                        <div className="col-12">
                          <label className="form-label-custom">
                            Excerpt / Summary
                          </label>

                          <textarea
                            className="form-control-custom"
                            rows={4}
                            value={excerpt}
                            onChange={(event) =>
                              setExcerpt(
                                event.target.value
                              )
                            }
                            placeholder="Write a short summary of your article..."

                            disabled={
  checkingAccess ||
  articleAccess !== true
}
                          />

                          <div className="form-help">
                            Provide a concise summary
                            that describes what readers
                            can expect from the article.
                          </div>
                        </div>

                      </div>
                    </div>
                  </div>

                  {/* ARTICLE CONTENT */}
                  <div className="col-12">
                    <div className="form-section">

                      <div className="form-section-title">
                        <i className="bi bi-pencil-square"></i>
                        <span>Article Content</span>
                      </div>

                      <label className="form-label-custom">
                        Content
                        <span className="text-danger ms-1">
                          *
                        </span>
                      </label>

                      <textarea
                        className="form-control-custom"
                        rows={15}
                        value={content}
                        onChange={(event) =>
                          setContent(
                            event.target.value
                          )
                        }
                        placeholder="Write your article content here..."
                        required

                        disabled={
  checkingAccess ||
  articleAccess !== true
}
                      />

                      <div className="form-help">
                        Write the complete content of
                        your article with clear and
                        informative explanations.
                      </div>

                    </div>
                  </div>

                  {/* ARTICLE IMAGES */}
                  <div className="col-12">
                    <div className="form-section">

                      <div className="form-section-title">
                        <i className="bi bi-images"></i>
                        <span>Article Images</span>
                      </div>

                      <div className="upload-box">

                        <label className="form-label-custom">
                          Select Images
                        </label>

                        <input
                          type="file"
                          className="upload-input"
                          accept="image/*"
                          multiple
                          onChange={
                            handleImagesChange
                          }
                          disabled={
  checkingAccess ||
  articleAccess !== true
}
                        />

                        <div className="form-help">
                          You can select one or multiple
                          images. The first image will be
                          used as the article thumbnail.
                        </div>

                      </div>

                      {previews.length > 0 && (
                        <div className="mt-4">

                          <div className="form-label-custom mb-3">
                            Image Preview
                          </div>

                          <div className="preview-grid">

                            {previews.map(
                              (preview, index) => (
                                <div
                                  key={`${preview}-${index}`}
                                  className="preview-item"
                                  style={{
                                    animationDelay: `${index * 80}ms`,
                                  }}
                                >

                                  <img
                                    src={preview}
                                    alt={`Preview ${index + 1}`}
                                    className="preview-image"
                                  />

                                  {index === 0 && (
                                    <span className="thumbnail-badge">
                                      Thumbnail
                                    </span>
                                  )}

                                  <button
                                    type="button"
                                    className="remove-image"
                                    onClick={() =>
                                      removeImage(index)
                                    }
                                    aria-label={`Remove image ${index + 1}`}
                                  >
                                    <i className="bi bi-x-lg"></i>
                                  </button>

                                </div>
                              )
                            )}

                          </div>
                        </div>
                      )}

                    </div>
                  </div>

                  {/* PUBLISH SETTINGS */}
                  <div className="col-12">
                    <div className="form-section">

                      <div className="form-section-title">
                        <i className="bi bi-calendar2-check"></i>
                        <span>Publish Settings</span>
                      </div>

                      <div className="row g-4">

                        <div className="col-12 col-lg-6">

                          <div className="publish-date-box">

                            <div className="publish-date-header">
                              <i className="bi bi-calendar-event"></i>

                              <div className="publish-date-title">
                                Publish Date
                                <span className="text-danger ms-1">
                                  *
                                </span>
                              </div>
                            </div>

                            <input
                              type="date"
                              className="publish-date-input"
                              value={publishedAt}
                              onChange={(event) =>
                                setPublishedAt(
                                  event.target.value
                                )
                              }
                              required
                              disabled={
  checkingAccess ||
  articleAccess !== true
}
                            />

                            <div className="form-help">
                              Select the date when the
                              article should be published.
                            </div>

                          </div>

                        </div>

                        <div className="col-12 col-lg-6">

                          <div className="publish-box h-100">

                            <div className="publish-info">

                              <div className="publish-icon">
                                <i
                                  className={
                                    published
                                      ? "bi bi-send-check-fill"
                                      : "bi bi-file-earmark-text"
                                  }
                                ></i>
                              </div>

                              <div>

                                <div className="publish-title">
                                  {published
                                    ? "Article Published"
                                    : "Article Draft"}
                                </div>

                                <div className="publish-description">
                                  {published
                                    ? "The article will be published immediately."
                                    : "The article will be saved as a draft."}
                                </div>

                              </div>

                            </div>

                            <div className="form-check form-switch switch-custom mt-3">

                              <input
                                className="form-check-input"
                                type="checkbox"
                                id="published"
                                checked={published}
                                onChange={(event) =>
                                  setPublished(
                                    event.target.checked
                                  )
                                }
                                disabled={
  checkingAccess ||
  articleAccess !== true
}
                              />

                            </div>

                          </div>

                        </div>

                      </div>
                    </div>
                  </div>

                  {/* ACTIONS */}
                  <div className="col-12">

                    <hr className="my-1" />

                    <div className="form-actions">

                      <Link
                        href="/articles/edit"
                        className="cancel-button"
                      >
                        <i className="bi bi-arrow-left"></i>
                        <span>Cancel</span>
                      </Link>

                      <button
  type="submit"
  className="save-button"
  disabled={
    checkingAccess ||
    articleAccess !== true ||
    saving ||
    uploading
  }
>

                        {saving || uploading ? (
                          <>
                            <span
                              className="spinner-border spinner-border-sm"
                              role="status"
                              aria-hidden="true"
                            ></span>

                            <span>
                              {uploading
                                ? "Uploading Images..."
                                : "Saving Article..."}
                            </span>
                          </>
                        ) : (
                          <>
                            <i className="bi bi-check-lg"></i>

                            <span>
                              {published
                                ? "Save & Publish Article"
                                : "Save Article"}
                            </span>
                          </>
                        )}

                      </button>

                    </div>

                  </div>

                </div>

              </form>

            </div>
          </section>

        </div>
      </main>
{showAlertModal && (
  <div className="article-alert-overlay">
    <div className="article-alert-modal">
      <div
  className={`article-alert-icon ${alertType}`}
>
  {alertType === "success" ? (
    <svg
      className="article-alert-check"
      viewBox="0 0 64 64"
      aria-hidden="true"
    >
      <circle
        className="article-alert-check-circle"
        cx="32"
        cy="32"
        r="25"
      />

      <path
        className="article-alert-check-mark"
        d="M19 33.5 L28 42 L46 23"
      />
    </svg>
  ) : (
    <i
      className={
        alertType === "error"
          ? "bi bi-x-lg"
          : alertType === "warning"
          ? "bi bi-exclamation-lg"
          : "bi bi-info-lg"
      }
    ></i>
  )}
</div>

      <h4 className="article-alert-title">
        {alertTitle}
      </h4>

      <p className="article-alert-message">
        {alertMessage}
      </p>

      <button
        type="button"
        className="article-alert-button"
        onClick={() => {
          const shouldRedirect =
            alertType === "success";

          closeAlert();

          if (shouldRedirect) {
            setTimeout(() => {
              window.location.href = "/blog";
            }, 300);
          }
        }}
      >
        OK
      </button>
    </div>
  </div>
)}

<Footer />
    </>
  );
}