'use client'

import * as React from 'react'
import { ArrowRight, Calendar, Tag, Filter } from 'lucide-react'
import { useRouter } from '@/lib/router'
import { PageShell, PageHero, Section, SectionHeading, Reveal, Eyebrow, Card, LinkButton, Pill } from '@/components/site/ui'
import { ContentModal } from '@/components/site/content-modal'
import { NEWS_ARTICLES, type ArticleData } from '@/lib/articles'

interface NewsItem {
  tag: 'Research' | 'Corporate' | 'Investors' | 'Sustainability' | 'Careers' | 'CDMO'
  date: string
  title: string
  excerpt: string
  route?: 'news' | 'research' | 'investors' | 'sustainability' | 'careers' | 'cdmo' | 'specialty' | 'about'
  articleId?: string
}

const ALL_NEWS: NewsItem[] = [
  {
    tag: 'Research',
    date: 'August 22, 2026',
    title: 'ESP-7021 demonstrates significant intracranial activity in Phase II NSCLC study.',
    excerpt: 'Updated Phase II data from the ESP-7021-001 study show a 52.4% intracranial objective response rate in KRAS G12C-mutant NSCLC patients with untreated brain metastases, with cerebrospinal fluid concentrations exceeding the IC90 by 4.2-fold.',
    route: 'research',
    articleId: 'news-37',
  },
  {
    tag: 'CDMO',
    date: 'July 10, 2026',
    title: 'AI-powered predictive manufacturing system deployed across all sites.',
    excerpt: 'Espandiar\'s proprietary "Sentinel" AI platform has been deployed across all eight manufacturing sites, providing predictive batch release, predictive maintenance and real-time process optimization capabilities.',
    route: 'cdmo',
    articleId: 'news-36',
  },
  {
    tag: 'Corporate',
    date: 'May 18, 2026',
    title: 'Strategic collaboration with leading global pharmaceutical company announced.',
    excerpt: 'A multi-year collaboration for the co-development and co-commercialization of ESP-7021, a brain-penetrant KRAS G12C inhibitor, includes an EUR 150 million upfront payment and up to EUR 850 million in milestones.',
    route: 'about',
    articleId: 'news-35',
  },
  {
    tag: 'Research',
    date: 'February 14, 2026',
    title: 'Phase III ESP-101-301 study begins global enrollment.',
    excerpt: 'The pivotal Phase III study of Esparib in germline BRCA-mutated metastatic breast cancer will enroll 420 patients across 120 sites in 18 countries, with PFS as the primary endpoint.',
    route: 'research',
    articleId: 'news-34',
  },
  {
    tag: 'Research',
    date: 'May 14, 2025',
    title: 'Espandiar presents new translational data in precision oncology.',
    excerpt: 'Translational data from a Phase II program in molecularly defined solid tumors will be presented at an upcoming international oncology congress. The data describe biomarker-selected response patterns and inform the design of the planned Phase III program.',
    route: 'research',
    articleId: 'news-1',
  },
  {
    tag: 'Corporate',
    date: 'April 28, 2025',
    title: '2024 impact report charts progress toward net-zero operations.',
    excerpt: 'Espandiar\'s 2024 sustainability report, aligned with GRI, SASB and TCFD frameworks, documents progress against science-aligned emission reduction targets and outlines the path to net-zero Scope 1 and 2 emissions by 2035.',
    route: 'sustainability',
    articleId: 'news-2',
  },
  {
    tag: 'Investors',
    date: 'April 08, 2025',
    title: 'First-quarter results and pipeline update announced.',
    excerpt: 'Espandiar reported first-quarter financial results and provided a pipeline update across its oncology, neurology and rare disease programs. The company reaffirmed full-year guidance for R&D investment and capital expenditure.',
    route: 'investors',
    articleId: 'news-3',
  },
  {
    tag: 'CDMO',
    date: 'March 22, 2025',
    title: 'New sterile fill-finish capacity qualified at European site.',
    excerpt: 'Espandiar announced the successful qualification of a new aseptic fill-finish line at one of its European manufacturing sites, expanding CDMO capacity for vials, pre-filled syringes and cartridges in compliance with EU GMP Annex 1 (2023).',
    route: 'cdmo',
    articleId: 'news-4',
  },
  {
    tag: 'Research',
    date: 'March 10, 2025',
    title: 'AI-assisted lead optimization platform enters second generation.',
    excerpt: 'The next generation of Espandiar\'s computational chemistry platform integrates generative chemistry models with active-learning experimental loops, reducing lead-optimization cycle time for selected programs.',
    route: 'research',
    articleId: 'news-5',
  },
  {
    tag: 'Careers',
    date: 'February 24, 2025',
    title: 'Espandiar launches expanded postdoctoral fellowship program.',
    excerpt: 'A new cohort of two-year postdoctoral fellowships in computational biology, bioprocessing and formulation science is now open for applications, in partnership with leading academic medical centers.',
    route: 'careers',
    articleId: 'news-6',
  },
  {
    tag: 'Sustainability',
    date: 'February 12, 2025',
    title: 'Zero-liquid-discharge system commissioned at API facility.',
    excerpt: 'A new zero-liquid-discharge (ZLD) wastewater treatment system has been commissioned at Espandiar\'s largest API manufacturing facility, eliminating liquid effluent discharge and supporting water stewardship objectives.',
    route: 'sustainability',
    articleId: 'news-7',
  },
  {
    tag: 'Research',
    date: 'January 30, 2025',
    title: 'Preclinical data published in rare disease program.',
    excerpt: 'Peer-reviewed publication of preclinical pharmacology and toxicology data supporting an upcoming IND/CTA filing for a rare disease program. The data describe target engagement, dose–exposure–response and safety margins.',
    route: 'research',
    articleId: 'news-8',
  },
  {
    tag: 'Corporate',
    date: 'January 15, 2025',
    title: 'Espandiar joins international public-private pre-competitive consortium.',
    excerpt: 'Espandiar has joined a multi-company pre-competitive consortium focused on shared scientific and regulatory challenges in advanced therapy medicinal products (ATMPs), supporting broader industry progress in cell and gene therapy.',
    route: 'about',
    articleId: 'news-9',
  },
  {
    tag: 'Research',
    date: 'November 18, 2024',
    title: 'Rare disease gene therapy program ESP-4821 enters first-in-human trial.',
    excerpt: 'The first patient has been dosed in a Phase I/II trial of ESP-4821, a novel enzyme replacement therapy for a rare lysosomal storage disorder, with preclinical data showing a 3.8-fold increase in brain enzyme activity.',
    route: 'research',
    articleId: 'news-33',
  },
  {
    tag: 'Corporate',
    date: 'September 22, 2024',
    title: 'New manufacturing and R&D campus opens in Shanghai, China.',
    excerpt: 'A EUR 65 million campus in Zhangjiang Hi-Tech Park includes API manufacturing, formulation development, quality control and R&D capabilities, designed to meet NMPA, EU GMP and US FDA standards.',
    route: 'about',
    articleId: 'news-32',
  },
  {
    tag: 'CDMO',
    date: 'June 15, 2024',
    title: 'CDMO division expands into biologics contract manufacturing.',
    excerpt: 'Leveraging the newly qualified 2,000-litre single-use bioreactor facility in Berlin, Espandiar offers end-to-end biologics CDMO services including cell line development, upstream process optimization and fill-finish.',
    route: 'cdmo',
    articleId: 'news-31',
  },
  {
    tag: 'Corporate',
    date: 'March 12, 2024',
    title: 'EMA grants conditional marketing authorization for Esparib.',
    excerpt: 'Esparib (ESP-101) has received conditional EU marketing authorization for germline BRCA-mutated, HER2-negative advanced breast cancer, based on Phase II data showing a 41.4% objective response rate.',
    route: 'about',
    articleId: 'news-30',
  },
  {
    tag: 'Research',
    date: 'January 28, 2024',
    title: 'Positive Phase II data for ESP-101 presented at ASCO Annual Meeting.',
    excerpt: 'ESP-101 demonstrated a 41.4% ORR in HRD-positive advanced solid tumours, with median duration of response of 12.7 months. Data were published simultaneously in The Lancet Oncology.',
    route: 'research',
    articleId: 'news-29',
  },
  {
    tag: 'CDMO',
    date: 'September 10, 2023',
    title: 'First biologics manufacturing line qualified at Berlin campus.',
    excerpt: 'A 2,000-litre single-use bioreactor suite has been qualified for GMP manufacturing of monoclonal antibodies and recombinant proteins, inspected and approved by the German PEI.',
    route: 'cdmo',
    articleId: 'news-28',
  },
  {
    tag: 'Sustainability',
    date: 'May 22, 2023',
    title: 'Green chemistry initiative launched across API development programs.',
    excerpt: 'The Green Chemistry Initiative mandates PMI, E-factor and solvent recovery metrics at every project gate, with a transition from Class 1/2 ICH Q3C solvents to greener alternatives and adoption of biocatalysis.',
    route: 'sustainability',
    articleId: 'news-27',
  },
  {
    tag: 'Sustainability',
    date: 'January 18, 2023',
    title: 'Espandiar commits to science-aligned sustainability targets.',
    excerpt: 'SBTi-validated targets include net-zero Scope 1 and 2 emissions by 2035 and 50% absolute Scope 3 reduction by 2040. The "Green Blueprint 2035" strategy covers climate, water, circular economy and biodiversity.',
    route: 'sustainability',
    articleId: 'news-26',
  },
  {
    tag: 'CDMO',
    date: 'November 08, 2022',
    title: 'Second manufacturing site qualified in Hyderabad, India.',
    excerpt: 'The Genome Valley facility adds HPAPI manufacturing capabilities with operator isolation technology, OEL-based containment below 1 μg/m³, and approvals from EU, FDA, CDSCO, TGA and PMDA.',
    route: 'cdmo',
    articleId: 'news-25',
  },
  {
    tag: 'Corporate',
    date: 'September 20, 2021',
    title: 'First regulatory marketing authorization received in emerging market.',
    excerpt: 'Kenya\'s Pharmacy and Poisons Board approved Esparib for BRCA-mutated advanced ovarian cancer, based on Phase II data showing 42.3% ORR and 7.8-month median PFS.',
    route: 'about',
    articleId: 'news-24',
  },
  {
    tag: 'Corporate',
    date: 'April 14, 2021',
    title: 'Strategic research partnership with Dana-Farber Cancer Institute announced.',
    excerpt: 'A multi-year collaboration will use patient-derived organoids and GEMMs to evaluate drug combinations and biomarker strategies in precision oncology.',
    route: 'research',
    articleId: 'news-23',
  },
  {
    tag: 'Research',
    date: 'January 11, 2021',
    title: 'Biotechnology platform formally launched with monoclonal antibody pipeline.',
    excerpt: 'A dedicated Biotechnology division with a 100-billion-member phage display library and CHO cell line development platform has three antibody programs in lead optimization.',
    route: 'research',
    articleId: 'news-22',
  },
  {
    tag: 'Investors',
    date: 'October 05, 2022',
    title: 'Series B financing raises EUR 85 million.',
    excerpt: 'Co-led by Wellington Management and T. Rowe Price, the round brings total capital to EUR 120 million. Proceeds will fund Phase II ESP-101, two new FIH trials and platform investment.',
    route: 'investors',
    articleId: 'news-21',
  },
  {
    tag: 'CDMO',
    date: 'August 16, 2022',
    title: 'CDMO services division formally launched.',
    excerpt: 'End-to-end API development and manufacturing services now offered, from route scouting and process development through GMP manufacturing and regulatory support including DMF preparation.',
    route: 'cdmo',
    articleId: 'news-20',
  },
  {
    tag: 'Research',
    date: 'May 09, 2022',
    title: 'New R&D center opens in Cambridge, Massachusetts.',
    excerpt: 'A 1,200-square-metre facility in Kendall Square houses discovery biology, computational science and translational research, with 35 scientists and plans to grow to 80.',
    route: 'research',
    articleId: 'news-19',
  },
  {
    tag: 'CDMO',
    date: 'February 14, 2022',
    title: 'API manufacturing capacity doubled with new synthesis wing.',
    excerpt: 'EUR 18 million expansion at the Mumbai facility adds six glass-lined reactors (2,000–8,000 L), cryogenic capability and DCS automation, designed per ICH Q7 and EU GMP Part II.',
    route: 'cdmo',
    articleId: 'news-18',
  },
  {
    tag: 'Corporate',
    date: 'October 22, 2020',
    title: 'Espandiar supplies critical API intermediates for COVID-19 treatment.',
    excerpt: 'An EUR 8 million supply agreement with an international procurement agency leveraged the Mumbai facility to produce a critical antiviral intermediate, with process transfer completed in eight weeks.',
    route: 'about',
    articleId: 'news-17',
  },
  {
    tag: 'CDMO',
    date: 'August 10, 2020',
    title: 'Espandiar acquires API manufacturing facility in Mumbai, India.',
    excerpt: 'Acquisition of a fully operational API facility with CDSCO, FDA and EU GMP approvals, including 500–5,000 L reactors, hydrogenation suite and QC laboratory.',
    route: 'cdmo',
    articleId: 'news-16',
  },
  {
    tag: 'Research',
    date: 'March 15, 2020',
    title: 'First-in-human study initiated for ESP-101 in advanced solid tumours.',
    excerpt: 'Phase I dose-escalation study ESP-101-001 has dosed its first patient at five sites in Germany and the UK, using a modified 3+3 design with ctDNA pharmacodynamic biomarkers.',
    route: 'research',
    articleId: 'news-15',
  },
  {
    tag: 'Corporate',
    date: 'November 20, 2019',
    title: 'First regulatory engagement with EMA on clinical development plan.',
    excerpt: 'EMA scientific advice endorsed a biomarker-enriched Phase I design, confirmed CMC alignment with ICH Q6A and Q8(R2), and recommended ICH Q1A(R2) stability conditions.',
    route: 'about',
    articleId: 'news-14',
  },
  {
    tag: 'Research',
    date: 'July 08, 2019',
    title: 'First clinical candidate nominated for IND-enabling studies.',
    excerpt: 'ESP-101, a RAD51-ssDNA interaction inhibitor, was nominated as the first clinical candidate with 8 nM IC50, >65% oral bioavailability and synergy in HRD PDX models.',
    route: 'research',
    articleId: 'news-13',
  },
  {
    tag: 'Investors',
    date: 'February 25, 2019',
    title: 'Series A funding round raises EUR 28 million.',
    excerpt: 'Led by EQT Ventures with participation from Novo Holdings and Versant Ventures, the oversubscribed round provides 30 months of runway to advance the lead program through IND-enabling studies.',
    route: 'investors',
    articleId: 'news-12',
  },
  {
    tag: 'Corporate',
    date: 'November 12, 2018',
    title: 'First research laboratory opens in Berlin-Buch.',
    excerpt: 'An 800-square-metre facility at Berlin-Buch Biotech Park includes medicinal chemistry labs, BSL-2 cell biology suite, analytical development laboratory and GPU-accelerated molecular modelling cluster.',
    route: 'about',
    articleId: 'news-11',
  },
  {
    tag: 'Corporate',
    date: 'September 17, 2018',
    title: 'Espandiar Pharmaceuticals founded in Berlin.',
    excerpt: 'Co-founded by Dr. Lukas Hartmann and Dr. Priya Ramaswamy with EUR 4.2 million seed funding from Berlin angel investors and the BMBF GO-Bio programme. Initial team of 12 at Berlin Biotech Park.',
    route: 'about',
    articleId: 'news-10',
  },
]

const CATEGORIES: NewsItem['tag'][] = ['Research', 'Corporate', 'Investors', 'Sustainability', 'Careers', 'CDMO']

export function NewsPage() {
  const { navigate } = useRouter()
  const [filter, setFilter] = React.useState<NewsItem['tag'] | 'All'>('All')
  const [modalOpen, setModalOpen] = React.useState(false)
  const [activeArticle, setActiveArticle] = React.useState<ArticleData | null>(null)

  const openArticle = React.useCallback((articleId: string) => {
    const article = NEWS_ARTICLES[articleId]
    if (article) {
      setActiveArticle(article)
      setModalOpen(true)
    }
  }, [])

  const filtered = filter === 'All' ? ALL_NEWS : ALL_NEWS.filter((n) => n.tag === filter)

  return (
    <PageShell>
      <PageHero
        index="01"
        eyebrow="News & media"
        title="Latest from"
        highlight="Espandiar."
        lead="Announcements, research highlights, corporate news and program updates. For media inquiries, please contact our communications team through the Contact page."
      />

      {/* Featured + filter */}
      <Section tone="light">
        <SectionHeading
          index="02"
          eyebrow="Newsroom"
          title="Filter by category."
          highlight="Find what matters."
          lead="Use the filters below to navigate our newsroom by topic. Each article links to the most relevant Espandiar page for additional context."
        />

        <Reveal className="mt-10">
          <div className="flex flex-wrap items-center gap-2">
            <span className="mr-2 flex items-center gap-1.5 text-xs font-bold uppercase tracking-[0.14em] text-muted-foreground">
              <Filter className="h-3.5 w-3.5" /> Filter
            </span>
            <button
              onClick={() => setFilter('All')}
              className={`rounded-full px-4 py-2 text-xs font-bold uppercase tracking-[0.1em] transition ${
                filter === 'All'
                  ? 'bg-[#0d5d50] text-white dark:bg-[#8fb9ad] dark:text-[#0c1311]'
                  : 'bg-muted text-muted-foreground hover:bg-[#0d5d50]/10'
              }`}
            >
              All
            </button>
            {CATEGORIES.map((c) => (
              <button
                key={c}
                onClick={() => setFilter(c)}
                className={`rounded-full px-4 py-2 text-xs font-bold uppercase tracking-[0.1em] transition ${
                  filter === c
                    ? 'bg-[#0d5d50] text-white dark:bg-[#8fb9ad] dark:text-[#0c1311]'
                    : 'bg-muted text-muted-foreground hover:bg-[#0d5d50]/10'
                }`}
              >
                {c}
              </button>
            ))}
          </div>
        </Reveal>

        <div className="mt-10 grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filtered.map((n, i) => (
            <Reveal key={n.title} delay={(i % 3) * 0.08}>
              <button
                onClick={() => n.articleId ? openArticle(n.articleId) : (n.route && navigate(n.route))}
                className="group flex h-full w-full flex-col rounded-[26px] border border-border bg-card p-7 text-left card-hover"
              >
                <div className="flex items-center gap-3">
                  <Pill tone="emerald">
                    <Tag className="h-3 w-3" /> {n.tag}
                  </Pill>
                  <span className="ml-auto flex items-center gap-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground">
                    <Calendar className="h-3 w-3" /> {n.date}
                  </span>
                </div>
                <h3 className="mt-6 text-xl font-semibold tracking-[-0.03em]">{n.title}</h3>
                <p className="mt-4 flex-1 text-sm leading-6 text-muted-foreground">{n.excerpt}</p>
                <span className="mt-6 inline-flex items-center gap-1.5 text-xs font-bold text-[#0d5d50] dark:text-[#8fb9ad]">
                  Read more
                  <ArrowRight className="h-3.5 w-3.5 transition group-hover:translate-x-1" />
                </span>
              </button>
            </Reveal>
          ))}
        </div>

        {filtered.length === 0 && (
          <div className="mt-10 rounded-2xl border border-border bg-card p-10 text-center text-muted-foreground">
            No news in this category.
          </div>
        )}
      </Section>

      {/* Media contact */}
      <Section tone="dark">
        <div className="grid gap-8 lg:grid-cols-[1.2fr_0.8fr] lg:items-center">
          <Reveal>
            <Eyebrow tone="sage">Media relations</Eyebrow>
            <h2 className="mt-5 text-3xl font-semibold tracking-[-0.04em] sm:text-5xl">
              For journalists and analysts.
            </h2>
            <p className="mt-5 max-w-xl text-sm leading-6 text-white/70">
              Our communications team responds to media and analyst inquiries
              within one business day. Embargoed materials, executive
              interviews and site visits can be arranged on request.
            </p>
          </Reveal>
          <Reveal delay={0.1} className="flex flex-wrap gap-3 lg:justify-end">
            <LinkButton variant="light" onClick={() => navigate('contact')}>
              Media contact
              <ArrowRight className="h-4 w-4" />
            </LinkButton>
            <LinkButton variant="outline" className="text-white" onClick={() => navigate('investors')}>
              Investor relations
              <ArrowRight className="h-4 w-4" />
            </LinkButton>
          </Reveal>
        </div>
      </Section>

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