# Research Show Page Improvements

## Overview
Enhance the research paper detail page (`/show/{slug}`) with better UX for abstracts and actions.

**Templates**:
- `src/syndex/AcademicBundle/Resources/views/Research/show_elastic.html.twig` - Elasticsearch articles ✅ Updated
- `src/syndex/AcademicBundle/Resources/views/Research/show.html.twig` - Database articles ✅ Updated (MD button)
- `src/syndex/AcademicBundle/Resources/views/Research/show_external.html.twig` - External articles ⏳ Needs update

---

## Completed (March 2026)

> **Scope**: Items 1-5 are in `show_elastic.html.twig` only. Item 6 (Download MD) is in both templates.

### 1. Download/Share Buttons Redesign
- ✅ Made both buttons same size and inline in one row
- ✅ Gradient styling with hover effects
- ✅ Responsive layout

### 2. Abstract Tabbed Interface
- ✅ When both Arabic and English abstracts exist, show tabs to switch between them
- ✅ Single abstract shows without tabs
- ✅ RTL support for Arabic tab

### 3. Abstract Action Buttons
- ✅ **Copy button**: Copies abstract text to clipboard
- ✅ **Text-to-speech (TTS)**: Reads abstract aloud using Web Speech API
  - Detects language (ar/en)
  - Shows play/stop toggle
  - Displays message if Arabic voice not installed on user's system
- ✅ **Expand/Collapse**: For long abstracts (>220px height)
  - Gradient fade overlay when collapsed
  - "Show more" / "Show less" toggle

### 4. Translations Added
- `translations/Academia.ar.yml`: copy.success, copy.failed, tts.not_supported
- `translations/Academia.en.yml`: copy.success, copy.failed, tts.not_supported

### 5. Collapsible Keywords
- ✅ Show first 6 tags by default
- ✅ "+X المزيد" button to expand remaining tags
- ✅ "عرض أقل" to collapse back
- ✅ Smooth toggle with chevron icon

### 6. Download Markdown (MD) Button ✅ (March 22, 2026)
Added "Extract MD" button for PDF→Markdown conversion using Mistral OCR.

**Implementation:**
- `src/Service/ResearchMarkdownService.php` - Core service for extraction and ES storage
- `src/Controller/ResearchMarkdownController.php` - API endpoints
- `src/Message/ProcessResearchMarkdown.php` + Handler - Async processing
- `scripts/add_content_md_field.sh` - ES mapping update
- Both `show.html.twig` and `show_elastic.html.twig` templates updated

**API Endpoints:**
- `GET /api/research-markdown/status/{id}` - Check if MD available, user has credits
- `POST /api/research-markdown/extract` - Start extraction (costs 2 credits/page)
- `GET /api/research-markdown/download/{id}` - Download as .md file
- `GET /api/research-markdown/content/{id}` - Get raw markdown content

**Features:**
- Uses existing MistralOcrService.extractWithImages() already deployed for OCR
- Caches extracted markdown in ES `content_md` field
- Shows progress spinner during extraction
- Requires AI credits (PlaygroundSubscription), NOT PDF subscription
- **Conversion funnel**: Button visible to ALL users (not just logged-in with credits)
  - Not logged in → redirects to login page
  - Logged in without credits → redirects to subscription page
  - Logged in with credits → performs extraction
- **Double-click protection**: Cache-based lock (10 min TTL) prevents duplicate job dispatch
- Second click while processing returns `status: 'processing'` without charging credits

**Bug Fixes Applied:**
- Fixed `useCredits()` method name (was `deductCredits()`)
- Fixed jQuery `.data()` type coercion (use `== 1` not `=== '1'`)
- Fixed route name `app_login` (was `fos_user_security_login`)

**Note:** Research pages are at `/show/{slug}` NOT `/research/{slug}`.

---

## Search Results UI Improvements

### Current Issues
1. **Dense layout** - Everything looks the same weight, hard to scan quickly
2. **No author names** - Important metadata missing from results
3. **Keywords too prominent** - Take up more visual space than the abstract
4. **"المزيد.." hard to find** - Small, easy to miss
5. **No search term highlighting** - Hard to see why result matched
6. **No quick actions** - Can't save/cite without clicking into paper
7. **No visual distinction** - All results look identical

### Quick Wins (✅ Completed March 11, 2026)
- [x] **Highlight search terms** in title/abstract with yellow background
- [x] **Make keywords collapsible** (like show page - first 4, +X more)
- [x] **Larger "المزيد" button** - styled toggle with count display
- [ ] **Add author names** below title

**Implementation Details:**
- Added `.search-highlight-target` class to titles and abstracts in research_brief.html.twig
- JavaScript in all.html.twig highlights matching terms from search query
- Keywords show first 4, with "+X المزيد" toggle button
- New CSS classes: `.search-highlight`, `.keyword-toggle-btn`, `.research-keyword`

### Medium Effort
- [ ] **Quick action buttons on search results** - Inline buttons for:
  - Download (📥) - Direct PDF/DOCX download
  - Add to favorites (⭐) - Save to user's library (requires login)
  - Cite (📋) - Modal with citation formats (BibTeX, APA, MLA, Chicago, Harvard)
- [ ] **Add card-style layout** with subtle borders/shadows
- [ ] **Visual indicator for article type** - Paper icon, thesis icon, etc.
- [ ] **Show download/view stats** more prominently

### Larger Features
- [ ] **Thumbnail/preview image** for papers with figures
- [ ] **AI-generated summary snippet** that's more relevant to search
- [ ] **"Similar papers" quick link** for each result

---

## Known Limitations

### TTS Arabic Voice
- Web Speech API requires Arabic TTS voice installed on user's OS
- Windows users need to install Arabic language pack with TTS enabled
- Alert shown with instructions if Arabic voice missing

---

## Next Up: Citation Generator

### Implementation: Client-side JavaScript (Option A)
- Generate citations in browser using article metadata already on the page
- No server calls, instant
- Simple dropdown with format selection + copy button
- ~100 lines of JS
- Zero dependencies

### Supported Formats
1. **BibTeX** - For LaTeX users
2. **APA (7th ed.)** - Psychology, social sciences
3. **MLA (9th ed.)** - Humanities
4. **Chicago** - History, general
5. **Harvard** - Common in UK/Australia

### UI Design
```
┌─────────────────────────────────────────────────────────┐
│  [📄 Download]  [🔗 Share]  [📋 Cite ▼]                 │
│                                    ├── BibTeX           │
│                                    ├── APA (7th ed.)    │
│                                    ├── MLA (9th ed.)    │
│                                    ├── Chicago          │
│                                    └── Harvard          │
└─────────────────────────────────────────────────────────┘
```

When user clicks a format, show modal:
```
┌─────────────────────────────────────────────────────────┐
│  Citation - APA (7th ed.)                          [X]  │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  Author, A. A., & Author, B. B. (2024). Title of the   │
│  article. Journal Name, 12(3), 45-67.                  │
│  https://doi.org/10.1234/example                       │
│                                                         │
├─────────────────────────────────────────────────────────┤
│                              [📋 Copy to Clipboard]     │
└─────────────────────────────────────────────────────────┘
```

### Required Metadata
From ES document / page data:
- `title` (Arabic and/or English)
- `authors` (array of names)
- `year` / `publication_date`
- `journal_name` / `publisher`
- `volume`, `issue`, `pages` (if available)
- `doi` (if available)
- `url` (page URL as fallback)

### Tasks
- [ ] Add "Cite" button next to Download/Share
- [ ] Create dropdown menu with format options
- [ ] Build citation modal component
- [ ] Implement citation generators for each format
- [ ] Add copy to clipboard functionality
- [ ] Add translations (ar/en)
- [ ] Test with various article types

---

## TODO: Apply to Other Templates

> **Note**: Focusing on `show_elastic.html.twig` only. Plan is to eventually converge all articles to use ES template, so DB template updates are deferred.

### show.html.twig (Database articles) - PARTIAL
- [x] Download MD button added (March 22, 2026)
- [ ] Abstract tabs, TTS, expand/collapse - Will be deprecated once all articles are in ES

### show_external.html.twig (External articles) - DEFERRED
- [ ] Will be deprecated once all articles are in ES

---

## Future Ideas

### High Priority
- [ ] **PDF inline viewer**: Embed PDF.js for in-browser reading
- [ ] **Citation generator**: Generate BibTeX, APA, MLA, Chicago citations
- [ ] **Social share buttons**: Twitter, LinkedIn, Facebook, WhatsApp
- [ ] **Related papers**: Show similar papers based on tags/keywords

### Medium Priority
- [ ] **Annotation/highlighting**: Allow users to highlight text (requires auth)
- [ ] **Reading list**: "Save for later" functionality
- [ ] **Print-friendly view**: Optimized print CSS
- [ ] **Translation toggle**: Auto-translate abstract using AI

### Low Priority
- [ ] **Audio summary**: AI-generated audio summary of paper
- [ ] **Accessibility**: Screen reader improvements, keyboard navigation
- [ ] **Dark mode**: Theme toggle for late-night reading

---

## Technical Notes

### CSS Classes
- `.action-btn`, `.action-btn-download`, `.action-btn-share` - Main action buttons
- `.abstract-tabs-container`, `.abstract-tab` - Tab navigation
- `.abstract-panel`, `.abstract-text` - Abstract content
- `.abstract-action-btn`, `.copy-btn`, `.tts-btn` - Abstract action buttons
- `.expand-toggle`, `.collapsed` - Expand/collapse functionality

### JavaScript
- Tab switching via jQuery click handlers
- Copy uses Clipboard API with fallback to `execCommand`
- TTS uses Web Speech API (`SpeechSynthesisUtterance`)
- Voice caching with `onvoiceschanged` event handler

### Data Attributes
- `data-full-text` - Clean text for copy (HTML entities for special chars)
- `data-target` - Target element ID for actions
- `data-lang` - Language code for TTS (ar/en)
