# Znakopis Page - Bug Fixes and Feature Additions

## Overview
This document outlines the bugs to fix and features to add to the Znakopis page for document and sentence management.

---

## 🐛 BUG FIXES

### Bug 1: Sentence Deletion Error
**Issue:** When loading a document and trying to delete a sentence, an error occurs and the sentence is not deleted.

**Root Cause:** The API endpoint path is incorrect in the frontend.
- Frontend calls: `/api/sentences/${sentenceId}` (via `documentApi.deleteSentence()`)
- Backend expects: `/api/sentences/:sentenceId` 
- Backend route is registered at: `app.use('/api', sentenceRoutes)` in `server.ts`
- This means the actual endpoint is: `/api/sentences/:sentenceId` ✅

**Investigation Needed:**
1. Check browser console for the exact error message
2. Verify the sentence ID is being passed correctly
3. Check if authentication is working properly
4. Verify the backend route is handling the DELETE request correctly

**Files to Check:**
- `packages/frontend/src/lib/documentApi.ts` - Line 121-123 (deleteSentence method)
- `packages/backend/src/routes/sentences.ts` - Line 169-199 (DELETE endpoint)
- `packages/frontend/src/pages/Znakopis.tsx` - Line 129-144 (handleDeleteSentence)
- `packages/frontend/src/components/znakopis/DocumentPanel.tsx` - Line 119-125 (delete button)

**Fix Steps:**
1. Add error logging to identify the exact issue
2. Verify the sentence ID format (should be UUID string)
3. Ensure the DELETE request includes authentication credentials
4. Test the endpoint directly to confirm it works
5. Add better error handling and user feedback

---

### Bug 2: Incorrect API Endpoint for Creating Pages
**Issue:** The frontend uses wrong endpoint path for creating pages.

**Current State:**
- Frontend calls: `/api/${documentId}/pages` (Line 88 in documentApi.ts)
- Backend expects: `/api/documents/:documentId/pages` (Line 205 in sentences.ts)

**Fix Required:**
- Update `packages/frontend/src/lib/documentApi.ts` line 88
- Change from: `api.post(\`/api/${documentId}/pages\`, { title })`
- Change to: `api.post(\`/api/documents/${documentId}/pages\`, { title })`

---

### Bug 3: Incorrect API Endpoint for Creating Sentences
**Issue:** The frontend uses wrong endpoint path for creating sentences.

**Current State:**
- Frontend calls: `/api/${documentId}/pages/${pageIndex}/sentences` (Line 99 in documentApi.ts)
- Backend expects: `/api/documents/:documentId/pages/:pageIndex/sentences` (Line 11 in sentences.ts)

**Fix Required:**
- Update `packages/frontend/src/lib/documentApi.ts` line 99
- Change from: `api.post(\`/api/${documentId}/pages/${pageIndex}/sentences\`, data)`
- Change to: `api.post(\`/api/documents/${documentId}/pages/${pageIndex}/sentences\`, data)`

---

## ✨ NEW FEATURES

### Feature 1: Delete Document Functionality
**Description:** Add ability to delete documents from the Znakopis page.

**Backend:** Already implemented ✅
- Endpoint: `DELETE /api/documents/:id` (Line 236 in documents.ts)
- Method: `documentApi.deleteDocument(id)` already exists (Line 82 in documentApi.ts)

**Frontend Changes Needed:**

1. **Update DocumentPanel Component** (`packages/frontend/src/components/znakopis/DocumentPanel.tsx`):
   - Add `onDeleteDocument` prop to interface (Line 6-15)
   - Add delete button in the document info section (around Line 56-65)
   - Use Trash2 icon from lucide-react (already imported)
   - Add confirmation dialog before deletion

2. **Update Znakopis Page** (`packages/frontend/src/pages/Znakopis.tsx`):
   - Add `handleDeleteDocument` function (similar to handleDeleteSentence)
   - Pass handler to DocumentPanel component
   - After deletion:
     - Clear selectedDocument state
     - Reload documents list
     - Show success toast
   - Handle errors with error toast

3. **UI/UX Considerations:**
   - Add confirmation dialog: "Jeste li sigurni da želite obrisati ovaj dokument?"
   - Show document title in confirmation
   - Disable delete button while deleting (loading state)
   - Clear current tokens if deleting the selected document

---

### Feature 2: Edit Document Name
**Description:** Allow users to edit document title and description.

**Backend:** Already implemented ✅
- Endpoint: `PATCH /api/documents/:id` (Line 174 in documents.ts)
- Method: `documentApi.updateDocument(id, data)` already exists (Line 76 in documentApi.ts)

**Frontend Changes Needed:**

1. **Update DocumentPanel Component** (`packages/frontend/src/components/znakopis/DocumentPanel.tsx`):
   - Add `onUpdateDocument` prop to interface
   - Add edit mode state for document title and description
   - Add edit button (Pencil icon from lucide-react)
   - When in edit mode:
     - Show input field for title
     - Show textarea for description
     - Show Save and Cancel buttons
   - When not in edit mode:
     - Show title and description as text
     - Show edit button

2. **Update Znakopis Page** (`packages/frontend/src/pages/Znakopis.tsx`):
   - Add `handleUpdateDocument` function
   - Accept documentId, title, and description
   - Call `documentApi.updateDocument()`
   - Reload document after update
   - Update documents list
   - Show success/error toast

3. **UI/UX Considerations:**
   - Inline editing for better UX
   - Validate title is not empty
   - Show loading state while saving
   - Revert changes on cancel
   - Auto-focus title input when entering edit mode

---

### Feature 3: Name Document on Creation
**Description:** Allow users to provide a custom name when creating a new document instead of auto-generated name.

**Current Behavior:**
- Auto-generates name: `Dokument ${new Date().toLocaleDateString('hr-HR')}`
- Creates with description: "Novi dokument"

**Proposed Changes:**

1. **Add Document Creation Dialog:**
   - Create new component: `CreateDocumentDialog.tsx`
   - Use Dialog component from UI library
   - Include:
     - Title input field (required)
     - Description textarea (optional)
     - Create and Cancel buttons

2. **Update Znakopis Page** (`packages/frontend/src/pages/Znakopis.tsx`):
   - Add state for dialog open/closed
   - Modify "Novi dokument" button to open dialog
   - Update `handleSaveDocument`:
     - If no document selected, check if user wants to create new or use dialog
     - Option 1: Always show dialog for new documents
     - Option 2: Show dialog only when clicking "Novi dokument", auto-create when saving first sentence
   - Pass document data from dialog to createDocument API

3. **Alternative Approach (Simpler):**
   - Add inline form in DocumentPanel when no document is selected
   - Show title and description inputs
   - First save creates document with provided info
   - If fields empty, use default values

4. **UI/UX Considerations:**
   - Default title could be: "Novi dokument" (user can change)
   - Placeholder for description: "Dodajte opis dokumenta..."
   - Validate title is not empty
   - Show character count for title (max 255)

---

## 📋 IMPLEMENTATION CHECKLIST

### Phase 1: Bug Fixes (Priority: HIGH)
- [ ] Fix API endpoint for creating pages (documentApi.ts line 88)
- [ ] Fix API endpoint for creating sentences (documentApi.ts line 99)
- [ ] Debug and fix sentence deletion error
  - [ ] Add console logging to identify error
  - [ ] Verify authentication is working
  - [ ] Test endpoint directly
  - [ ] Fix any issues found
  - [ ] Add better error handling

### Phase 2: Delete Document Feature (Priority: HIGH)
- [ ] Add onDeleteDocument prop to DocumentPanel interface
- [ ] Add delete button to DocumentPanel UI
- [ ] Implement confirmation dialog
- [ ] Add handleDeleteDocument function in Znakopis page
- [ ] Test deletion flow
- [ ] Verify state updates correctly after deletion

### Phase 3: Edit Document Name (Priority: MEDIUM)
- [ ] Add onUpdateDocument prop to DocumentPanel interface
- [ ] Add edit mode state to DocumentPanel
- [ ] Implement inline editing UI (title and description)
- [ ] Add edit/save/cancel buttons
- [ ] Add handleUpdateDocument function in Znakopis page
- [ ] Add validation for title
- [ ] Test edit flow
- [ ] Verify state updates correctly after edit

### Phase 4: Name Document on Creation (Priority: MEDIUM)
- [ ] Decide on approach (dialog vs inline form)
- [ ] Create CreateDocumentDialog component (if using dialog approach)
- [ ] Update "Novi dokument" button behavior
- [ ] Add form validation
- [ ] Update handleSaveDocument or create separate handler
- [ ] Test document creation with custom name
- [ ] Ensure backward compatibility (auto-name if not provided)

---

## 🧪 TESTING REQUIREMENTS

### For Each Bug Fix:
1. Test the specific scenario that was failing
2. Verify error messages are clear and helpful
3. Test edge cases (empty data, invalid IDs, etc.)
4. Verify authentication is required

### For Each Feature:
1. Test happy path (normal usage)
2. Test validation (empty fields, too long text, etc.)
3. Test error handling (network errors, server errors)
4. Test UI states (loading, success, error)
5. Test on different screen sizes (responsive design)
6. Verify Croatian language text is correct

---

## 📝 NOTES FOR IMPLEMENTATION

1. **Consistency:** Follow existing patterns in the codebase
2. **Error Handling:** Always show user-friendly error messages in Croatian
3. **Loading States:** Show loading indicators for async operations
4. **Confirmation Dialogs:** Use for destructive actions (delete)
5. **Toast Messages:** Use Sonner toast for feedback (already imported)
6. **Icons:** Use lucide-react icons (already in use)
7. **Styling:** Use existing Tailwind classes for consistency
8. **TypeScript:** Ensure all types are properly defined
9. **API Calls:** Always handle errors with try-catch
10. **State Management:** Update all relevant state after API calls

---

## 🔍 FILES TO MODIFY

### Bug Fixes:
1. `packages/frontend/src/lib/documentApi.ts` - Fix API endpoints
2. `packages/frontend/src/pages/Znakopis.tsx` - Improve error handling
3. `packages/backend/src/routes/sentences.ts` - Verify DELETE endpoint (if needed)

### Features:
1. `packages/frontend/src/components/znakopis/DocumentPanel.tsx` - Add delete and edit UI
2. `packages/frontend/src/pages/Znakopis.tsx` - Add handlers for delete and edit
3. `packages/frontend/src/components/znakopis/CreateDocumentDialog.tsx` - New file (if using dialog approach)
4. `packages/frontend/src/components/ui/dialog.tsx` - May need to create if not exists

---

## ⚠️ IMPORTANT CONSIDERATIONS

1. **Data Loss Prevention:** Always confirm before deleting documents
2. **Concurrent Edits:** Consider what happens if document is edited while viewing
3. **Permissions:** Verify user owns document before allowing edit/delete
4. **Validation:** Ensure title is not empty and within length limits
5. **Accessibility:** Ensure all interactive elements are keyboard accessible
6. **Mobile:** Test on mobile devices for touch interactions

