'use client'

import * as React from 'react'
import { ArrowRight, BookOpen, FileText, HelpCircle, Microscope, Beaker, Activity, Brain, Heart } from 'lucide-react'
import { useRouter } from '@/lib/router'
import { PageShell, PageHero, Section, SectionHeading, Reveal, Eyebrow, Card, LabeledDivider, LinkButton, Pill } from '@/components/site/ui'
import { ContentModal } from '@/components/site/content-modal'
import { KNOWLEDGE_ARTICLES, type ArticleData } from '@/lib/articles'

const ARTICLES = [
  { tag: 'Analytical', title: 'Method validation per ICH Q2(R2): a practical primer', desc: 'An overview of the updated ICH Q2(R2) guideline on analytical method validation — specificity, linearity, range, accuracy, precision, LOD, LOQ and robustness.', articleId: 'ich-q2r2-method-validation' },
  { tag: 'Biologics', title: 'Characterizing monoclonal antibodies: a multi-attribute approach', desc: 'How peptide mapping, glycan profiling, charge variant analysis and aggregation testing combine to define a mAb quality profile.', articleId: 'mab-characterization' },
  { tag: 'Formulation', title: 'Lipid nanoparticles for nucleic acid delivery', desc: 'The science behind LNP-mediated mRNA delivery — ionizable lipids, PEG-lipids, structure-function relationships and characterization.', articleId: 'lnp-nucleic-acid-delivery' },
  { tag: 'Clinical', title: 'Adaptive clinical trial design: principles and practice', desc: 'How adaptive designs — including seamless Phase II/III and master protocols — improve the efficiency and ethics of clinical development.', articleId: 'adaptive-clinical-trials' },
  { tag: 'Quality', title: 'EU GMP Annex 1 (2023): what changed, and why', desc: 'A summary of the revised EU GMP Annex 1 — contamination control strategy, barrier technology, and the QRM framework.', articleId: 'eu-gmp-annex-1-2023' },
  { tag: 'Sustainability', title: 'Green chemistry in API synthesis', desc: 'How the 12 Principles of Green Chemistry are applied in pharmaceutical manufacturing — atom economy, solvent selection, biocatalysis.', articleId: 'green-chemistry-api-synthesis' },
]

const FAQS = [
  {
    q: 'What is the difference between a pharmaceutical and a nutraceutical?',
    a: 'A pharmaceutical is a medicinal product with demonstrated efficacy, safety and quality, authorized by a regulatory authority (such as the FDA or EMA) for the diagnosis, treatment, prevention or cure of disease. A nutraceutical is a product derived from food or nutrient sources that is intended to provide health or medical benefits, including the prevention and treatment of disease. Nutraceuticals are typically regulated as dietary supplements or food, not as medicines, and are not held to the same efficacy standards as pharmaceuticals. Espandiar manufactures both, under pharmaceutical-grade quality systems.',
  },
  {
    q: 'What does GMP mean, and why does it matter?',
    a: 'GMP — Good Manufacturing Practice — is a system for ensuring that products are consistently produced and controlled according to quality standards. GMP covers all aspects of production — from raw materials, premises and equipment to training, hygiene and documentation. The principles of GMP are defined by national and international regulators including FDA (21 CFR 210/211), EU GMP (EudraLex Volume 4), WHO GMP and ICH Q7. GMP is a regulatory requirement for the manufacture of pharmaceutical products.',
  },
  {
    q: 'What is an API?',
    a: 'An Active Pharmaceutical Ingredient (API) is the biologically active component of a drug product — the molecule that produces the therapeutic effect. A finished drug product typically contains one or more APIs plus excipients (inactive ingredients) that confer desired formulation properties. APIs are manufactured under ICH Q7 GMP and characterized for identity, assay, purity, impurities and physicochemical properties, with specifications defined per ICH Q6A (chemical) or Q6B (biological).',
  },
  {
    q: 'What is the difference between a generic and an innovator drug?',
    a: 'An innovator drug is the first authorized version of a new active substance, developed and approved on the basis of a full clinical development program. A generic drug contains the same active substance as the innovator, in the same dosage form, with the same quality, and demonstrated to be bioequivalent. Generic drugs can be approved through abbreviated pathways (ANDA in the US; hybrid/abridged procedures in the EU) once relevant patent and regulatory exclusivities have expired. ICH M13A harmonizes bioequivalence requirements across major markets.',
  },
  {
    q: 'What is a CDMO?',
    a: 'A Contract Development and Manufacturing Organization (CDMO) is a company that provides drug development and manufacturing services to pharmaceutical and biotechnology companies on a contract basis. CDMO services may include formulation development, analytical method development and validation, technology transfer, scale-up, clinical-trial supply, commercial manufacturing, packaging and regulatory support. The CDMO operates under GMP and is subject to the same regulatory oversight as the sponsoring company.',
  },
  {
    q: 'What is pharmacovigilance?',
    a: 'Pharmacovigilance is the science and activities relating to the detection, assessment, understanding and prevention of adverse effects or any other drug-related problem. Pharmacovigilance is a regulatory obligation throughout a product\'s lifecycle — from clinical development through post-marketing surveillance. The framework is defined by ICH E2 series (including E2D for post-marketing safety data management and E2E for pharmacovigilance planning) and implemented through national regulations (FDA 21 CFR 314.80, EU Pharmacovigilance Regulation EC 726/2004).',
  },
]

const GLOSSARY = [
  { term: 'ADME', def: 'Absorption, Distribution, Metabolism, Excretion — the four processes that determine the fate of a drug in the body.' },
  { term: 'ALCOA+', def: 'Data integrity principles: Attributable, Legible, Contemporaneous, Original, Accurate, plus Complete, Consistent, Enduring, Available.' },
  { term: 'API', def: 'Active Pharmaceutical Ingredient — the biologically active component of a drug product.' },
  { term: 'AUC', def: 'Area Under the Curve — total drug exposure over time, used in pharmacokinetics and bioequivalence.' },
  { term: 'CAPA', def: 'Corrective Action and Preventive Action — quality system for addressing deviations and preventing recurrence.' },
  { term: 'Cmax', def: 'Maximum plasma concentration of a drug after administration — a key pharmacokinetic parameter.' },
  { term: 'CQA', def: 'Critical Quality Attribute — a physical, chemical, biological or microbiological property that should be within an appropriate limit, range or distribution.' },
  { term: 'CTD', def: 'Common Technical Document — the harmonized format for regulatory submissions (ICH M4).' },
  { term: 'GMP', def: 'Good Manufacturing Practice — the system for ensuring consistent product quality in pharmaceutical manufacturing.' },
  { term: 'ICH', def: 'International Council for Harmonisation — the body that harmonizes pharmaceutical guidelines across FDA, EMA, PMDA and other regulators.' },
  { term: 'LNP', def: 'Lipid Nanoparticle — a delivery system used to encapsulate and deliver nucleic acids (mRNA, siRNA).' },
  { term: 'mAb', def: 'Monoclonal Antibody — a laboratory-produced molecule engineered to bind a specific target.' },
  { term: 'PAT', def: 'Process Analytical Technology — systems for real-time measurement and control of pharmaceutical manufacturing.' },
  { term: 'PBPK', def: 'Physiologically Based Pharmacokinetic modeling — a mechanistic approach to predicting drug disposition.' },
  { term: 'Ph. Eur.', def: 'European Pharmacopoeia — compendial standards for pharmaceutical substances and products in Europe.' },
  { term: 'QbD', def: 'Quality by Design — a systematic approach to pharmaceutical development per ICH Q8.' },
  { term: 'RTRT', def: 'Real Time Release Testing — the ability to evaluate and release a product based on process data rather than end-product testing.' },
  { term: 'USP', def: 'United States Pharmacopeia — compendial standards for pharmaceutical substances and products in the US.' },
]

export function KnowledgePage() {
  const { navigate } = useRouter()
  const [modalOpen, setModalOpen] = React.useState(false)
  const [activeArticle, setActiveArticle] = React.useState<ArticleData | null>(null)

  const openArticle = React.useCallback((articleId: string) => {
    const article = KNOWLEDGE_ARTICLES.find(a => a.id === articleId)
    if (article) {
      setActiveArticle(article)
      setModalOpen(true)
    }
  }, [])
  return (
    <PageShell>
      <PageHero
        index="01"
        eyebrow="Knowledge center"
        title="Science should be"
        highlight="shared."
        lead="Espandiar&apos;s Knowledge Center provides scientifically accurate, professionally written articles, white papers, FAQs and a glossary — intended for healthcare professionals, students, partners and anyone seeking reliable pharmaceutical information."
      />

      {/* Articles */}
      <Section tone="light">
        <SectionHeading
          index="02"
          eyebrow="Scientific articles"
          title="Articles grounded in"
          highlight="established science."
          lead="Our articles describe pharmaceutical science as recognized by ICH, WHO, FDA, EMA, USP, Ph. Eur. and peer-reviewed literature. They are intended for education, not for treatment decisions."
        />
        <div className="mt-12 grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {ARTICLES.map((a, i) => (
            <Reveal key={a.title} delay={(i % 3) * 0.08}>
              <Card className="h-full">
                <Pill tone="emerald">{a.tag}</Pill>
                <h3 className="mt-5 text-lg font-semibold tracking-[-0.02em]">{a.title}</h3>
                <p className="mt-3 text-sm leading-6 text-muted-foreground">{a.desc}</p>
                <button onClick={() => openArticle(a.articleId)} className="mt-5 inline-flex items-center gap-1.5 text-xs font-bold text-[#0d5d50] dark:text-[#8fb9ad]">
                  Read article <ArrowRight className="h-3.5 w-3.5" />
                </button>
              </Card>
            </Reveal>
          ))}
        </div>
      </Section>

      {/* Educational resources */}
      <Section tone="dark">
        <SectionHeading
          tone="dark"
          index="03"
          eyebrow="Educational resources"
          title="For students,"
          highlight="professionals and patients."
          lead="Whether you are a pharmacy student preparing for exams, a healthcare professional seeking a refresher, or a patient looking to understand your treatment better, these resources are for you."
        />
        <div className="mt-12 grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {[
            { icon: BookOpen, t: 'White papers', d: 'In-depth technical documents on formulation, analytical, manufacturing and regulatory topics — typically 8–20 pages.' },
            { icon: FileText, t: 'Research summaries', d: 'Concise summaries of published research — typically 1–2 pages, with full citations to peer-reviewed sources.' },
            { icon: Microscope, t: 'Industry insights', d: 'Perspective pieces on trends in pharmaceutical science, regulation and manufacturing — written by Espandiar subject-matter experts.' },
            { icon: HelpCircle, t: 'FAQs', d: 'Answers to commonly asked questions about pharmaceuticals, nutraceuticals, quality and regulation.' },
          ].map((r, i) => {
            const Icon = r.icon
            return (
              <Reveal key={r.t} delay={(i % 4) * 0.08}>
                <Card tone="dark" className="h-full">
                  <div className="grid h-12 w-12 place-items-center rounded-2xl bg-white/10 text-white">
                    <Icon className="h-5 w-5" />
                  </div>
                  <h3 className="mt-5 text-lg font-semibold tracking-[-0.02em]">{r.t}</h3>
                  <p className="mt-3 text-sm leading-6 text-white/60">{r.d}</p>
                </Card>
              </Reveal>
            )
          })}
        </div>
      </Section>

      {/* FAQs */}
      <Section tone="light">
        <SectionHeading
          index="04"
          eyebrow="Frequently asked questions"
          title="Common questions,"
          highlight="clearly answered."
          lead="These FAQs address questions we frequently hear from patients, healthcare professionals, students and partners. They are educational, not medical advice."
        />
        <div className="mt-12 grid gap-4 lg:grid-cols-2">
          {FAQS.map((f, i) => (
            <Reveal key={f.q} delay={(i % 2) * 0.08}>
              <Card className="h-full">
                <div className="flex items-start gap-3">
                  <span className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-[#0d5d50]/10 text-xs font-bold text-[#0d5d50] dark:bg-[#8fb9ad]/10 dark:text-[#8fb9ad]">
                    ?
                  </span>
                  <div>
                    <h3 className="text-base font-semibold tracking-[-0.02em]">{f.q}</h3>
                    <p className="mt-3 text-sm leading-6 text-muted-foreground">{f.a}</p>
                  </div>
                </div>
              </Card>
            </Reveal>
          ))}
        </div>
      </Section>

      {/* Glossary */}
      <Section tone="pearl">
        <SectionHeading
          index="05"
          eyebrow="Medical & pharmaceutical glossary"
          title="The language of"
          highlight="pharmaceutical science."
          lead="A reference glossary of common pharmaceutical, regulatory and quality terms. Definitions are based on ICH, FDA, EMA, WHO, USP and Ph. Eur. sources where applicable."
        />
        <div className="mt-12 grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {GLOSSARY.map((g, i) => (
            <Reveal key={g.term} delay={(i % 3) * 0.06}>
              <div className="rounded-2xl border border-border bg-card p-5">
                <b className="text-sm font-bold text-[#0d5d50] dark:text-[#8fb9ad]">{g.term}</b>
                <p className="mt-2 text-sm leading-6 text-muted-foreground">{g.def}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </Section>

      {/* Topics */}
      <Section tone="dark">
        <SectionHeading
          tone="dark"
          index="06"
          eyebrow="Browse by topic"
          title="Find what you"
          highlight="are looking for."
          lead="Quick navigation to the most relevant Espandiar pages by scientific topic."
        />
        <div className="mt-12 grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {[
            { icon: Beaker, t: 'Drug discovery', r: 'research' as const },
            { icon: Activity, t: 'Pharmacokinetics', r: 'research' as const },
            { icon: Microscope, t: 'Analytical chemistry', r: 'quality' as const },
            { icon: Brain, t: 'Neurology', r: 'specialty' as const },
            { icon: Heart, t: 'Cardiovascular medicine', r: 'specialty' as const },
            { icon: FileText, t: 'GMP & quality systems', r: 'quality' as const },
            { icon: BookOpen, t: 'Biotechnology', r: 'biotechnology' as const },
            { icon: FileText, t: 'Manufacturing', r: 'manufacturing' as const },
          ].map((t, i) => {
            const Icon = t.icon
            return (
              <Reveal key={t.t} delay={(i % 4) * 0.07}>
                <button
                  onClick={() => navigate(t.r)}
                  className="group flex h-full w-full items-center gap-4 rounded-2xl border border-white/15 bg-white/[0.06] p-5 text-left backdrop-blur-sm transition hover:bg-white/10"
                >
                  <div className="grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-white/10 text-white">
                    <Icon className="h-5 w-5" />
                  </div>
                  <span className="text-sm font-semibold">{t.t}</span>
                  <ArrowRight className="ml-auto h-4 w-4 opacity-50 transition group-hover:translate-x-1 group-hover:opacity-100" />
                </button>
              </Reveal>
            )
          })}
        </div>
        <Reveal className="mt-12">
          <LabeledDivider label="Disclaimer" tone="dark" />
          <p className="mt-4 text-sm leading-6 text-white/55">
            The information on this Knowledge Center is provided for
            educational purposes only. It is not medical advice and is not
            a substitute for professional diagnosis or treatment. Always
            consult a qualified healthcare professional with questions
            about a medical condition or treatment.
          </p>
        </Reveal>
      </Section>

      <ContentModal open={modalOpen} onClose={() => setModalOpen(false)} article={activeArticle} />
    </PageShell>
  )
}
