import { NavLink, Outlet, Route, Routes, useNavigate, useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import BridgeupSurveyPage from "./BridgeupSurveyPage";
import AiChatbotPage from "./AiChatbotPage";

const researchItems = [
  {
    title: "LLMs",
    description: "Prompting, fine-tuning, RAG, and practical patterns for building reliable LLM systems.",
  },
  {
    title: "NLP Tasks",
    description: "Sentiment analysis, named entity recognition, question answering, and applied language workflows.",
  },
  {
    title: "System Design",
    description: "LLM pipelines, retrieval architecture, and experiment workflows that connect research to deployment.",
  },
];

const datasetItems = [
  {
    title: "Vietnamese NLP",
    description: "Curated datasets for Vietnamese tasks and downstream system experiments.",
  },
  {
    title: "Multilingual Sets",
    description: "Resources that support cross-lingual evaluation, adaptation, and broader model comparison.",
  },
  {
    title: "Synthetic Data",
    description: "Generated datasets for augmentation, prototyping, and stress-testing task behaviour.",
  },
];


const projectItems = [
  {
    path: "/projects",
    title: "LLM Applications",
    description: "Production-facing apps built from retrieval, prompting, and evaluation components.",
  },
  {
    path: "/projects",
    title: "NLP Pipelines",
    description: "Task-focused systems for sentiment analysis, information extraction, and QA workflows.",
  },
  {
    path: "/projects",
    title: "Applied Architectures",
    description: "System diagrams, stack choices, and real-world implementation notes from experiments.",
  },
];

const differentiators = [
  "Community-first research hub",
  "Project currently in build mode",
  "Data engineering + LLMs in one workflow",
  "Experiment-driven development",
];

function formatDatasetVolume(totalBytes) {
  if (!totalBytes) {
    return "0GB";
  }

  const gb = totalBytes / 1000000000;
  return `${gb.toFixed(1)}GB`;
}
function App() {
  return (
    <Routes>
      <Route element={<SiteLayout />}>
        <Route path="/" element={<HomePage />} />
        <Route
          path="/about"
          element={
            <InfoPage
              eyebrow="OVERVIEW"
              title="AI research hub for NLP and LLM systems."
              description="ColdBrewNLP focuses on the path from research to datasets, projects, and real-world experiments."
            />
          }
        />
        <Route path="/research" element={<ResearchPage />} />
        <Route path="/datasets" element={<DatasetsPage />} />
        <Route path="/projects" element={<ProjectsPage />} />
        <Route path="/projects/bridgeup-survey-demo" element={<BridgeupSurveyPage />} />
        <Route path="/projects/ai-chatbot" element={<AiChatbotPage />} />
        <Route path="/blog" element={<BlogPage />} />
        <Route path="/blog/:slug" element={<BlogDetailPage />} />
        <Route path="/contact" element={<ContactPage />} />
        <Route path="/modules/ai" element={<AiServicePage />} />
      </Route>
    </Routes>
  );
}

function SiteLayout() {
  return (
    <div className="site-shell">
      <header className="site-header">
        <div className="container nav-row">
          <NavLink to="/" className="brand">
            ColdBrew<span>NLP</span>
          </NavLink>
          <nav className="site-nav">
            <NavLink to="/research">Research</NavLink>
            <NavLink to="/datasets">Datasets</NavLink>
            <NavLink to="/projects">Projects</NavLink>
            <NavLink to="/contact">Community</NavLink>
          </nav>
        </div>
      </header>
      <main className="page-main">
        <Outlet />
      </main>
      <footer className="site-footer">
        <div className="container footer-layout">
          <div>
            <p className="eyebrow footer-eyebrow">COLDBREWNLP</p>
            <h2 className="footer-title">Research community for NLP and LLM systems.</h2>
            <p className="footer-copy">
              From data to LLM systems. The project is in progress and growing across research, datasets, projects, and applied experiments.
            </p>
          </div>
          <div className="footer-presence">
            <div className="footer-card">
              <p className="eyebrow">Australia</p>
              <p>Community presence, research connections, and project development.</p>
            </div>
            <div className="footer-card">
              <p className="eyebrow">Vietnam</p>
              <p>Vietnamese NLP focus, datasets, experiments, and local community building.</p>
            </div>
          </div>
        </div>
                <div className="container footer-meta">
          <p>{"\u00A9"} 2026 ColdBrewNLP. All rights reserved.</p>
          <p>
            <a href="https://huggingface.co/coldbrewnlp" target="_blank" rel="noreferrer" className="footer-social-link">
              <img className="footer-social-icon footer-social-icon-image" src="/icons/huggingface.svg" alt="" aria-hidden="true" />
              <span>HuggingFace</span>
            </a>
          </p>
          <p>
            <a href="https://github.com/coldbrewnlp" target="_blank" rel="noreferrer" className="footer-social-link">
              <img className="footer-social-icon footer-social-icon-image" src="/icons/github.svg" alt="" aria-hidden="true" />
              <span>Github</span>
            </a>
          </p>
        </div>
      </footer>
    </div>
  );
}

function HomePage() {
  return (
    <>
      <section className="hero hero-unimelb">
        <div className="container hero-layout">
          <div className="hero-copy-wrap">
            <p className="eyebrow light-eyebrow">COLDBREWNLP</p>
            <h1 className="hero-title">AI Research Hub for NLP and LLM Systems.</h1>
            <p className="hero-copy hero-copy-light">
              From research to datasets, projects, and real-world experiments. We are building an open community around NLP and LLM systems while the project is still in progress.
            </p>
            <div className="hero-actions">
              <NavLink to="/research" className="button button-primary-blue">
                Explore Research
              </NavLink>
              <NavLink to="/datasets" className="button button-outline-light">
                View datasets
              </NavLink>
            </div>
          </div>

          <aside className="hero-aside">
            <p className="eyebrow">Focus</p>
            <h2>From data to LLM systems.</h2>
            <ul className="feature-list">
              {differentiators.map((item) => (
                <li key={item}>{item}</li>
              ))}
            </ul>
          </aside>
        </div>
      </section>

      <section className="section section-surface">
        <div className="container split-section">
          <div className="section-heading narrow">
            <p className="eyebrow">CORE SECTIONS</p>
            <h2>Research that connects directly to data, evaluation, and applied systems.</h2>
          </div>
          <div className="card-grid editorial-grid">
            {researchItems.map((item) => (
              <article className="editorial-card" key={item.title}>
                <h3>{item.title}</h3>
                <p>{item.description}</p>
              </article>
            ))}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container showcase-block">
          <div className="showcase-copy">
            <p className="eyebrow">DATASETS</p>
            <h2>Vietnamese-first resources, multilingual coverage, and synthetic data for experimentation.</h2>
            <p>
              Each dataset entry is intended to carry practical metadata such as task, size, domain, and source link so experiments stay reproducible.
            </p>
          </div>
          <div className="module-stack">
            {datasetItems.map((item) => (
              <NavLink key={item.title} to="/datasets" className="module-row">
                <div>
                  <h3>{item.title}</h3>
                  <p>{item.description}</p>
                </div>
                <span className="arrow-mark">-&gt;</span>
              </NavLink>
            ))}
          </div>
        </div>
      </section>


      <section className="section">
        <div className="container showcase-block">
          <div className="showcase-copy">
            <p className="eyebrow">PROJECTS</p>
            <h2>Real-world systems with architecture, tech stack, and implementation notes.</h2>
            <p>
              Typical examples include sentiment analysis pipelines, retrieval-augmented generation systems, and recommendation workflows grounded in experiments.
            </p>
          </div>
          <div className="module-stack">
            {projectItems.map((item) => (
              <NavLink key={item.title} to={item.path} className="module-row">
                <div>
                  <h3>{item.title}</h3>
                  <p>{item.description}</p>
                </div>
                <span className="arrow-mark">-&gt;</span>
              </NavLink>
            ))}
          </div>
        </div>
      </section>

    </>
  );
}

function InfoPage({ eyebrow = "COMPANY", title, description }) {
  return (
    <section className="section page-banner">
      <div className="container info-panel section-callout">
        <p className="eyebrow">{eyebrow}</p>
        <h1>{title}</h1>
        <p className="callout-copy">{description}</p>
      </div>
    </section>
  );
}

function ResearchPage() {
  const [researchData, setResearchData] = useState({
    title: "",
    description: "",
    statusOptions: [],
    entries: [],
  });
  const [query, setQuery] = useState("");
  const [status, setStatus] = useState("All Status");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    async function fetchResearchSource(url) {
      const response = await fetch(url, {
        headers: {
          Accept: "application/json",
        },
      });
      const contentType = response.headers.get("content-type") || "";

      if (!contentType.includes("application/json")) {
        throw new Error(`Expected JSON from ${url} but received ${contentType || "unknown content type"}.`);
      }

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data?.error || `Could not load research from ${url}.`);
      }

      return data;
    }

    async function loadResearch() {
      try {
        const data = await fetchResearchSource("/api/research");
        setResearchData(data);
      } catch (apiError) {
        try {
          const fallbackData = await fetchResearchSource("/data/research.json");
          setResearchData(fallbackData);
        } catch (fallbackError) {
          setError(`Could not load research: ${apiError.message}`);
        }
      } finally {
        setLoading(false);
      }
    }

    loadResearch();
  }, []);

  const filteredEntries = researchData.entries.filter((entry) => {
    const keyword = query.trim().toLowerCase();
    const matchesQuery = !keyword || [entry.topic, entry.reference, ...(entry.keyFocus || []), ...(entry.documents || []).map((item) => item.title)].join(" ").toLowerCase().includes(keyword);
    const matchesStatus = status === "All Status" || entry.status === status;
    return matchesQuery && matchesStatus;
  });

  return (
    <section className="section page-banner research-repository-page">
      <div className="container page-stack research-repository-stack">
        <section className="research-hero">
          <h1>{researchData.title || "Research Repository"}</h1>
          <p className="intro-copy research-intro">
            {researchData.description || "A centralized index of our ongoing inquiries, technical documentation, and published papers regarding large-scale language modeling."}
          </p>
        </section>

        {loading ? (
          <article className="info-panel section-callout">
            <p className="callout-copy">Loading research repository...</p>
          </article>
        ) : error ? (
          <article className="info-panel section-callout">
            <p className="status-message callout-copy">{error}</p>
          </article>
        ) : (
          <>
            <section className="research-controls">
              <div className="research-controls-label">Search index</div>
              <div className="research-controls-row">
                <label className="research-search-field" htmlFor="research-query">
                  <span className="research-field-icon" aria-hidden="true">
                    <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                      <circle cx="8.5" cy="8.5" r="4.75" />
                      <path d="M12 12l4.5 4.5" />
                    </svg>
                  </span>
                  <input
                    id="research-query"
                    type="text"
                    value={query}
                    onChange={(event) => setQuery(event.target.value)}
                    placeholder="Filter by keyword..."
                  />
                </label>
                <label className="research-filter-field" htmlFor="research-status">
                  <span className="research-field-icon" aria-hidden="true">
                    <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M5 7.5h10" />
                      <path d="M7.5 10.5h5" />
                      <path d="M9 13.5h2" />
                    </svg>
                  </span>
                  <select id="research-status" value={status} onChange={(event) => setStatus(event.target.value)}>
                    {researchData.statusOptions.map((option) => (
                      <option key={option} value={option}>{option}</option>
                    ))}
                  </select>
                </label>
              </div>
            </section>

            <section className="research-table-shell" aria-label="Research repository entries">
              <div className="research-table-head">
                <span>Research topic</span>
                <span>Key focus</span>
                <span>Documentation / papers</span>
                <span>Access</span>
              </div>
              <div className="research-table-body">
                {filteredEntries.map((entry) => (
                  <article className="research-row" key={entry.id}>
                    <div className="research-topic-cell">
                      <h3>{entry.topic}</h3>
                      <p>{entry.reference}</p>
                    </div>
                    <div className="research-focus-cell">
                      <ul>
                        {entry.keyFocus.map((focus) => (
                          <li key={focus}>{focus}</li>
                        ))}
                      </ul>
                    </div>
                    <div className="research-docs-cell">
                      {entry.documents.map((document) => (
                        <div className="research-doc-item" key={document.title}>
                          <strong>{document.title}</strong>
                          <span>{document.meta}</span>
                        </div>
                      ))}
                    </div>
                    <div className="research-access-cell">
                      {entry.access.map((link) => (
                        <a key={link.label} href={link.url} onClick={(event) => { if (!link.url || link.url === "/") event.preventDefault(); }} target={link.url && link.url !== "/" && !link.url.startsWith("/") ? "_blank" : undefined} rel={link.url && link.url !== "/" && !link.url.startsWith("/") ? "noreferrer" : undefined}>{link.label}</a>
                      ))}
                    </div>
                  </article>
                ))}
              </div>
            </section>
          </>
        )}
      </div>
    </section>
  );
}
function DatasetsPage() {
  const pageSize = 5;
  const [page, setPage] = useState(1);
  const [datasets, setDatasets] = useState([]);
  const [query, setQuery] = useState("");
  const [datasetFilter, setDatasetFilter] = useState("All Status");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    async function fetchDatasetSource(url) {
      const response = await fetch(url, {
        headers: {
          Accept: "application/json",
        },
      });
      const contentType = response.headers.get("content-type") || "";

      if (!contentType.includes("application/json")) {
        throw new Error(`Expected JSON from ${url} but received ${contentType || "unknown content type"}.`);
      }

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data?.error || `Could not load datasets from ${url}.`);
      }

      return data;
    }

    async function loadDatasets() {
      try {
        const data = await fetchDatasetSource("/api/datasets");
        setDatasets(data);
      } catch (apiError) {
        try {
          const fallbackData = await fetchDatasetSource("/data/datasets.json");
          setDatasets(fallbackData);
        } catch (fallbackError) {
          setError(`Could not load datasets: ${apiError.message}`);
        }
      } finally {
        setLoading(false);
      }
    }

    loadDatasets();
  }, []);

  const datasetOptions = ["All Status", ...new Set(datasets.map((item) => item.type))];
  const filteredDatasets = datasets.filter((item) => {
    const keyword = query.trim().toLowerCase();
    const matchesQuery = !keyword || [item.title, item.summary, item.type].join(" ").toLowerCase().includes(keyword);
    const matchesFilter = datasetFilter === "All Status" || item.type === datasetFilter;
    return matchesQuery && matchesFilter;
  });

  useEffect(() => {
    setPage(1);
  }, [datasets.length, query, datasetFilter]);

  const totalPages = Math.max(1, Math.ceil(filteredDatasets.length / pageSize));
  const currentPage = Math.min(page, totalPages);
  const startIndex = (currentPage - 1) * pageSize;
  const visibleDatasets = filteredDatasets.slice(startIndex, startIndex + pageSize);

  return (
    <section className="section page-banner dataset-archive-page">
      <div className="container page-stack dataset-archive-stack">
        <div className="dataset-archive-hero">
          <div className="dataset-archive-copy">
            <p className="eyebrow dataset-archive-eyebrow">Regional resources / Asia-Pacific</p>
            <h1>Vietnamese NLP Datasets Archive</h1>
            <p className="intro-copy dataset-archive-intro">
              A curated, high-precision repository of linguistic resources for Vietnamese language processing, covering clinical, legal, and sentiment domains. Built as a systematically collected and curated collection for learning and research, this archive supports the advancement of NLP for Vietnamese, a low-resource language.
            </p>
          </div>
        </div>

        {loading ? (
          <article className="info-panel section-callout">
            <p className="callout-copy">Loading datasets...</p>
          </article>
        ) : error ? (
          <article className="info-panel section-callout">
            <p className="status-message callout-copy">{error}</p>
          </article>
        ) : (
          <>
            <section className="research-controls dataset-controls">
              <div className="research-controls-label">Search index</div>
              <div className="research-controls-row">
                <label className="research-search-field" htmlFor="dataset-query">
                  <span className="research-field-icon" aria-hidden="true">
                    <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                      <circle cx="8.5" cy="8.5" r="4.75" />
                      <path d="M12 12l4.5 4.5" />
                    </svg>
                  </span>
                  <input
                    id="dataset-query"
                    type="text"
                    value={query}
                    onChange={(event) => setQuery(event.target.value)}
                    placeholder="Filter by keyword..."
                  />
                </label>
                <label className="research-filter-field" htmlFor="dataset-filter">
                  <span className="research-field-icon" aria-hidden="true">
                    <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M5 7.5h10" />
                      <path d="M7.5 10.5h5" />
                      <path d="M9 13.5h2" />
                    </svg>
                  </span>
                  <select id="dataset-filter" value={datasetFilter} onChange={(event) => setDatasetFilter(event.target.value)}>
                    {datasetOptions.map((option) => (
                      <option key={option} value={option}>{option}</option>
                    ))}
                  </select>
                </label>
              </div>
            </section>

            <section className="dataset-table-shell" aria-label="Dataset archive">
              <div className="dataset-table-head">
                <span>Dataset name</span>
                <span>Type</span>
                <span>Size</span>
                <span>Entries</span>
                <span>Paper</span>
              </div>
              <div className="dataset-table-body">
                {visibleDatasets.map((item) => (
                  <article className="dataset-row" key={item.id || item.title}>
                    <div className="dataset-name-cell">
                      <h3>{item.title}</h3>
                      <p>{item.summary}</p>
                    </div>
                    <div className="dataset-type-cell">
                      <span className="dataset-pill">{item.type}</span>
                    </div>
                    <div className="dataset-meta-cell" data-label="Size">
                      {item.size}
                    </div>
                    <div className="dataset-meta-cell" data-label="Entries">
                      {item.entries} {item.entriesLabel}
                    </div>
                    <div className="dataset-action-cell">
                      <a href={item.paper} target="_blank" rel="noreferrer" className="dataset-action-link">
                        Paper
                      </a>
                    </div>
                  </article>
                ))}
              </div>
            </section>

            <div className="dataset-table-footer">
              <p>
                Showing {filteredDatasets.length === 0 ? 0 : startIndex + 1} to {Math.min(startIndex + pageSize, filteredDatasets.length)} of {filteredDatasets.length} datasets
              </p>
              <nav className="dataset-pagination" aria-label="Dataset pages">
                <button type="button" onClick={() => setPage((current) => Math.max(1, current - 1))} disabled={currentPage === 1}>
                  {"<"}
                </button>
                {Array.from({ length: totalPages }, (_, index) => {
                  const pageNumber = index + 1;

                  return (
                    <button
                      key={pageNumber}
                      type="button"
                      className={currentPage === pageNumber ? "is-active" : ""}
                      onClick={() => setPage(pageNumber)}
                    >
                      {pageNumber}
                    </button>
                  );
                })}
                <button type="button" onClick={() => setPage((current) => Math.min(totalPages, current + 1))} disabled={currentPage === totalPages}>
                  {">"}
                </button>
              </nav>
            </div>
          </>
        )}
      </div>
    </section>
  );
}
function ProjectsPage() {
  const [projectsData, setProjectsData] = useState({
    stats: [],
    ongoingLabel: "",
    ongoing: [],
    archiveFilters: [],
    archive: [],
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    async function fetchProjectSource(url) {
      const response = await fetch(url, {
        headers: {
          Accept: "application/json",
        },
      });
      const contentType = response.headers.get("content-type") || "";

      if (!contentType.includes("application/json")) {
        throw new Error(`Expected JSON from ${url} but received ${contentType || "unknown content type"}.`);
      }

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data?.error || `Could not load projects from ${url}.`);
      }

      return data;
    }

    async function loadProjects() {
      try {
        const data = await fetchProjectSource("/api/projects");
        setProjectsData(data);
      } catch (apiError) {
        try {
          const fallbackData = await fetchProjectSource("/data/projects.json");
          setProjectsData(fallbackData);
        } catch (fallbackError) {
          setError(`Could not load projects: ${apiError.message}`);
        }
      } finally {
        setLoading(false);
      }
    }

    loadProjects();
  }, []);

  return (
    <section className="section page-banner projects-directory-page">
      <div className="container page-stack projects-directory-stack">
        <section className="projects-hero">
          <div className="projects-hero-copy">
            <p className="eyebrow projects-eyebrow">Project directory</p>
            <h1>Active Lab Projects & Archives</h1>
            <p className="intro-copy projects-intro">
              A comprehensive repository of our ongoing computational linguistics initiatives and historical research milestones. We specialize in low-resource language modeling and cross-lingual semantic alignment.
            </p>
          </div>
          <aside className="projects-stats-card">
            {projectsData.stats.map((item) => (
              <div key={item.label}>
                <strong>{item.value}</strong>
                <span>{item.label}</span>
              </div>
            ))}
          </aside>
        </section>

        {loading ? (
          <article className="info-panel section-callout">
            <p className="callout-copy">Loading projects...</p>
          </article>
        ) : error ? (
          <article className="info-panel section-callout">
            <p className="status-message callout-copy">{error}</p>
          </article>
        ) : (
          <>
            <section className="projects-section">
              <div className="projects-section-head">
                <h2>Ongoing Research</h2>
                <p>{projectsData.ongoingLabel}</p>
              </div>
              <section className="projects-table-shell" aria-label="Ongoing research projects">
                <div className="projects-table-head">
                  <span>Project name</span>
                  <span>Phase / status</span>
                  <span>Lead / scope</span>
                  <span>Actions</span>
                </div>
                <div className="projects-table-body">
                  {projectsData.ongoing.map((project) => (
                    <article className="projects-row" key={project.id || project.title}>
                      <div className="projects-name-cell">
                        <h3>{project.title}</h3>
                        <p>{project.summary}</p>
                      </div>
                      <div className="projects-phase-cell">
                        <span className="projects-phase-pill">{project.phase}</span>
                      </div>
                      <div className="projects-lead-cell">
                        <strong>{project.lead}</strong>
                        <span>{project.scope}</span>
                      </div>
                      <div className="projects-action-cell">
                        <a href={project.actionUrl || "/"} onClick={(event) => { if (!project.actionUrl) event.preventDefault(); }} className="projects-action-link" target={project.actionUrl && !project.actionUrl.startsWith("/") ? "_blank" : undefined} rel={project.actionUrl && !project.actionUrl.startsWith("/") ? "noreferrer" : undefined}>{project.actionLabel}</a>
                      </div>
                    </article>
                  ))}
                </div>
              </section>
            </section>

            <section className="projects-section">
              <div className="projects-section-head">
                <h2>Completed & Archive</h2>
                <div className="projects-filter-tags">
                  {projectsData.archiveFilters.map((filter, index) => (
                    <span key={filter} className={index === 0 ? "is-active" : ""}>{filter}</span>
                  ))}
                </div>
              </div>
              <div className="archive-grid-shell">
                <div className="archive-grid">
                  {projectsData.archive.map((project) => (
                    <article className="archive-card" key={project.id}>
                      <div className="archive-card-top">
                        <span className="archive-code">{project.id}</span>
                        <span className="archive-year">{project.year}</span>
                      </div>
                      <h3>{project.title}</h3>
                      <p>{project.description}</p>
                      <div className="archive-links">
                        {project.links.map((link) => (
                          <a key={link.label} href={link.url} onClick={(event) => { if (!link.url || link.url === "/") event.preventDefault(); }} target={link.url && link.url !== "/" && !link.url.startsWith("/") ? "_blank" : undefined} rel={link.url && link.url !== "/" && !link.url.startsWith("/") ? "noreferrer" : undefined}>{link.label}</a>
                        ))}
                      </div>
                    </article>
                  ))}
                </div>
              </div>
              <div className="archive-loadmore-wrap">
                <button type="button" className="projects-loadmore-button">Load More Archives</button>
              </div>
            </section>
          </>
        )}
      </div>
    </section>
  );
}
function BlogPage() {
  const navigate = useNavigate();
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [publishing, setPublishing] = useState(false);
  const [error, setError] = useState("");
  const [form, setForm] = useState({
    title: "",
    author: "",
    excerpt: "",
    content: "",
  });

  useEffect(() => {
    async function loadPosts() {
      try {
        const response = await fetch("/api/blog/posts");
        const data = await response.json();
        setPosts(data);
      } catch (fetchError) {
        setError(`Could not load blog posts: ${fetchError.message}`);
      } finally {
        setLoading(false);
      }
    }

    loadPosts();
  }, []);

  async function handlePublish(event) {
    event.preventDefault();
    setPublishing(true);
    setError("");

    try {
      const response = await fetch("/api/blog/posts", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(form),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to publish post.");
      }

      setPosts((currentPosts) => [data, ...currentPosts]);
      setForm({ title: "", author: "", excerpt: "", content: "" });
      navigate(`/blog/${data.slug}`);
    } catch (publishError) {
      setError(publishError.message);
    } finally {
      setPublishing(false);
    }
  }

  function updateField(event) {
    const { name, value } = event.target;
    setForm((current) => ({ ...current, [name]: value }));
  }

  return (
    <section className="section page-banner">
      <div className="container blog-layout">
        <div className="blog-column">
          <div className="section-heading narrow">
            <p className="eyebrow">RESEARCH NOTES</p>
            <h1>Write and publish research notes</h1>
            <p className="intro-copy">
              This section is being built as a lightweight space for research notes, experiments, and community-shared findings.
            </p>
          </div>

          {loading ? <p>Loading posts...</p> : null}
          {error ? <p className="status-message">{error}</p> : null}

          <div className="blog-list">
            {posts.map((post) => (
              <NavLink key={post.slug} to={`/blog/${post.slug}`} className="blog-card">
                <p className="eyebrow">{formatDate(post.createdAt)}</p>
                <h3>{post.title}</h3>
                <p>{post.excerpt}</p>
                <span className="text-link">Read article</span>
              </NavLink>
            ))}
          </div>
        </div>

        <aside className="writer-panel">
          <p className="eyebrow">BLOG STUDIO</p>
          <h2>Draft a new post</h2>
          <form className="writer-form" onSubmit={handlePublish}>
            <label className="field-label" htmlFor="title">
              Title
            </label>
            <input id="title" name="title" value={form.title} onChange={updateField} className="text-input" />

            <label className="field-label" htmlFor="author">
              Author
            </label>
            <input id="author" name="author" value={form.author} onChange={updateField} className="text-input" />

            <label className="field-label" htmlFor="excerpt">
              Excerpt
            </label>
            <textarea id="excerpt" name="excerpt" value={form.excerpt} onChange={updateField} className="textarea-compact" />

            <label className="field-label" htmlFor="content">
              Content
            </label>
            <textarea id="content" name="content" value={form.content} onChange={updateField} />

            <button className="button button-primary-blue" type="submit" disabled={publishing}>
              {publishing ? "Publishing..." : "Publish post"}
            </button>
          </form>
        </aside>
      </div>
    </section>
  );
}

function BlogDetailPage() {
  const { slug } = useParams();
  const [post, setPost] = useState(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadPost() {
      try {
        const response = await fetch(`/api/blog/posts/${slug}`);
        const data = await response.json();

        if (!response.ok) {
          throw new Error(data.error || "Could not load post.");
        }

        setPost(data);
      } catch (fetchError) {
        setError(fetchError.message);
      } finally {
        setLoading(false);
      }
    }

    loadPost();
  }, [slug]);

  if (loading) {
    return (
      <section className="section page-banner">
        <div className="container info-panel section-callout">
          <p>Loading post...</p>
        </div>
      </section>
    );
  }

  if (error) {
    return (
      <section className="section page-banner">
        <div className="container info-panel section-callout">
          <p className="status-message">{error}</p>
        </div>
      </section>
    );
  }

  return (
    <section className="section page-banner">
      <article className="container article-shell">
        <p className="eyebrow">BLOG ARTICLE</p>
        <h1>{post.title}</h1>
        <div className="article-meta">
          <span>{post.author}</span>
          <span>{formatDate(post.createdAt)}</span>
        </div>
        <div className="article-body">
          {post.content.split("\n\n").map((paragraph) => (
            <p key={paragraph}>{paragraph}</p>
          ))}
        </div>
      </article>
    </section>
  );
}

function ContactPage() {
  return (
    <section className="section page-banner">
      <div className="container contact-layout">
        <article className="info-panel section-callout community-panel">
          <p className="eyebrow">COMMUNITY</p>
          <h1>We are building the community</h1>
          <p className="callout-copy">
            ColdBrewNLP is currently being built. We are growing a community around Vietnamese NLP, LLM systems, datasets, projects, and practical experiments.
          </p>
          <p className="callout-copy">More updates, contributions, and public project directions will be shared as the platform evolves.</p>
        </article>
      </div>
    </section>
  );
}

function AiServicePage() {
  const [prompt, setPrompt] = useState("");
  const [result, setResult] = useState("No analysis yet.");
  const [loading, setLoading] = useState(false);

  async function handleSubmit(event) {
    event.preventDefault();
    setLoading(true);

    try {
      const response = await fetch("/api/analyze", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ prompt }),
      });

      const data = await response.json();
      setResult(data.result || data.error || "No response payload received.");
    } catch (error) {
      setResult(`Request failed: ${error.message}`);
    } finally {
      setLoading(false);
    }
  }

  return (
    <section className="section page-banner">
      <div className="container ai-demo-layout">
        <div className="section-heading narrow">
          <p className="eyebrow">IN PROGRESS</p>
          <h1>AI Service Demo</h1>
          <p className="intro-copy">
            A lightweight demo is still available while the broader project and community platform continue to be built.
          </p>
        </div>
        <div className="demo-grid demo-grid-modern">
          <form className="demo-panel" onSubmit={handleSubmit}>
            <label htmlFor="prompt" className="field-label">
              Prompt
            </label>
            <textarea
              id="prompt"
              value={prompt}
              onChange={(event) => setPrompt(event.target.value)}
              placeholder="Paste a prompt to analyse..."
            />
            <button className="button button-primary-blue" type="submit" disabled={loading}>
              {loading ? "Analysing..." : "Send"}
            </button>
          </form>
          <div className="demo-panel">
            <p className="field-label">Result</p>
            <pre>{result}</pre>
          </div>
        </div>
      </div>
    </section>
  );
}

function formatDate(value) {
  return new Date(value).toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

export default App;








































